Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/GraphModel.swift3// Description: View model of the knowledge graph screen: the seven server views, the layout (computed off the main4// actor), pan / zoom / selection, typed relations (create, accept, reject, edit, delete — online only), and5// the insights panel (deterministic analysis is free; the AI analysis is an explicit, paid action).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import Foundation11import Observation12import SPNotesAPI13import SPNotesSync1415/// A neighbour of a node: the other end and the edge that links them.16public struct GraphNeighbour: Identifiable, Sendable, Equatable {17 public var node: GraphNode18 public var edge: GraphEdge19 /// True when the edge goes from the focused node to this one.20 public var outgoing: Bool21 public var id: String { edge.id + "|" + node.id }22}2324/// What the relation form edits.25public struct GraphRelationForm: Sendable, Equatable {26 /// nil = a new relation.27 public var relationId: String?28 public var fromId: String29 public var toId: String30 public var relType: String31 public var note: String3233 public init(relationId: String? = nil, fromId: String, toId: String, relType: String = RelationType.related, note: String = "") {34 self.relationId = relationId35 self.fromId = fromId36 self.toId = toId37 self.relType = relType38 self.note = note39 }40}4142@Observable @MainActor43public final class GraphModel {44 // MARK: state4546 public private(set) var view: String47 /// The page the `local` and `project` views are about.48 public private(set) var focusPageId: String?49 public var includeSuggestions = true50 public var hideOrphans = false5152 public private(set) var graph: KnowledgeGraph?53 /// Unit-box position of every node of `graph`.54 public private(set) var positions: [String: CGPoint] = [:]55 public private(set) var phase: LoadPhase = .idle56 public private(set) var freshness: Freshness?57 /// The failure of the last write (relation, insight); the screen shows it as a calm banner.58 public var actionFailure: FeatureFailure?59 public private(set) var isWorking = false6061 public var viewport = GraphViewport()62 public private(set) var selectedNodeId: String?63 public private(set) var selectedEdgeId: String?64 /// Increases each time a new graph is laid out: the screen replays the edge-draw motion.65 public private(set) var layoutGeneration = 06667 public private(set) var insights: GraphInsights?68 public private(set) var insightsPhase: LoadPhase = .idle69 public private(set) var insightsFreshness: Freshness?70 public private(set) var lastRun: InsightRunResult?7172 /// The relation being created or edited (the screen presents the form while non-nil).73 public var form: GraphRelationForm?7475 private let repository: GraphRepository76 private weak var router: (any FeatureRouter)?77 private let now: @Sendable () -> Date78 private var loadToken = 07980 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, view: String = GraphView.global, pageId: String? = nil,81 now: @escaping @Sendable () -> Date = { Date() }) {82 repository = repositories.graph83 self.router = router84 self.view = GraphView.all.contains(view) ? view : GraphView.global85 focusPageId = pageId86 self.now = now87 }8889 // MARK: derived9091 public var nodes: [GraphNode] { graph?.nodes ?? [] }92 public var edges: [GraphEdge] { graph?.edges ?? [] }93 public var selectedNode: GraphNode? { nodes.first { $0.id == selectedNodeId } }94 public var selectedEdge: GraphEdge? { edges.first { $0.id == selectedEdgeId } }95 public var isEmpty: Bool { graph?.nodes.isEmpty ?? true }9697 /// `local` and `project` need a page; without one the screen asks the user to pick a node first.98 public var needsFocus: Bool { (view == GraphView.local || view == GraphView.project) && focusPageId == nil }99100 /// The node the compact layout is centred on: the selection, else the server's centre, else the best-connected node.101 public var focusNode: GraphNode? {102 if let selectedNode { return selectedNode }103 if let center = graph?.center, let node = nodes.first(where: { $0.id == center }) { return node }104 return nodes.max { ($0.degree ?? 0, $1.id) < ($1.degree ?? 0, $0.id) }105 }106107 public func node(_ id: String) -> GraphNode? { nodes.first { $0.id == id } }108109 public func neighbours(of nodeId: String) -> [GraphNeighbour] {110 var result: [GraphNeighbour] = []111 for edge in edges {112 if edge.source == nodeId, let other = node(edge.target) { result.append(GraphNeighbour(node: other, edge: edge, outgoing: true)) }113 else if edge.target == nodeId, let other = node(edge.source) { result.append(GraphNeighbour(node: other, edge: edge, outgoing: false)) }114 }115 return result116 }117118 /// AI-made and not yet decided: must be shown as a suggestion, with accept / reject.119 public nonisolated static func isSuggestion(_ edge: GraphEdge) -> Bool { edge.status == DecisionStatus.suggested }120 public nonisolated static func isAI(_ edge: GraphEdge) -> Bool { edge.origin == KnowledgeOrigin.ai || edge.kind == GraphEdgeKind.aiSuggested }121 /// Only a relation of kind `relation` (view kind `typed`) with a real row can be edited or deleted.122 public nonisolated static func isEditable(_ edge: GraphEdge) -> Bool { edge.kind == GraphEdgeKind.typed && !edge.isSynthetic }123 /// A stored edge awaiting a decision can be accepted or rejected.124 public nonisolated static func isDecidable(_ edge: GraphEdge) -> Bool { !edge.isSynthetic && isSuggestion(edge) && (edge.kind == GraphEdgeKind.typed || edge.kind == GraphEdgeKind.aiSuggested) }125 /// Relations can link pages, references and concepts.126 public nonisolated static func canRelate(_ node: GraphNode) -> Bool {127 [GraphNodeKind.page, GraphNodeKind.database, GraphNodeKind.research, GraphNodeKind.row, GraphNodeKind.canvas, GraphNodeKind.reference, GraphNodeKind.concept].contains(node.kind)128 }129130 nonisolated static func entityKind(_ node: GraphNode) -> String {131 switch node.kind {132 case GraphNodeKind.reference: return GraphEntityKind.reference133 case GraphNodeKind.concept: return GraphEntityKind.concept134 default: return GraphEntityKind.page135 }136 }137138 // MARK: loading139140 public var query: GraphQuery {141 GraphQuery(view: view, pageId: (view == GraphView.local || view == GraphView.project) ? focusPageId : nil,142 includeSuggestions: includeSuggestions, hideOrphans: hideOrphans)143 }144145 public func load() async {146 guard !needsFocus else {147 graph = nil148 positions = [:]149 phase = .loaded150 return151 }152 loadToken += 1153 let token = loadToken154 phase = .loading155 do {156 let cached = try await repository.view(query)157 let graph = cached.value158 let ids = graph.nodes.map(\.id)159 let pairs = graph.edges.map { ($0.source, $0.target) }160 let layout = await GraphForceLayout.layoutInBackground(nodes: ids, edges: pairs, options: .init(seed: GraphForceLayout.seed(for: ids)))161 guard token == loadToken else { return }162 self.graph = graph163 positions = layout164 freshness = Freshness(cached)165 if let selectedNodeId, graph.nodes.contains(where: { $0.id == selectedNodeId }) == false { self.selectedNodeId = nil }166 if let selectedEdgeId, graph.edges.contains(where: { $0.id == selectedEdgeId }) == false { self.selectedEdgeId = nil }167 layoutGeneration += 1168 phase = .loaded169 } catch {170 guard token == loadToken else { return }171 phase = .failed(FeatureFailure(error))172 }173 }174175 public func setView(_ newView: String) async {176 guard GraphView.all.contains(newView), newView != view else { return }177 if (newView == GraphView.local || newView == GraphView.project), focusPageId == nil {178 // Use what the user is looking at: the selected page, else the centre of the current view.179 if let node = selectedNode ?? focusNode, Self.entityKind(node) == GraphEntityKind.page { focusPageId = node.entityUUID }180 }181 view = newView182 viewport.reset()183 await load()184 }185186 /// Makes a page the subject of the `local` / `project` views (and reloads when one of them is shown).187 public func focus(pageId: String) async {188 focusPageId = pageId189 if view == GraphView.local || view == GraphView.project { await load() }190 }191192 public func setIncludeSuggestions(_ value: Bool) async {193 guard value != includeSuggestions else { return }194 includeSuggestions = value195 await load()196 }197198 public func setHideOrphans(_ value: Bool) async {199 guard value != hideOrphans else { return }200 hideOrphans = value201 await load()202 }203204 // MARK: selection and gestures205206 public func select(nodeId: String?) {207 selectedNodeId = nodeId208 if nodeId != nil { selectedEdgeId = nil }209 }210211 public func select(edgeId: String?) {212 selectedEdgeId = edgeId213 }214215 /// A tap in the canvas: selects the node under the point, or clears the selection.216 public func tap(at location: CGPoint, in size: CGSize) {217 select(nodeId: viewport.hitTest(location, positions: positions, in: size))218 }219220 public func pan(by translation: CGSize) { viewport.pan(by: translation) }221 public func zoom(by factor: CGFloat, anchor: CGPoint, in size: CGSize) { viewport.zoom(by: factor, anchor: anchor, in: size) }222 public func resetViewport() { viewport.reset() }223224 /// Opens the selected (or given) node in the host app.225 public func open(_ node: GraphNode) {226 switch node.kind {227 case GraphNodeKind.database: router?.openDatabase(id: node.entityUUID)228 case GraphNodeKind.canvas: router?.openCanvas(pageId: node.entityUUID)229 case GraphNodeKind.page, GraphNodeKind.research, GraphNodeKind.row: router?.openPage(id: node.entityUUID, blockId: nil)230 default: break // references, concepts, attachments and tags have no page of their own231 }232 }233234 public nonisolated static func canOpen(_ node: GraphNode) -> Bool {235 [GraphNodeKind.database, GraphNodeKind.canvas, GraphNodeKind.page, GraphNodeKind.research, GraphNodeKind.row].contains(node.kind)236 }237238 // MARK: relations (online only)239240 public func beginRelation(from node: GraphNode, to other: GraphNode? = nil) {241 actionFailure = nil242 form = GraphRelationForm(fromId: node.id, toId: other?.id ?? "")243 }244245 public func beginEditing(_ edge: GraphEdge) {246 guard Self.isEditable(edge) else { return }247 actionFailure = nil248 form = GraphRelationForm(relationId: edge.id, fromId: edge.source, toId: edge.target, relType: edge.relType ?? RelationType.related, note: edge.note ?? "")249 }250251 /// The nodes a relation from `fromId` may point to.252 public func relationTargets(for fromId: String) -> [GraphNode] {253 nodes.filter { $0.id != fromId && Self.canRelate($0) }.sorted { KnowledgeVocabulary.title($0.title).localizedCaseInsensitiveCompare(KnowledgeVocabulary.title($1.title)) == .orderedAscending }254 }255256 /// Saves `form`: creates the relation or patches type / note. Returns true on success (the form is then closed).257 @discardableResult258 public func submitForm() async -> Bool {259 guard let form else { return false }260 if let relationId = form.relationId {261 let note: PatchValue<String> = form.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? .null : .value(form.note)262 return await write { _ = try await self.repository.update(relationId: relationId, RelationChanges(relType: form.relType, note: note)) } then: { self.form = nil }263 }264 guard let from = node(form.fromId), let to = node(form.toId) else {265 actionFailure = FeatureFailure(kind: .other, message: L("Choisissez la cible de la relation."))266 return false267 }268 let note = form.note.trimmingCharacters(in: .whitespacesAndNewlines)269 let draft = RelationDraft(fromId: from.entityUUID, toId: to.entityUUID, relType: form.relType, sourceKind: Self.entityKind(from), targetKind: Self.entityKind(to),270 note: note.isEmpty ? nil : note)271 return await write { _ = try await self.repository.createRelation(draft) } then: { self.form = nil }272 }273274 @discardableResult275 public func accept(_ edge: GraphEdge) async -> Bool {276 guard Self.isDecidable(edge) else { return false }277 return await write { _ = try await self.repository.accept(relationId: edge.id) }278 }279280 @discardableResult281 public func reject(_ edge: GraphEdge) async -> Bool {282 guard Self.isDecidable(edge) else { return false }283 return await write { _ = try await self.repository.reject(relationId: edge.id) }284 }285286 @discardableResult287 public func delete(_ edge: GraphEdge) async -> Bool {288 guard Self.isEditable(edge) else { return false }289 return await write { try await self.repository.deleteRelation(id: edge.id) } then: { if self.selectedEdgeId == edge.id { self.selectedEdgeId = nil } }290 }291292 private func write(_ work: @escaping () async throws -> Void, then: (() -> Void)? = nil) async -> Bool {293 guard !isWorking else { return false }294 isWorking = true295 actionFailure = nil296 defer { isWorking = false }297 do {298 try await work()299 then?()300 await load()301 return true302 } catch {303 let failure = FeatureFailure(error)304 actionFailure = failure.code == "relation_exists" ? FeatureFailure(kind: .server, message: L("Cette relation existe déjà entre ces deux éléments."), code: failure.code) : failure305 return false306 }307 }308309 // MARK: insights310311 public func loadInsights() async {312 insightsPhase = .loading313 do {314 let cached = try await repository.insights(InsightQuery(status: InsightStatus.suggested))315 insights = cached.value316 insightsFreshness = Freshness(cached)317 insightsPhase = .loaded318 } catch {319 insightsPhase = .failed(FeatureFailure(error))320 }321 }322323 /// The deterministic analysis (clusters, recurring topics, duplicates): free, done in the request.324 @discardableResult325 public func runDeterministicInsights() async -> Bool {326 await run(.deterministic)327 }328329 /// The AI analysis (contradictions, open questions, concept suggestions): **one paid job** — only from the330 /// explicit, labelled button. Its findings arrive later as suggestions.331 @discardableResult332 public func runAIInsights() async -> Bool {333 await run(InsightRunRequest(mode: InsightRunMode.ai))334 }335336 private func run(_ request: InsightRunRequest) async -> Bool {337 guard !isWorking else { return false }338 isWorking = true339 actionFailure = nil340 defer { isWorking = false }341 do {342 lastRun = try await repository.runInsights(request)343 await loadInsights()344 return true345 } catch {346 actionFailure = FeatureFailure(error)347 return false348 }349 }350351 @discardableResult352 public func decide(_ insight: KnowledgeInsight, accept: Bool) async -> Bool {353 guard !isWorking else { return false }354 isWorking = true355 actionFailure = nil356 defer { isWorking = false }357 do {358 _ = try await repository.decideInsight(id: insight.id, status: accept ? InsightStatus.accepted : InsightStatus.dismissed)359 insights?.insights.removeAll { $0.id == insight.id }360 await loadInsights()361 if accept, insight.kind == InsightKind.contradiction { await load() } // accepting it records a relation362 return true363 } catch {364 actionFailure = FeatureFailure(error)365 return false366 }367 }368369 public func openPages(of insight: KnowledgeInsight) {370 guard let first = insight.pageIds.first else { return }371 router?.openPage(id: first, blockId: insight.blockIds.first)372 }373374 public func openPage(id: String, blockId: String? = nil) { router?.openPage(id: id, blockId: blockId) }375376 /// What the last run answered, in words.377 public var lastRunSummary: String? {378 guard let lastRun else { return nil }379 var parts: [String] = []380 if let deterministic = lastRun.deterministic { parts.append(LF("%lld constat(s) ajouté(s) sur %lld examinés", deterministic.created, deterministic.considered)) }381 if lastRun.queued { parts.append(L("Analyse IA en file d'attente : ses constats arriveront comme suggestions.")) }382 else if lastRun.mode != InsightRunMode.deterministic {383 parts.append(lastRun.reason.map { LF("Analyse IA non lancée (%@).", $0) } ?? L("Analyse IA non lancée."))384 }385 return parts.isEmpty ? nil : parts.joined(separator: " · ")386 }387}388