Move backlinks, inspector and agenda file checks off the main actor !455

merged merged by cmc on 2026-11-22 12:37 UTC · krz/orgstar:issue-188-main-thread into main

10 files changed, +144 −61

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +26 −30
@@ -177,39 +177,35 @@ public final class AgendaModel {
177177 defer { interval.end("\(files.count) files") }
178178 let defaults = workspace.settings.org
179179 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
180 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
181 for path in files {
182 if let text = open[path] {
183 // The same text parsed before, as the buffer or as the file on disk.
184 func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
185 guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
186 return source
187 }
188 let fromOpen = cache.open[path]
189 let fromDisk = cache.entries[path]
190 let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
191 reads.append((path, cached, .distantPast, -1, text))
192 continue
193 }
194 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
195 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
196 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
197 // A file reading setup files is read again: they may have changed.
198 let cached = cache.entries[path].flatMap { entry in
199 entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
200 }
201 reads.append((path, cached, mtime, size, nil))
202 }
180 let files = files
181 let (openCache, diskCache) = (cache.open, cache.entries)
203182 let loaded = await Task.detached {
204183 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
205 for read in reads {
206 if let cached = read.cached {
207 sources.append((read.path, read.mtime, read.size, cached, read.text == nil))
208 } else if let text = read.text {
209 sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), false))
210 } else if let data = FileManager.default.contents(atPath: read.path) {
184 for path in files {
185 if let text = open[path] {
186 // The same text parsed before, as the buffer or as the file on disk.
187 func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
188 guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
189 return source
190 }
191 let fromOpen = openCache[path]
192 let fromDisk = diskCache[path]
193 let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
194 sources.append((path, .distantPast, -1, cached ?? AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), false))
195 continue
196 }
197 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
198 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
199 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
200 // A file reading setup files is read again: they may have changed.
201 let cached = diskCache[path].flatMap { entry in
202 entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
203 }
204 if let cached {
205 sources.append((path, mtime, size, cached, true))
206 } else if let data = FileManager.default.contents(atPath: path) {
211207 let text = SourceText(bytes: [UInt8](data)).text
212 sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), true))
208 sources.append((path, mtime, size, AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), true))
213209 }
214210 }
215211 return sources
Sources/OrgApp/WorkspaceModel.swift +7 −3
@@ -19,6 +19,8 @@ public final class WorkspaceModel {
1919 public var lastError: String?
2020 /// Bumped when an indexed file changes on disk, with its path.
2121 public private(set) var changedFile: (path: String, version: Int)?
22 /// Bumped when the index may hold other rows: after a reconcile, or a root's removal.
23 public private(set) var indexVersion = 0
2224
2325 public let index: IndexStore
2426 /// A change (other TODO keywords) reindexes the files it affects.
@@ -279,6 +281,7 @@ public final class WorkspaceModel {
279281 guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
280282 return FileEntry(path: file.path, root: root, kind: file.kind)
281283 }
284 indexVersion += 1
282285 }
283286
284287 /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
@@ -441,11 +444,12 @@ public final class WorkspaceModel {
441444 }
442445
443446 /// Headings with links to `target`, the target heading's own links left out, each with
444 /// the line its link is on as its snippet.
445 public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
447 /// 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.
449 public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
446450 var seen = Set<HeadingLocation>()
447451 return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
448 guard !(link.source.path == target.path && link.source.start == start),
452 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start),
449453 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
450454 var source = link.source
451455 if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
Sources/OrgCore/Links/Backlinks.swift +7 −3
@@ -19,6 +19,11 @@ public enum Backlinks {
1919 }
2020 }
2121
22 /// A link type and its colon.
23 nonisolated(unsafe) private static let typePrefix = /^[a-zA-Z][-a-zA-Z0-9+]*:/
24 /// A bracket link: what it links to, and its description.
25 nonisolated(unsafe) private static let bracketLink = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
26
2227 /// Whether `link`, written in the file at `source`, leads to `target`.
2328 public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool {
2429 let link = Links.unescape(link)
@@ -42,7 +47,7 @@ public enum Backlinks {
4247 let parts = link.components(separatedBy: "::")
4348 path = parts[0]
4449 search = parts.dropFirst().joined(separator: "::")
45 } else if link.firstMatch(of: /^[a-zA-Z][-a-zA-Z0-9+]*:/) != nil {
50 } else if link.firstMatch(of: typePrefix) != nil {
4651 return false
4752 } else {
4853 // Within the file.
@@ -66,13 +71,12 @@ public enum Backlinks {
6671 /// description, else what they link to), and the range of that link in the line. A line
6772 /// longer than `width` keeps the part around the link.
6873 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
69 let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
7074 for line in body.split(whereSeparator: \.isNewline) {
7175 guard line.contains("[[" + link + "]") else { continue }
7276 var text = ""
7377 var found: Range<Int>?
7478 var rest = Substring(line)
75 while let match = rest.firstMatch(of: pattern) {
79 while let match = rest.firstMatch(of: bracketLink) {
7680 text += rest[..<match.range.lowerBound]
7781 let shown = match.2.map(String.init) ?? String(match.1)
7882 let start = text.utf16.count
Sources/OrgCore/Links/Links.swift +4 −2
@@ -33,12 +33,14 @@ public enum Links {
3333 pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
3434 )
3535
36 /// Runs of backslashes before a bracket or the end.
37 private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
38
3639 /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
3740 static func unescape(_ s: String) -> String {
38 let regex = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
3941 let ns = s as NSString
4042 var out = s
41 for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
43 for m in escapes.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
4244 let run = m.range(at: 1)
4345 out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
4446 }
Sources/Orgstar/BacklinksPane.swift +17 −11
@@ -21,7 +21,8 @@ struct BacklinksPane: View {
2121 private struct Key: Equatable {
2222 var path: String?
2323 var heading: Int?
24 var version: Int
24 var title: String?
25 var index: Int
2526 }
2627
2728 var body: some View {
@@ -32,7 +33,7 @@ struct BacklinksPane: View {
3233 Section("Links to this file") { rows(toFile) }
3334 }
3435 .themedListBackground(theme.color("sidebar-background", in: colorScheme))
35 .task(id: Key(path: session.path, heading: heading?.start, version: session.editVersion)) { refresh() }
36 .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() }
3637 }
3738
3839 @ViewBuilder
@@ -56,23 +57,28 @@ struct BacklinksPane: View {
5657 }
5758 }
5859
59 private func refresh() {
60 private func refresh() async {
6061 guard let path = session.path else {
6162 toHeading = []
6263 toFile = []
6364 return
6465 }
6566 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
70 }
71
72 @concurrent
73 private nonisolated static func backlinks(
74 in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord]
75 ) async -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) {
76 let model = tree.map { DocumentModel(tree: $0) }
6677 // The file's own ID, as an org-roam file node.
67 let fileID = session.document.map { DocumentModel(tree: $0.tree).property("ID", of: nil)?.value }
68 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: fileID ?? nil), overlay: overlay)
69 guard let heading, let tree = session.document?.tree,
70 let info = DocumentModel(tree: tree).headings.first(where: { $0.headingRange.lowerBound == heading.start }) else {
71 toHeading = []
72 return
73 }
78 let toFile = 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, []) }
7480 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
7581 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
76 toHeading = workspace.backlinks(to: target, excluding: heading.start, overlay: overlay)
82 return (toFile, workspace.backlinks(to: target, excluding: heading, overlay: overlay))
7783 }
7884}
Sources/Orgstar/ContentView.swift +1 −1
@@ -282,7 +282,7 @@ struct ContentView: View {
282282 detail
283283 .frame(maxWidth: .infinity)
284284 .inspector(isPresented: $inspectorShown) {
285 InspectorPane(session: session, commands: commands)
285 InspectorPane(session: session, commands: commands, shown: inspectorShown)
286286 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
287287 }
288288 }
Sources/Orgstar/InspectorPane.swift +18 −5
@@ -7,6 +7,8 @@ import SwiftUI
77struct InspectorPane: View {
88 let session: DocumentSession
99 let commands: AppCommands
10 /// Whether the inspector is on screen; nothing is computed while it isn't.
11 let shown: Bool
1012 @AppStorage("inspectorTab") private var tab = Tab.columns
1113 @AppStorage("inspectorColumnsScope") private var subtree = false
1214 @AppStorage("inspectorClockSpan") private var span = Span.week
@@ -17,6 +19,7 @@ struct InspectorPane: View {
1719 enum Span: String, CaseIterable { case today = "Today", week = "This Week", all = "All" }
1820
1921 private struct Key: Equatable {
22 var shown: Bool
2023 var path: String?
2124 var version: Int
2225 var caret: Int?
@@ -41,7 +44,9 @@ struct InspectorPane: View {
4144 case .clock: clockView
4245 }
4346 }
44 .task(id: Key(path: session.path, version: session.editVersion, caret: subtree ? heading : nil, subtree: subtree, span: span)) { refresh() }
47 .task(id: Key(shown: shown, path: session.path, version: shown ? session.editVersion : 0, caret: shown && subtree ? heading : nil, subtree: subtree, span: span)) {
48 if shown { await refresh() }
49 }
4550 }
4651
4752 @ViewBuilder
@@ -120,14 +125,22 @@ struct InspectorPane: View {
120125 }
121126 }
122127
123 private func refresh() {
128 private func refresh() async {
124129 guard session.isOrg, let document = session.document else {
125130 columns = nil
126131 clocked = []
127132 return
128133 }
129 let text = document.text
130 columns = (try? ColumnView.capture(text: text, tree: document.tree, at: heading ?? 0, global: !subtree || heading == nil))?.view
134 let found = await Self.content(text: document.text, tree: document.tree, heading: heading, subtree: subtree, span: span)
135 guard !Task.isCancelled else { return }
136 (columns, clocked) = found
137 }
138
139 @concurrent
140 private nonisolated static func content(
141 text: String, tree: OrgTree, heading: Int?, subtree: Bool, span: Span
142 ) async -> (columns: ColumnView.View?, clocked: [(start: Int, heading: String, minutes: Int)]) {
143 let columns = (try? ColumnView.capture(text: text, tree: tree, at: heading ?? 0, global: !subtree || heading == nil))?.view
131144 let formatter = DateFormatter()
132145 formatter.locale = Locale(identifier: "en_US_POSIX")
133146 formatter.dateFormat = "yyyy-MM-dd"
@@ -140,6 +153,6 @@ struct InspectorPane: View {
140153 case .week: calendar.dateInterval(of: .weekOfYear, for: today)?.start
141154 case .all: nil
142155 }
143 clocked = ClockReport.byHeading(ClockReport.entries(text), from: from.map(formatter.string), to: span == .all ? nil : formatter.string(from: today))
156 return (columns, ClockReport.byHeading(ClockReport.entries(text), from: from.map(formatter.string), to: span == .all ? nil : formatter.string(from: today)))
144157 }
145158}
Sources/OrgstarMobile/BacklinksScreen.swift +15 −6
@@ -28,7 +28,7 @@ struct BacklinksScreen: View {
2828 .navigationBarTitleDisplayMode(.inline)
2929 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
3030 }
31 .task { refresh() }
31 .task { await refresh() }
3232 }
3333
3434 @ViewBuilder
@@ -52,15 +52,24 @@ struct BacklinksScreen: View {
5252 }
5353 }
5454
55 private func refresh() {
55 private func refresh() async {
5656 let overlay = workspace.overlay(session.openDocuments)
5757 guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return }
58 let model = DocumentModel(tree: document.tree)
59 toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay)
60 guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return heading = nil }
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
61 }
62
63 @concurrent
64 private nonisolated static func backlinks(
65 in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord]
66 ) async -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) {
67 let model = DocumentModel(tree: tree)
68 let toFile = 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) }
6170 let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
6271 let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID)
63 heading = (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay))
72 return (toFile, (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)))
6473 }
6574}
6675#endif
Tests/OrgAppTests/AppTests.swift +30
@@ -149,6 +149,8 @@ struct WorkspaceModelTests {
149149 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
150150 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
151151 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
152 // Off the main actor, as the panes ask.
153 #expect(await Task.detached { model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"])
152154 // Each with the line its link is on, the link as it reads.
153155 #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."])
154156 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
@@ -593,6 +595,34 @@ struct AgendaModelTests {
593595 #expect(agenda.list.map(\.text) == ["TODO One"])
594596 }
595597
598 /// A refresh over cached files leaves the main actor free while it checks them on disk.
599 @Test func checksFilesOffTheMainActor() async throws {
600 let notes = try Folder()
601 for file in 0..<1_500 { try notes.write("f\(file).org", "* TODO Item\n") }
602 let model = try WorkspaceModel(directory: nil)
603 try await model.addRoot(notes.url)
604 let agenda = AgendaModel(workspace: model)
605 agenda.mode = .todo(keywords: nil)
606 await agenda.refresh(open: [:])
607 let clock = ContinuousClock()
608 var longest = Duration.zero
609 let beat = Task { @MainActor in
610 var last = clock.now
611 while !Task.isCancelled {
612 await Task.yield()
613 longest = max(longest, clock.now - last)
614 last = clock.now
615 }
616 }
617 await Task.yield()
618 let start = clock.now
619 await agenda.refresh(open: [:])
620 let took = clock.now - start
621 beat.cancel()
622 #expect(agenda.list.count == 1_500)
623 #expect(longest < took / 2, "main actor held for \(longest) of \(took)")
624 }
625
596626 @Test func entriesKnowTheirDoneKeyword() async throws {
597627 let notes = try Folder()
598628 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
Tests/OrgCoreTests/BacklinkTests.swift +19
@@ -24,6 +24,25 @@ struct BacklinkTests {
2424 #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading))
2525 }
2626
27 /// The patterns are compiled once, not for each link: testing the links takes less time
28 /// than compiling them that often would.
29 @Test func testsManyLinksWithoutCompilingPatterns() throws {
30 let links = (0..<20_000).map { ["id:abc-\($0)", "file:a.org::*Fix the sink", "https://example.org/\($0)", "Fix the sink"][$0 % 4] }
31 let clock = ContinuousClock()
32 let compiling = try clock.measure {
33 for index in links.indices {
34 _ = try NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
35 if index % 2 == 0 { _ = try Regex("^[a-zA-Z][-a-zA-Z0-9+]*:") }
36 }
37 }
38 var hits = 0
39 let testing = clock.measure {
40 for link in links where Backlinks.links(link, from: "/notes/b.org", to: heading, home: "/home") { hits += 1 }
41 }
42 #expect(hits == 5_000)
43 #expect(testing < compiling / 2, "\(testing) against \(compiling)")
44 }
45
2746 @Test func followsDenoteLinks() {
2847 let file = Backlinks.Target(path: "/notes/20261119T120000--a-note__kw.org")
2948 let heading = Backlinks.Target(path: file.path, title: "Inside", customID: "in")