Report index and reload errors instead of empty results !463

merged merged by cmc on 2026-11-22 19:16 UTC · krz/orgstar:issue-214-index-errors into main

13 files changed, +179 −62

Layout: unified · split

Sources/OrgApp/DenoteSequenceActions.swift +4 −1
@@ -1,5 +1,6 @@
11import Foundation
22import OrgCore
3import OrgIndex
34
45/// denote-sequence's commands, `app.node.sequence-…`: notes numbered in a hierarchy through
56/// their signatures.
@@ -39,7 +40,9 @@ extension RoamActions {
3940 do { signature = try sequence() } catch { return show("\(error)") }
4041 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
4142 guard let title else { return }
42 createDenote(title.trimmingCharacters(in: .whitespaces), known: nodes(), signature: signature) { choice in
43 let known: [IndexStore.Node]
44 do { known = try nodes() } catch { return show(error.localizedDescription) }
45 createDenote(title.trimmingCharacters(in: .whitespaces), known: known, signature: signature) { choice in
4346 if case .created(let path, _, _) = choice { open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) }
4447 }
4548 }
Sources/OrgApp/DocumentSession.swift +10 −2
@@ -1099,10 +1099,18 @@ public final class DocumentSession {
10991099 public func fileChanged(_ path: String) {
11001100 let interval = Perf.begin("session.fileChanged")
11011101 defer { interval.end((path as NSString).lastPathComponent) }
1102 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
1102 guard let entry = entry(path) else { return }
1103 let name = (path as NSString).lastPathComponent
1104 let read: [UInt8]?
1105 do {
1106 read = try fileSystem.read(URL(fileURLWithPath: path))
1107 } catch {
1108 lastError = "Can't read \(name): \(error.localizedDescription)"
1109 return
1110 }
1111 guard let bytes = read else { return }
11031112 let buffer = entry.buffer
11041113 guard bytes != buffer.document.mergeBase else { return }
1105 let name = (path as NSString).lastPathComponent
11061114 switch buffer.update({ $0.diskChanged(to: bytes) }) {
11071115 case .conflict:
11081116 entry.autosave?.cancel()
Sources/OrgApp/RoamActions.swift +6 −4
@@ -11,7 +11,7 @@ public struct RoamActions {
1111 /// The sidebar folders, the first being `org-roam-directory` unless it's set.
1212 public var roots: () -> [String]
1313 /// Headings and files with IDs.
14 public var nodes: () -> [IndexStore.Node]
14 public var nodes: () throws -> [IndexStore.Node]
1515 public var show: (String) -> Void
1616 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
1717 /// Opens a file with the caret at an offset.
@@ -26,7 +26,7 @@ public struct RoamActions {
2626 public var reachFolders: ([String]) -> Bool = { _ in true }
2727
2828 public init(
29 session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () -> [IndexStore.Node], show: @escaping (String) -> Void,
29 session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () throws -> [IndexStore.Node], show: @escaping (String) -> Void,
3030 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void,
3131 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void
3232 ) {
@@ -111,7 +111,7 @@ public struct RoamActions {
111111 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) }
112112 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
113113 guard let title = title?.trimmingCharacters(in: .whitespaces) else { return }
114 createDenote(title, known: nodes(), silo: silo, opened)
114 do { createDenote(title, known: try nodes(), silo: silo, opened) } catch { show(error.localizedDescription) }
115115 }
116116 }
117117 case "app.node.insert":
@@ -186,7 +186,9 @@ public struct RoamActions {
186186 /// title no node has makes a node with it, as org-roam's default capture template does;
187187 /// with Denote, `denote` asks for its keywords and makes the note.
188188 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
189 let all = silo.map { silo in nodes().filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? nodes()
189 let known: [IndexStore.Node]
190 do { known = try nodes() } catch { return show(error.localizedDescription) }
191 let all = silo.map { silo in known.filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? known
190192 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
191193 let labels = all.map { node in
192194 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
Sources/OrgApp/RoamGraph.swift +1 −1
@@ -162,7 +162,7 @@ public struct RoamGraph: Sendable, Equatable {
162162extension WorkspaceModel {
163163 /// The graph of the workspace's nodes, with unsaved buffers' in place of their files'.
164164 public func roamGraph(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) -> RoamGraph {
165 RoamGraph(nodes: nodes(overlay: overlay, denote: denote), links: (try? index.links(overlay: overlay)) ?? [],
165 RoamGraph(nodes: (try? nodes(overlay: overlay, denote: denote)) ?? [], links: (try? index.links(overlay: overlay)) ?? [],
166166 sections: denote ? [:] : (try? index.nodeSections(overlay: overlay)) ?? [:], denote: denote)
167167 }
168168}
Sources/OrgApp/WorkspaceModel.swift +26 −10
@@ -289,14 +289,23 @@ public final class WorkspaceModel {
289289 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
290290 var pending = downloading
291291 for rootURL in roots {
292 let report = try? await Task.detached { try reconciler.reconcile(root: rootURL) }.value
293 pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(report?.placeholders.map(\.path) ?? [])
292 var placeholders: [String] = []
293 do {
294 placeholders = try await Task.detached { try reconciler.reconcile(root: rootURL) }.value.placeholders.map(\.path)
295 } catch {
296 lastError = "Indexing \(rootURL.path) failed: \(error.localizedDescription)"
297 }
298 pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(placeholders)
294299 }
295300 for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
296301 let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
297302 guard !inRoot.isEmpty else { continue }
298 let report = try? await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
299 pending.formUnion(report?.placeholders.map(\.path) ?? [])
303 do {
304 let report = try await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
305 pending.formUnion(report.placeholders.map(\.path))
306 } catch {
307 lastError = "Indexing \(rootURL.path) failed: \(error.localizedDescription)"
308 }
300309 }
301310 try? reloadFiles()
302311 setDownloading(pending)
@@ -446,9 +455,11 @@ public final class WorkspaceModel {
446455 /// Headings with links to `target`, the target heading's own links left out, each with
447456 /// the line its link is on as its snippet. Reads every link in the index, so call it off
448457 /// the main actor; a cancelled task gets what was found so far.
449 public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
458 public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
450459 var seen = Set<HeadingLocation>()
451 return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
460 let links: [(source: HeadingLocation, target: String)]
461 do { links = try index.links(overlay: overlay) } catch { throw Self.indexFailed(error) }
462 return links.compactMap { link in
452463 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start),
453464 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
454465 var source = link.source
@@ -460,12 +471,17 @@ public final class WorkspaceModel {
460471 }
461472
462473 /// Headings and files with IDs (org-roam's nodes), or Denote's notes.
463 public func nodes(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) -> [IndexStore.Node] {
464 (try? denote ? index.denoteNodes(overlay: overlay) : index.nodes(overlay: overlay)) ?? []
474 public func nodes(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) throws -> [IndexStore.Node] {
475 do { return try denote ? index.denoteNodes(overlay: overlay) : index.nodes(overlay: overlay) } catch { throw Self.indexFailed(error) }
476 }
477
478 public func search(_ query: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
479 do { return try index.search(query, overlay: overlay) } catch { throw Self.indexFailed(error) }
465480 }
466481
467 public func search(_ query: String, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
468 (try? index.search(query, overlay: overlay)) ?? []
482 /// A query's database error, as the screen showing the query's results says it.
483 private nonisolated static func indexFailed(_ error: any Error) -> FileError {
484 FileError(message: "Can't read the index: \(error.localizedDescription)")
469485 }
470486
471487 /// Index rows for an open file's unsaved text, keyed by path, for queries to use in place
Sources/Orgstar/BacklinksPane.swift +23 −9
@@ -12,6 +12,8 @@ struct BacklinksPane: View {
1212 let open: (HeadingLocation) -> Void
1313 @State private var toHeading: [HeadingLocation] = []
1414 @State private var toFile: [HeadingLocation] = []
15 /// Why the index couldn't be read, shown in place of the lists.
16 @State private var failure: String?
1517 @Environment(\.orgTheme) private var theme
1618 @Environment(\.colorScheme) private var colorScheme
1719
@@ -27,10 +29,14 @@ struct BacklinksPane: View {
2729
2830 var body: some View {
2931 List {
30 if let heading {
31 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(toHeading) }
32 if let failure {
33 Text(failure).foregroundStyle(.secondary)
34 } else {
35 if let heading {
36 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(toHeading) }
37 }
38 Section("Links to this file") { rows(toFile) }
3239 }
33 Section("Links to this file") { rows(toFile) }
3440 }
3541 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
3642 .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() }
@@ -61,24 +67,32 @@ struct BacklinksPane: View {
6167 guard let path = session.path else {
6268 toHeading = []
6369 toFile = []
70 failure = nil
6471 return
6572 }
6673 let overlay = workspace.overlay(session.openDocuments)
67 let found = await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay)
68 guard !Task.isCancelled else { return }
69 (toFile, toHeading) = found
74 do {
75 let found = try await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay)
76 guard !Task.isCancelled else { return }
77 (toFile, toHeading) = found
78 failure = nil
79 } catch {
80 guard !Task.isCancelled else { return }
81 (toFile, toHeading) = ([], [])
82 failure = error.localizedDescription
83 }
7084 }
7185
7286 @concurrent
7387 private nonisolated static func backlinks(
7488 in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord]
75 ) async -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) {
89 ) async throws -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) {
7690 let model = tree.map { DocumentModel(tree: $0) }
7791 // The file's own ID, as an org-roam file node.
78 let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay)
92 let toFile = try workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay)
7993 guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) }
8094 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
8195 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
82 return (toFile, workspace.backlinks(to: target, excluding: heading, overlay: overlay))
96 return (toFile, try workspace.backlinks(to: target, excluding: heading, overlay: overlay))
8397 }
8498}
Sources/Orgstar/ContentView.swift +2 −2
@@ -270,7 +270,7 @@ struct ContentView: View {
270270 }
271271 }
272272 } else {
273 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
273 SearchResults(results: Result { try workspace.search(query, overlay: workspace.overlay(session.openDocuments)) }) { location in
274274 selectedFile = location.path
275275 session.show(location)
276276 }
@@ -872,7 +872,7 @@ struct ContentView: View {
872872 private var roamActions: RoamActions {
873873 var actions = RoamActions(
874874 session: session, roots: { [workspace] in workspace.rootPaths },
875 nodes: { [workspace, session] in workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
875 nodes: { [workspace, session] in try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
876876 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
877877 open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
878878 insertLink: { [commands] link, title in
Sources/Orgstar/SearchViews.swift +8 −3
@@ -5,11 +5,12 @@ import OrgWorkspace
55import SwiftUI
66
77struct SearchResults: View {
8 let results: [HeadingLocation]
8 let results: Result<[HeadingLocation], any Error>
99 let open: (HeadingLocation) -> Void
1010
1111 var body: some View {
12 List(results, id: \.self) { location in
12 let found = (try? results.get()) ?? []
13 List(found, id: \.self) { location in
1314 Button {
1415 open(location)
1516 } label: {
@@ -24,7 +25,11 @@ struct SearchResults: View {
2425 .buttonStyle(.plain)
2526 }
2627 .overlay {
27 if results.isEmpty { ContentUnavailableView.search }
28 if case .failure(let error) = results {
29 ContentUnavailableView(error.localizedDescription, systemImage: "exclamationmark.triangle")
30 } else if found.isEmpty {
31 ContentUnavailableView.search
32 }
2833 }
2934 }
3035}
Sources/OrgstarMobile/BacklinksScreen.swift +20 −9
@@ -14,15 +14,21 @@ struct BacklinksScreen: View {
1414 let open: (HeadingLocation) -> Void
1515 @State private var heading: (title: String, links: [HeadingLocation])?
1616 @State private var toFile: [HeadingLocation] = []
17 /// Why the index couldn't be read, shown in place of the lists.
18 @State private var failure: String?
1719 @Environment(\.dismiss) private var dismiss
1820
1921 var body: some View {
2022 NavigationStack {
2123 List {
22 if let heading {
23 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(heading.links) }
24 if let failure {
25 Text(failure).foregroundStyle(.secondary)
26 } else {
27 if let heading {
28 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(heading.links) }
29 }
30 Section("Links to this file") { rows(toFile) }
2431 }
25 Section("Links to this file") { rows(toFile) }
2632 }
2733 .navigationTitle("Backlinks")
2834 .navigationBarTitleDisplayMode(.inline)
@@ -55,21 +61,26 @@ struct BacklinksScreen: View {
5561 private func refresh() async {
5662 let overlay = workspace.overlay(session.openDocuments)
5763 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
58 let found = await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
59 guard !Task.isCancelled else { return }
60 (toFile, heading) = found
64 do {
65 let found = try await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
66 guard !Task.isCancelled else { return }
67 (toFile, heading) = found
68 } catch {
69 guard !Task.isCancelled else { return }
70 failure = error.localizedDescription
71 }
6172 }
6273
6374 @concurrent
6475 private nonisolated static func backlinks(
6576 in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord]
66 ) async -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) {
77 ) async throws -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) {
6778 let model = DocumentModel(tree: tree)
68 let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
79 let toFile = try workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
6980 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) }
7081 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
7182 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
72 return (toFile, (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)))
83 return (toFile, (info.title, try workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)))
7384 }
7485}
7586#endif
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -565,7 +565,7 @@ extension EditorScreen {
565565 private var roamActions: RoamActions {
566566 RoamActions(
567567 session: session, roots: { workspace.rootPaths },
568 nodes: { workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
568 nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
569569 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
570570 open: { file, offset in
571571 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
Sources/OrgstarMobile/SearchScreen.swift +7 −2
@@ -23,9 +23,14 @@ struct SearchScreen: View {
2323 }
2424 }
2525 }
26 let headings = Perf.measure("search.headings") { workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) }
26 let results = Perf.measure("search.headings") { Result { try workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) } }
27 let headings = (try? results.get()) ?? []
2728 Section("Notes") {
28 if headings.isEmpty { Text("No notes match").foregroundStyle(.secondary) }
29 if case .failure(let error) = results {
30 Text(error.localizedDescription).foregroundStyle(.secondary)
31 } else if headings.isEmpty {
32 Text("No notes match").foregroundStyle(.secondary)
33 }
2934 ForEach(headings, id: \.self) { location in
3035 NavigationLink(value: ReaderRoute.heading(location)) {
3136 VStack(alignment: .leading, spacing: 2) {
Tests/OrgAppTests/AppTests.swift +55 −18
@@ -1,7 +1,7 @@
11import Foundation
22import OrgCore
33import OrgDocument
4import OrgIndex
4@testable import OrgIndex
55import os
66import Testing
77@testable import OrgApp
@@ -60,7 +60,7 @@ struct WorkspaceModelTests {
6060 let model = try WorkspaceModel(directory: support.url)
6161 try await model.addRoot(notes.url)
6262 #expect(model.files.count == 3)
63 #expect(model.search("apples").map(\.title) == ["Groceries"])
63 #expect(try model.search("apples").map(\.title) == ["Groceries"])
6464 #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
6565 let root = try #require(model.rootPaths.first)
6666 #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
@@ -72,7 +72,7 @@ struct WorkspaceModelTests {
7272 try reopened.removeRoot(path: root)
7373 #expect(reopened.roots.isEmpty)
7474 #expect(reopened.files.isEmpty)
75 #expect(reopened.search("apples").isEmpty)
75 #expect(try reopened.search("apples").isEmpty)
7676 }
7777
7878 @Test func aMovedFolderLeavesNoOldRows() async throws {
@@ -83,13 +83,13 @@ struct WorkspaceModelTests {
8383 let data = parent.url.appendingPathComponent("data")
8484 let model = try WorkspaceModel(directory: data)
8585 try await model.addRoot(original)
86 #expect(model.search("plumber").count == 1)
86 #expect(try model.search("plumber").count == 1)
8787
8888 let moved = parent.url.appendingPathComponent("moved")
8989 try FileManager.default.moveItem(at: original, to: moved)
9090 let reopened = try WorkspaceModel(directory: data)
9191 await reopened.refresh()
92 let found = reopened.search("plumber").map(\.path)
92 let found = try reopened.search("plumber").map(\.path)
9393 #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
9494 // Adding it again, under its new path, adds nothing.
9595 try await reopened.addRoot(moved)
@@ -113,7 +113,7 @@ struct WorkspaceModelTests {
113113 try await reopened.regrant(root, with: found)
114114 #expect(reopened.unresolvedRoots.isEmpty)
115115 #expect(reopened.roots.map(\.path) == [found.path])
116 #expect(reopened.search("plumber").count == 1)
116 #expect(try reopened.search("plumber").count == 1)
117117 #expect(try WorkspaceModel(directory: data).roots.map(\.path) == [found.path])
118118
119119 // Chosen again as a folder already in the sidebar, the old one just goes.
@@ -146,16 +146,16 @@ struct WorkspaceModelTests {
146146 let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
147147 let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
148148 let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
149 #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
150 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
151 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
152 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
149 #expect(try model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
150 #expect(try model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
151 #expect(try model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
152 #expect(try model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
153153 // Off the main actor, as the panes ask.
154 #expect(await Task.detached { model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"])
154 #expect(try await Task.detached { try model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"])
155155 // Each with the line its link is on, the link as it reads.
156 #expect(model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
157 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
158 let fromC = try #require(model.backlinks(to: sink).last)
156 #expect(try model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
157 #expect(try model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
158 let fromC = try #require(try model.backlinks(to: sink).last)
159159 #expect(fromC == .file(c, contentHash: fromC.contentHash))
160160 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
161161 session.show(fromC)
@@ -184,7 +184,7 @@ struct WorkspaceModelTests {
184184 try await model.trash(folder + "/roadmap.org")
185185 #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
186186 #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
187 #expect(model.search("alpha").count == 1)
187 #expect(try model.search("alpha").count == 1)
188188 }
189189
190190 /// Watching starts with no folders (a first launch); a folder added afterwards is
@@ -210,9 +210,33 @@ struct WorkspaceModelTests {
210210 try await model.addRoot(notes.url)
211211 try notes.write("a.org", "* New\n")
212212 await model.filesChanged([file], rescan: [])
213 #expect(model.search("new").count == 1)
213 #expect(try model.search("new").count == 1)
214214 #expect(model.changedFile?.path == file.path)
215215 }
216
217 /// A database error is reported, not shown as nothing found.
218 @Test func reportsIndexErrors() async throws {
219 let notes = try Folder()
220 let file = try notes.write("a.org", "* Alpha\n:PROPERTIES:\n:ID: a-1\n:END:\n* Beta\n[[id:a-1]]\n")
221 let model = try WorkspaceModel(directory: nil)
222 try await model.addRoot(notes.url)
223 let a = try #require(model.files.first).path
224 let target = Backlinks.Target(path: a, title: "Alpha", id: "a-1")
225 #expect(try model.nodes(denote: false).map(\.title) == ["Alpha"])
226 #expect(try model.backlinks(to: target).map(\.title) == ["Beta"])
227 #expect(try model.search("gamma").isEmpty)
228 #expect(model.lastError == nil)
229
230 try model.index.database.close()
231 #expect(throws: WorkspaceModel.FileError.self) { try model.search("alpha") }
232 #expect(throws: WorkspaceModel.FileError.self) { try model.nodes(denote: false) }
233 #expect(throws: WorkspaceModel.FileError.self) { try model.backlinks(to: target) }
234 await model.filesChanged([file], rescan: [])
235 #expect(model.lastError?.hasPrefix("Indexing ") == true)
236 model.lastError = nil
237 await model.filesChanged([], rescan: [notes.url])
238 #expect(model.lastError?.hasPrefix("Indexing ") == true)
239 }
216240}
217241
218242@MainActor
@@ -235,6 +259,19 @@ struct DocumentSessionTests {
235259 #expect(session.revealRequest?.offset == 12)
236260 }
237261
262 /// A change that can't be read is reported, and the buffer keeps its text.
263 @Test func unreadableChangeIsReported() throws {
264 let notes = try Folder()
265 let file = try notes.write("a.org", "* One\n")
266 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
267 session.open(file.path)
268 try notes.write("a.org", "* Two\n")
269 try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: file.path)
270 session.fileChanged(file.path)
271 #expect(session.lastError?.hasPrefix("Can't read a.org: ") == true)
272 #expect(session.document?.text == "* One\n")
273 }
274
238275 @Test func sameFileByAnotherPathSharesItsBuffer() throws {
239276 let notes = try Folder()
240277 let file = try notes.write("a.org", "* One\n")
@@ -400,8 +437,8 @@ struct SessionSavingTests {
400437 try await workspace.addRoot(notes.url)
401438 try type("* Unsaved heading\n", at: 0)
402439 let overlay = workspace.overlay(path: session.path, document: session.document)
403 #expect(workspace.search("unsaved").isEmpty)
404 #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
440 #expect(try workspace.search("unsaved").isEmpty)
441 #expect(try workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
405442 }
406443}
407444
Tests/OrgAppTests/DailiesTests.swift +16
@@ -293,6 +293,22 @@ struct DailiesTests {
293293 #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n"))
294294 #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1)
295295 }
296
297 /// An index that can't be read is reported, not offered as an empty list of nodes.
298 @MainActor
299 @Test func nodeFindReportsAnIndexError() throws {
300 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath()
301 defer { try? FileManager.default.removeItem(at: folder) }
302 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
303 var shown: [String] = []
304 var asked: [String] = []
305 let actions = RoamActions(session: session, roots: { [folder.path] },
306 nodes: { throw WorkspaceModel.FileError(message: "Can't read the index: closed") },
307 show: { shown.append($0) }, ask: { prompt, _ in asked.append(prompt.key) },
308 open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
309 actions.run("app.node.find")
310 #expect(shown == ["Can't read the index: closed"] && asked.isEmpty)
311 }
296312}
297313
298314struct NodeIndexTests {