Commit b4ce8f5723

b4ce8f5723ebfb31d3b5104988844e96465f86d5

parent: 6d9f3d99cf

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 19:15 UTC

Report index and reload errors instead of empty results

filesChanged sets lastError when a reconcile fails. search, nodes and
backlinks throw; the search results, backlinks panes and node prompts
show the error in place of an empty list. fileChanged sets lastError
when an open file can't be read and keeps the buffer.

Closes #214

Layout: unified · split

Sources/OrgApp/DenoteSequenceActions.swift +4 −1
@@ -1,5 +1,6 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgIndex
3 4
4/// denote-sequence's commands, `app.node.sequence-…`: notes numbered in a hierarchy through 5/// denote-sequence's commands, `app.node.sequence-…`: notes numbered in a hierarchy through
5/// their signatures. 6/// their signatures.
@@ -39,7 +40,9 @@ extension RoamActions {
39 do { signature = try sequence() } catch { return show("\(error)") } 40 do { signature = try sequence() } catch { return show("\(error)") }
40 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in 41 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
41 guard let title else { return } 42 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
43 if case .created(let path, _, _) = choice { open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) } 46 if case .created(let path, _, _) = choice { open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) }
44 } 47 }
45 } 48 }
Sources/OrgApp/DocumentSession.swift +10 −2
@@ -1099,10 +1099,18 @@ public final class DocumentSession {
1099 public func fileChanged(_ path: String) { 1099 public func fileChanged(_ path: String) {
1100 let interval = Perf.begin("session.fileChanged") 1100 let interval = Perf.begin("session.fileChanged")
1101 defer { interval.end((path as NSString).lastPathComponent) } 1101 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 }
1103 let buffer = entry.buffer 1112 let buffer = entry.buffer
1104 guard bytes != buffer.document.mergeBase else { return } 1113 guard bytes != buffer.document.mergeBase else { return }
1105 let name = (path as NSString).lastPathComponent
1106 switch buffer.update({ $0.diskChanged(to: bytes) }) { 1114 switch buffer.update({ $0.diskChanged(to: bytes) }) {
1107 case .conflict: 1115 case .conflict:
1108 entry.autosave?.cancel() 1116 entry.autosave?.cancel()
Sources/OrgApp/RoamActions.swift +6 −4
@@ -11,7 +11,7 @@ public struct RoamActions {
11 /// The sidebar folders, the first being `org-roam-directory` unless it's set. 11 /// The sidebar folders, the first being `org-roam-directory` unless it's set.
12 public var roots: () -> [String] 12 public var roots: () -> [String]
13 /// Headings and files with IDs. 13 /// Headings and files with IDs.
14 public var nodes: () -> [IndexStore.Node] 14 public var nodes: () throws -> [IndexStore.Node]
15 public var show: (String) -> Void 15 public var show: (String) -> Void
16 public var ask: (Prompt, @escaping (String?) -> Void) -> Void 16 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
17 /// Opens a file with the caret at an offset. 17 /// Opens a file with the caret at an offset.
@@ -26,7 +26,7 @@ public struct RoamActions {
26 public var reachFolders: ([String]) -> Bool = { _ in true } 26 public var reachFolders: ([String]) -> Bool = { _ in true }
27 27
28 public init( 28 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,
30 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void, 30 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, open: @escaping (String, Int) -> Void,
31 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void 31 insertLink: @escaping (String, String) -> Void, refresh: @escaping () -> Void
32 ) { 32 ) {
@@ -111,7 +111,7 @@ public struct RoamActions {
111 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) } 111 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) }
112 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in 112 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
113 guard let title = title?.trimmingCharacters(in: .whitespaces) else { return } 113 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) }
115 } 115 }
116 } 116 }
117 case "app.node.insert": 117 case "app.node.insert":
@@ -186,7 +186,9 @@ public struct RoamActions {
186 /// title no node has makes a node with it, as org-roam's default capture template does; 186 /// title no node has makes a node with it, as org-roam's default capture template does;
187 /// with Denote, `denote` asks for its keywords and makes the note. 187 /// with Denote, `denote` asks for its keywords and makes the note.
188 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) { 188 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
190 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +) 192 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
191 let labels = all.map { node in 193 let labels = all.map { node in
192 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title 194 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 {
162extension WorkspaceModel { 162extension WorkspaceModel {
163 /// The graph of the workspace's nodes, with unsaved buffers' in place of their files'. 163 /// The graph of the workspace's nodes, with unsaved buffers' in place of their files'.
164 public func roamGraph(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) -> RoamGraph { 164 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)) ?? [],
166 sections: denote ? [:] : (try? index.nodeSections(overlay: overlay)) ?? [:], denote: denote) 166 sections: denote ? [:] : (try? index.nodeSections(overlay: overlay)) ?? [:], denote: denote)
167 } 167 }
168} 168}
Sources/OrgApp/WorkspaceModel.swift +26 −10
@@ -289,14 +289,23 @@ public final class WorkspaceModel {
289 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules) 289 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
290 var pending = downloading 290 var pending = downloading
291 for rootURL in roots { 291 for rootURL in roots {
292 let report = try? await Task.detached { try reconciler.reconcile(root: rootURL) }.value 292 var placeholders: [String] = []
293 pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(report?.placeholders.map(\.path) ?? []) 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)
294 } 299 }
295 for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) { 300 for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
296 let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") } 301 let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
297 guard !inRoot.isEmpty else { continue } 302 guard !inRoot.isEmpty else { continue }
298 let report = try? await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value 303 do {
299 pending.formUnion(report?.placeholders.map(\.path) ?? []) 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 }
300 } 309 }
301 try? reloadFiles() 310 try? reloadFiles()
302 setDownloading(pending) 311 setDownloading(pending)
@@ -446,9 +455,11 @@ public final class WorkspaceModel {
446 /// Headings with links to `target`, the target heading's own links left out, each with 455 /// Headings with links to `target`, the target heading's own links left out, each with
447 /// the line its link is on as its snippet. Reads every link in the index, so call it off 456 /// the line its link is on as its snippet. Reads every link in the index, so call it off
448 /// the main actor; a cancelled task gets what was found so far. 457 /// 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] {
450 var seen = Set<HeadingLocation>() 459 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
452 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start), 463 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start),
453 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil } 464 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
454 var source = link.source 465 var source = link.source
@@ -460,12 +471,17 @@ public final class WorkspaceModel {
460 } 471 }
461 472
462 /// Headings and files with IDs (org-roam's nodes), or Denote's notes. 473 /// 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] { 474 public func nodes(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) throws -> [IndexStore.Node] {
464 (try? denote ? index.denoteNodes(overlay: overlay) : index.nodes(overlay: overlay)) ?? [] 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) }
465 } 480 }
466 481
467 public func search(_ query: String, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] { 482 /// A query's database error, as the screen showing the query's results says it.
468 (try? index.search(query, overlay: overlay)) ?? [] 483 private nonisolated static func indexFailed(_ error: any Error) -> FileError {
484 FileError(message: "Can't read the index: \(error.localizedDescription)")
469 } 485 }
470 486
471 /// Index rows for an open file's unsaved text, keyed by path, for queries to use in place 487 /// 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 {
12 let open: (HeadingLocation) -> Void 12 let open: (HeadingLocation) -> Void
13 @State private var toHeading: [HeadingLocation] = [] 13 @State private var toHeading: [HeadingLocation] = []
14 @State private var toFile: [HeadingLocation] = [] 14 @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?
15 @Environment(\.orgTheme) private var theme 17 @Environment(\.orgTheme) private var theme
16 @Environment(\.colorScheme) private var colorScheme 18 @Environment(\.colorScheme) private var colorScheme
17 19
@@ -27,10 +29,14 @@ struct BacklinksPane: View {
27 29
28 var body: some View { 30 var body: some View {
29 List { 31 List {
30 if let heading { 32 if let failure {
31 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(toHeading) } 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) }
32 } 39 }
33 Section("Links to this file") { rows(toFile) }
34 } 40 }
35 .themedListBackground(theme.color("sidebar-background", in: colorScheme)) 41 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
36 .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() } 42 .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() }
@@ -61,24 +67,32 @@ struct BacklinksPane: View {
61 guard let path = session.path else { 67 guard let path = session.path else {
62 toHeading = [] 68 toHeading = []
63 toFile = [] 69 toFile = []
70 failure = nil
64 return 71 return
65 } 72 }
66 let overlay = workspace.overlay(session.openDocuments) 73 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) 74 do {
68 guard !Task.isCancelled else { return } 75 let found = try await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay)
69 (toFile, toHeading) = found 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 }
70 } 84 }
71 85
72 @concurrent 86 @concurrent
73 private nonisolated static func backlinks( 87 private nonisolated static func backlinks(
74 in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord] 88 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]) {
76 let model = tree.map { DocumentModel(tree: $0) } 90 let model = tree.map { DocumentModel(tree: $0) }
77 // The file's own ID, as an org-roam file node. 91 // 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)
79 guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) } 93 guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) }
80 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value 94 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
81 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) 95 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))
83 } 97 }
84} 98}
Sources/Orgstar/ContentView.swift +2 −2
@@ -270,7 +270,7 @@ struct ContentView: View {
270 } 270 }
271 } 271 }
272 } else { 272 } 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
274 selectedFile = location.path 274 selectedFile = location.path
275 session.show(location) 275 session.show(location)
276 } 276 }
@@ -872,7 +872,7 @@ struct ContentView: View {
872 private var roamActions: RoamActions { 872 private var roamActions: RoamActions {
873 var actions = RoamActions( 873 var actions = RoamActions(
874 session: session, roots: { [workspace] in workspace.rootPaths }, 874 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)) },
876 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) }, 876 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
877 open: { [commands] path, offset in commands.jump(path: path, offset: offset) }, 877 open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
878 insertLink: { [commands] link, title in 878 insertLink: { [commands] link, title in
Sources/Orgstar/SearchViews.swift +8 −3
@@ -5,11 +5,12 @@ import OrgWorkspace
5import SwiftUI 5import SwiftUI
6 6
7struct SearchResults: View { 7struct SearchResults: View {
8 let results: [HeadingLocation] 8 let results: Result<[HeadingLocation], any Error>
9 let open: (HeadingLocation) -> Void 9 let open: (HeadingLocation) -> Void
10 10
11 var body: some View { 11 var body: some View {
12 List(results, id: \.self) { location in 12 let found = (try? results.get()) ?? []
13 List(found, id: \.self) { location in
13 Button { 14 Button {
14 open(location) 15 open(location)
15 } label: { 16 } label: {
@@ -24,7 +25,11 @@ struct SearchResults: View {
24 .buttonStyle(.plain) 25 .buttonStyle(.plain)
25 } 26 }
26 .overlay { 27 .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 }
28 } 33 }
29 } 34 }
30} 35}
Sources/OrgstarMobile/BacklinksScreen.swift +20 −9
@@ -14,15 +14,21 @@ struct BacklinksScreen: View {
14 let open: (HeadingLocation) -> Void 14 let open: (HeadingLocation) -> Void
15 @State private var heading: (title: String, links: [HeadingLocation])? 15 @State private var heading: (title: String, links: [HeadingLocation])?
16 @State private var toFile: [HeadingLocation] = [] 16 @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?
17 @Environment(\.dismiss) private var dismiss 19 @Environment(\.dismiss) private var dismiss
18 20
19 var body: some View { 21 var body: some View {
20 NavigationStack { 22 NavigationStack {
21 List { 23 List {
22 if let heading { 24 if let failure {
23 Section("Links to \(heading.title.isEmpty ? "(untitled)" : heading.title)") { rows(heading.links) } 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) }
24 } 31 }
25 Section("Links to this file") { rows(toFile) }
26 } 32 }
27 .navigationTitle("Backlinks") 33 .navigationTitle("Backlinks")
28 .navigationBarTitleDisplayMode(.inline) 34 .navigationBarTitleDisplayMode(.inline)
@@ -55,21 +61,26 @@ struct BacklinksScreen: View {
55 private func refresh() async { 61 private func refresh() async {
56 let overlay = workspace.overlay(session.openDocuments) 62 let overlay = workspace.overlay(session.openDocuments)
57 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return } 63 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) 64 do {
59 guard !Task.isCancelled else { return } 65 let found = try await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay)
60 (toFile, heading) = found 66 guard !Task.isCancelled else { return }
67 (toFile, heading) = found
68 } catch {
69 guard !Task.isCancelled else { return }
70 failure = error.localizedDescription
71 }
61 } 72 }
62 73
63 @concurrent 74 @concurrent
64 private nonisolated static func backlinks( 75 private nonisolated static func backlinks(
65 in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord] 76 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])?) {
67 let model = DocumentModel(tree: tree) 78 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)
69 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) } 80 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) }
70 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value 81 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
71 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) 82 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)))
73 } 84 }
74} 85}
75#endif 86#endif
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -565,7 +565,7 @@ extension EditorScreen {
565 private var roamActions: RoamActions { 565 private var roamActions: RoamActions {
566 RoamActions( 566 RoamActions(
567 session: session, roots: { workspace.rootPaths }, 567 session: session, roots: { workspace.rootPaths },
568 nodes: { workspace.nodes(overlay: workspace.overlay(session.openDocuments)) }, 568 nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
569 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) }, 569 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
570 open: { file, offset in 570 open: { file, offset in
571 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) } 571 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 {
23 } 23 }
24 } 24 }
25 } 25 }
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()) ?? []
27 Section("Notes") { 28 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 }
29 ForEach(headings, id: \.self) { location in 34 ForEach(headings, id: \.self) { location in
30 NavigationLink(value: ReaderRoute.heading(location)) { 35 NavigationLink(value: ReaderRoute.heading(location)) {
31 VStack(alignment: .leading, spacing: 2) { 36 VStack(alignment: .leading, spacing: 2) {
Tests/OrgAppTests/AppTests.swift +55 −18
@@ -1,7 +1,7 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgDocument 3import OrgDocument
4import OrgIndex 4@testable import OrgIndex
5import os 5import os
6import Testing 6import Testing
7@testable import OrgApp 7@testable import OrgApp
@@ -60,7 +60,7 @@ struct WorkspaceModelTests {
60 let model = try WorkspaceModel(directory: support.url) 60 let model = try WorkspaceModel(directory: support.url)
61 try await model.addRoot(notes.url) 61 try await model.addRoot(notes.url)
62 #expect(model.files.count == 3) 62 #expect(model.files.count == 3)
63 #expect(model.search("apples").map(\.title) == ["Groceries"]) 63 #expect(try model.search("apples").map(\.title) == ["Groceries"])
64 #expect(model.quickOpen("bo").map(\.name) == ["b.org"]) 64 #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
65 let root = try #require(model.rootPaths.first) 65 let root = try #require(model.rootPaths.first)
66 #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"]) 66 #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
@@ -72,7 +72,7 @@ struct WorkspaceModelTests {
72 try reopened.removeRoot(path: root) 72 try reopened.removeRoot(path: root)
73 #expect(reopened.roots.isEmpty) 73 #expect(reopened.roots.isEmpty)
74 #expect(reopened.files.isEmpty) 74 #expect(reopened.files.isEmpty)
75 #expect(reopened.search("apples").isEmpty) 75 #expect(try reopened.search("apples").isEmpty)
76 } 76 }
77 77
78 @Test func aMovedFolderLeavesNoOldRows() async throws { 78 @Test func aMovedFolderLeavesNoOldRows() async throws {
@@ -83,13 +83,13 @@ struct WorkspaceModelTests {
83 let data = parent.url.appendingPathComponent("data") 83 let data = parent.url.appendingPathComponent("data")
84 let model = try WorkspaceModel(directory: data) 84 let model = try WorkspaceModel(directory: data)
85 try await model.addRoot(original) 85 try await model.addRoot(original)
86 #expect(model.search("plumber").count == 1) 86 #expect(try model.search("plumber").count == 1)
87 87
88 let moved = parent.url.appendingPathComponent("moved") 88 let moved = parent.url.appendingPathComponent("moved")
89 try FileManager.default.moveItem(at: original, to: moved) 89 try FileManager.default.moveItem(at: original, to: moved)
90 let reopened = try WorkspaceModel(directory: data) 90 let reopened = try WorkspaceModel(directory: data)
91 await reopened.refresh() 91 await reopened.refresh()
92 let found = reopened.search("plumber").map(\.path) 92 let found = try reopened.search("plumber").map(\.path)
93 #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)") 93 #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
94 // Adding it again, under its new path, adds nothing. 94 // Adding it again, under its new path, adds nothing.
95 try await reopened.addRoot(moved) 95 try await reopened.addRoot(moved)
@@ -113,7 +113,7 @@ struct WorkspaceModelTests {
113 try await reopened.regrant(root, with: found) 113 try await reopened.regrant(root, with: found)
114 #expect(reopened.unresolvedRoots.isEmpty) 114 #expect(reopened.unresolvedRoots.isEmpty)
115 #expect(reopened.roots.map(\.path) == [found.path]) 115 #expect(reopened.roots.map(\.path) == [found.path])
116 #expect(reopened.search("plumber").count == 1) 116 #expect(try reopened.search("plumber").count == 1)
117 #expect(try WorkspaceModel(directory: data).roots.map(\.path) == [found.path]) 117 #expect(try WorkspaceModel(directory: data).roots.map(\.path) == [found.path])
118 118
119 // Chosen again as a folder already in the sidebar, the old one just goes. 119 // Chosen again as a folder already in the sidebar, the old one just goes.
@@ -146,16 +146,16 @@ struct WorkspaceModelTests {
146 let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path 146 let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
147 let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path 147 let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
148 let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink") 148 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"]) 149 #expect(try model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
150 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"]) 150 #expect(try 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"]) 151 #expect(try 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"]) 152 #expect(try model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
153 // Off the main actor, as the panes ask. 153 // 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"])
155 // Each with the line its link is on, the link as it reads. 155 // 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."]) 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(model.backlinks(to: sink).first?.snippet?.matches == [0..<8]) 157 #expect(try model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
158 let fromC = try #require(model.backlinks(to: sink).last) 158 let fromC = try #require(try model.backlinks(to: sink).last)
159 #expect(fromC == .file(c, contentHash: fromC.contentHash)) 159 #expect(fromC == .file(c, contentHash: fromC.contentHash))
160 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 160 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
161 session.show(fromC) 161 session.show(fromC)
@@ -184,7 +184,7 @@ struct WorkspaceModelTests {
184 try await model.trash(folder + "/roadmap.org") 184 try await model.trash(folder + "/roadmap.org")
185 #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org")) 185 #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
186 #expect(!model.files.map(\.path).contains(folder + "/roadmap.org")) 186 #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
187 #expect(model.search("alpha").count == 1) 187 #expect(try model.search("alpha").count == 1)
188 } 188 }
189 189
190 /// Watching starts with no folders (a first launch); a folder added afterwards is 190 /// Watching starts with no folders (a first launch); a folder added afterwards is
@@ -210,9 +210,33 @@ struct WorkspaceModelTests {
210 try await model.addRoot(notes.url) 210 try await model.addRoot(notes.url)
211 try notes.write("a.org", "* New\n") 211 try notes.write("a.org", "* New\n")
212 await model.filesChanged([file], rescan: []) 212 await model.filesChanged([file], rescan: [])
213 #expect(model.search("new").count == 1) 213 #expect(try model.search("new").count == 1)
214 #expect(model.changedFile?.path == file.path) 214 #expect(model.changedFile?.path == file.path)
215 } 215 }
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 }
216} 240}
217 241
218@MainActor 242@MainActor
@@ -235,6 +259,19 @@ struct DocumentSessionTests {
235 #expect(session.revealRequest?.offset == 12) 259 #expect(session.revealRequest?.offset == 12)
236 } 260 }
237 261
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
238 @Test func sameFileByAnotherPathSharesItsBuffer() throws { 275 @Test func sameFileByAnotherPathSharesItsBuffer() throws {
239 let notes = try Folder() 276 let notes = try Folder()
240 let file = try notes.write("a.org", "* One\n") 277 let file = try notes.write("a.org", "* One\n")
@@ -400,8 +437,8 @@ struct SessionSavingTests {
400 try await workspace.addRoot(notes.url) 437 try await workspace.addRoot(notes.url)
401 try type("* Unsaved heading\n", at: 0) 438 try type("* Unsaved heading\n", at: 0)
402 let overlay = workspace.overlay(path: session.path, document: session.document) 439 let overlay = workspace.overlay(path: session.path, document: session.document)
403 #expect(workspace.search("unsaved").isEmpty) 440 #expect(try workspace.search("unsaved").isEmpty)
404 #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"]) 441 #expect(try workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
405 } 442 }
406} 443}
407 444
Tests/OrgAppTests/DailiesTests.swift +16
@@ -293,6 +293,22 @@ struct DailiesTests {
293 #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n")) 293 #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n"))
294 #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1) 294 #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1)
295 } 295 }
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 }
296} 312}
297 313
298struct NodeIndexTests { 314struct NodeIndexTests {