Commit d8d6302e6f

d8d6302e6fe2e80f6133f97bb45a8a1a457d1a81

parent: 3a5c6a6f0e

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-10 04:01 UTC

Stop iOS agenda stalls: no per-row file parsing, shared source cache, fewer refreshes

- Agenda entries carry their done keyword; rows no longer parse their
  file on every render to decide the Done swipe.
- Reminders and widgets share the agenda's parsed sources; the cache is
  keyed on the settings too.
- The agenda refresh waits out bursts of changes; reminders and widgets
  wait for it; concurrent workspace refreshes coalesce.
- One view per agenda list element, so the list counts rows without
  building them.
- Spotlight reads and summarizes files off the main thread.

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +18 −7
@@ -4,9 +4,17 @@ import OrgCore
44import OrgIndex
55import OrgPresentation
66
7/// Parsed agenda files by path, kept while the file's modification date and size and the
8/// settings it was parsed with hold. Agenda models over one workspace can share one.
9@MainActor
10public final class AgendaSourceCache {
11 var entries: [String: (mtime: Date, size: Int, defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
12
13 public init() {}
14}
15
716/// The day/week agenda over the workspace's agenda files. Sources are read from disk and
8/// cached by modification date and size; the open file's come from its buffer, so the agenda
9/// shows unsaved edits.
17/// cached in `cache`; the open file's come from its buffer, so the agenda shows unsaved edits.
1018@MainActor
1119@Observable
1220public final class AgendaModel {
@@ -33,11 +41,12 @@ public final class AgendaModel {
3341 @ObservationIgnored private var calendar = Calendar.current
3442
3543 private let workspace: WorkspaceModel
36 @ObservationIgnored private var cache: [String: (mtime: Date, size: Int, source: AgendaSource)] = [:]
44 @ObservationIgnored public let cache: AgendaSourceCache
3745 @ObservationIgnored private var generation = 0
3846
39 public init(workspace: WorkspaceModel) {
47 public init(workspace: WorkspaceModel, cache: AgendaSourceCache = AgendaSourceCache()) {
4048 self.workspace = workspace
49 self.cache = cache
4150 }
4251
4352 /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
@@ -113,7 +122,7 @@ public final class AgendaModel {
113122 }
114123
115124 /// The agenda files' sources: the open file's from its text, the others from the cache
116 /// while their modification date and size are unchanged.
125 /// while they and the settings are unchanged.
117126 private func sources(open: [String: String]) async -> [AgendaSource] {
118127 let interval = Perf.begin("agenda.sources")
119128 defer { interval.end("\(files.count) files") }
@@ -129,7 +138,9 @@ public final class AgendaModel {
129138 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
130139 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
131140 // A file reading setup files is read again: they may have changed.
132 let cached = cache[path].flatMap { $0.mtime == mtime && $0.size == size && !$0.source.readsSetupFiles && $0.source.checksBlocking == blocking ? $0.source : nil }
141 let cached = cache.entries[path].flatMap { entry in
142 entry.mtime == mtime && entry.size == size && entry.defaults == defaults && entry.blocking == blocking && !entry.source.readsSetupFiles ? entry.source : nil
143 }
133144 reads.append((path, cached, mtime, size, nil))
134145 }
135146 let loaded = await Task.detached {
@@ -147,7 +158,7 @@ public final class AgendaModel {
147158 return sources
148159 }.value
149160 for source in loaded where source.fromDisk {
150 cache[source.path] = (source.mtime, source.size, source.source)
161 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
151162 }
152163 return loaded.map(\.source)
153164 }
Sources/OrgApp/DocumentSession.swift −8
@@ -82,14 +82,6 @@ public final class DocumentSession {
8282 DocumentState(bytes: bytes, defaults: defaults.resolvingSetupFiles(in: SourceText(bytes: bytes).text, path: path, read: readText))
8383 }
8484
85 /// The settings of the file at `path` as the editor sees them: its open buffer's, or its
86 /// text on disk with the defaults and the setup files it names.
87 public func settings(for path: String) -> OrgSettings? {
88 if let entry = entry(path) { return entry.buffer.document.tree.settings }
89 guard let bytes = (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0 }) else { return nil }
90 return loaded(bytes, path: path).tree.settings
91 }
92
9385 /// A file's text, for setup files.
9486 func readText(_ file: String) -> String? {
9587 (try? fileSystem.read(URL(fileURLWithPath: file))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
Sources/OrgApp/WorkspaceModel.swift +21 −1
@@ -138,8 +138,28 @@ public final class WorkspaceModel {
138138 }
139139 }
140140
141 /// Reconciles every root off the main thread, then reloads the file list.
141 /// Reconciles every root off the main thread, then reloads the file list. A call while a
142 /// refresh runs waits for it and one more pass, which covers every such call.
142143 public func refresh() async {
144 if let refreshing {
145 refreshAgain = true
146 return await refreshing.value
147 }
148 let task = Task {
149 repeat {
150 refreshAgain = false
151 await refreshOnce()
152 } while refreshAgain
153 }
154 refreshing = task
155 await task.value
156 refreshing = nil
157 }
158
159 @ObservationIgnored private var refreshing: Task<Void, Never>?
160 @ObservationIgnored private var refreshAgain = false
161
162 private func refreshOnce() async {
143163 let interval = Perf.begin("workspace.refresh")
144164 defer { interval.end() }
145165 isIndexing = true
Sources/OrgCore/Agenda/Agenda.swift +3
@@ -54,6 +54,8 @@ public struct AgendaItem: Sendable, Equatable {
5454 public var planningDay: Int?
5555 /// Blocked from becoming done, for `org-agenda-dim-blocked-tasks`.
5656 public var isBlocked = false
57 /// The first done keyword of the sequence the entry's keyword belongs to.
58 public var doneKeyword: String?
5759 var blockedByCheckboxes = false
5860 var blockedByHierarchy = false
5961}
@@ -410,6 +412,7 @@ public enum Agenda {
410412 )
411413 item.blockedByCheckboxes = heading.blockedByCheckboxes
412414 item.blockedByHierarchy = heading.blockedByHierarchy
415 item.doneKeyword = heading.todo.flatMap { source.firstDone[$0] }
413416 return item
414417 }
415418
Sources/OrgCore/Agenda/AgendaSource.swift +8 −3
@@ -100,17 +100,16 @@ public struct AgendaSource: Sendable {
100100 let keywords: [String]
101101 /// The active ones (`org-not-done-keywords`).
102102 let notDoneKeywords: [String]
103 /// Each keyword's first done keyword in the first sequence that has it.
104 let firstDone: [String: String]
103105 /// The file's text, for the search view.
104106 let text: String
105 /// Whether the headings' blocked flags were worked out.
106 public let checksBlocking: Bool
107107 let priorities: Priorities
108108
109109 /// `checksBlocking` false leaves every heading unblocked, for when neither enforce
110110 /// setting is on.
111111 public init(path: String, text: String, defaults: OrgSettings = .default, checksBlocking: Bool = true) {
112112 self.path = path
113 self.checksBlocking = checksBlocking
114113 readsSetupFiles = text.range(of: "#+setupfile:", options: .caseInsensitive) != nil
115114 let tree = OrgParser.parse(text, defaults: defaults)
116115 let model = DocumentModel(tree: tree)
@@ -118,6 +117,12 @@ public struct AgendaSource: Sendable {
118117 let settings = tree.settings
119118 keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
120119 notDoneKeywords = settings.todoSequences.flatMap { $0.active.map(\.name) }
120 var firstDone: [String: String] = [:]
121 for sequence in settings.todoSequences {
122 guard let done = sequence.done.first?.name else { continue }
123 for keyword in sequence.active + sequence.done where firstDone[keyword.name] == nil { firstDone[keyword.name] = done }
124 }
125 self.firstDone = firstDone
121126 self.text = text
122127 priorities = settings.priorities
123128
Sources/OrgCore/Links/LinkStore.swift +3 −2
@@ -130,12 +130,13 @@ extension Links {
130130 }
131131 }
132132
133 static let bracketLink = try! NSRegularExpression(pattern: "\\[\\[((?:[^\\]\\[\\\\]|\\\\(?:\\\\\\\\)*[\\]\\[]|\\\\+[^\\]\\[])+)\\](?:\\[((?:.|\\n)+?)\\])?\\]")
134
133135 /// `org-link-display-format`: bracket links become their descriptions.
134136 static func displayFormat(_ s: String) -> String {
135 let regex = try! NSRegularExpression(pattern: "\\[\\[((?:[^\\]\\[\\\\]|\\\\(?:\\\\\\\\)*[\\]\\[]|\\\\+[^\\]\\[])+)\\](?:\\[((?:.|\\n)+?)\\])?\\]")
136137 let ns = s as NSString
137138 var out = s
138 for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
139 for m in bracketLink.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
139140 let group = m.range(at: 2).location != NSNotFound ? m.range(at: 2) : m.range(at: 1)
140141 out = (out as NSString).replacingCharacters(in: m.range, with: ns.substring(with: group))
141142 }
Sources/OrgstarMobile/AgendaScreen.swift +28 −13
@@ -206,6 +206,9 @@ struct AgendaScreen: View {
206206 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
207207 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
208208 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
209 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
210 try? await Task.sleep(for: .milliseconds(150))
211 guard !Task.isCancelled else { return }
209212 agenda.options.logMode = logMode
210213 await agenda.refresh(open: session.openTexts)
211214 }
@@ -258,15 +261,33 @@ struct AgendaScreen: View {
258261 if group.isEmpty {
259262 Text("Nothing scheduled").font(.subheadline).foregroundStyle(.secondary)
260263 }
261 let nowAt = nowIndex(group)
262 ForEach(Array(group.rows.enumerated()), id: \.element.id) { index, item in
263 if index == nowAt { NowLine(time: now, color: todayColor) }
264 row(item, day: group.day)
264 // One view per element, so the list counts its rows without building them.
265 ForEach(lines(group)) { line in
266 switch line {
267 case .now: NowLine(time: now, color: todayColor)
268 case .row(let item): row(item, day: group.day)
269 }
265270 }
266 if let nowAt, nowAt == group.rows.count { NowLine(time: now, color: todayColor) }
267271 }
268272 }
269273
274 /// A day's rows, with the now line among them as a line of its own.
275 private enum DayLine: Identifiable {
276 case now
277 case row(AgendaRow)
278
279 var id: String {
280 if case .row(let row) = self { return row.id }
281 return "now"
282 }
283 }
284
285 private func lines(_ group: AgendaDayGroup) -> [DayLine] {
286 var lines = group.rows.map(DayLine.row)
287 if let at = nowIndex(group) { lines.insert(.now, at: at) }
288 return lines
289 }
290
270291 private func nowIndex(_ group: AgendaDayGroup) -> Int? {
271292 let c = Calendar.current.dateComponents([.hour, .minute], from: now)
272293 return group.nowIndex(now: (c.hour ?? 0) * 100 + (c.minute ?? 0))
@@ -433,7 +454,7 @@ struct AgendaScreen: View {
433454 }
434455 }
435456 .swipeActions(edge: .trailing) {
436 if let item = row.item, item.todo != nil, !item.isDone, doneKeyword(for: item) != nil {
457 if let item = row.item, item.todo != nil, !item.isDone, item.doneKeyword != nil {
437458 Button("Done", systemImage: "checkmark") { markDone(item) }.tint(.green)
438459 Button("Next State", systemImage: "arrow.right.circle") { run("org.todo.next", on: item) }.tint(.blue)
439460 }
@@ -535,14 +556,8 @@ struct AgendaScreen: View {
535556 tick += 1
536557 }
537558
538 /// The first done keyword of the item's TODO sequence.
539 private func doneKeyword(for item: AgendaItem) -> String? {
540 guard let todo = item.todo, let path = item.path, let settings = session.settings(for: path) else { return nil }
541 return settings.todoSequences.first { ($0.active + $0.done).contains { $0.name == todo } }?.done.first?.name
542 }
543
544559 private func markDone(_ item: AgendaItem) {
545 guard let keyword = doneKeyword(for: item) else { return }
560 guard let keyword = item.doneKeyword else { return }
546561 run(SetTodo(keyword: keyword), on: item)
547562 done += 1
548563 }
Sources/OrgstarMobile/MobileModel.swift +4 −2
@@ -237,8 +237,10 @@ final class MobileModel {
237237 return
238238 }
239239 guard !workspace.files.isEmpty else { return }
240 let agenda = AgendaModel(workspace: workspace)
240 // The agenda's cache and options, so files it has read aren't read again.
241 let agenda = AgendaModel(workspace: workspace, cache: self.agenda?.cache ?? AgendaSourceCache())
241242 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
243 if let options = self.agenda?.options { agenda.options = options }
242244 let reminders = await agenda.reminders(open: session.openTexts, lead: OrgPreferences.reminderLead())
243245 await scheduler.reconcile(reminders)
244246 }
@@ -249,7 +251,7 @@ final class MobileModel {
249251 let interval = Perf.begin("widgets.update")
250252 defer { interval.end() }
251253 guard let workspace, let file = AgendaSnapshot.file() else { return }
252 let days = AgendaModel(workspace: workspace)
254 let days = AgendaModel(workspace: workspace, cache: agenda?.cache ?? AgendaSourceCache())
253255 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
254256 if let agenda {
255257 days.includeSubfolders = agenda.includeSubfolders
Sources/OrgstarMobile/OrgstarMobileApp.swift +2
@@ -202,6 +202,8 @@ struct RootView: View {
202202 settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
203203 guard scenePhase == .active else { return }
204204 try? await Task.sleep(for: .seconds(1))
205 // After the agenda's refresh, whose parsed files these share.
206 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
205207 guard !Task.isCancelled else { return }
206208 await model.updateReminders()
207209 await model.updateWidgets()
Sources/OrgstarMobile/SpotlightIndexer.swift +16 −12
@@ -53,17 +53,22 @@ final class SpotlightIndexer {
5353 private func index(_ files: [FileEntry]) async {
5454 let generation = Data(state.generation.uuidString.utf8)
5555 let stamps = (try? await index.fetchLastClientState()) == generation ? state.stamps : [:]
56 var current: [String: Date] = [:]
57 var items: [CSSearchableItem] = []
58 for file in files where file.kind == .org {
59 guard let date = (try? FileManager.default.attributesOfItem(atPath: file.path))?[.modificationDate] as? Date else { continue }
60 if stamps[file.path] == date {
61 current[file.path] = date
62 } else if let text = try? String(contentsOfFile: file.path, encoding: .utf8) {
63 items.append(Self.item(file, text: text))
64 current[file.path] = date
56 // Reading and summarizing files stays off the main thread.
57 let (current, changed) = await Task.detached {
58 var current: [String: Date] = [:]
59 var changed: [(file: FileEntry, text: String, summary: FileSummary)] = []
60 for file in files where file.kind == .org {
61 guard let date = (try? FileManager.default.attributesOfItem(atPath: file.path))?[.modificationDate] as? Date else { continue }
62 if stamps[file.path] == date {
63 current[file.path] = date
64 } else if let text = try? String(contentsOfFile: file.path, encoding: .utf8) {
65 changed.append((file, text, FileSummary(text)))
66 current[file.path] = date
67 }
6568 }
66 }
69 return (current, changed)
70 }.value
71 let items = changed.map { Self.item($0.file, text: $0.text, summary: $0.summary) }
6772 let gone = stamps.keys.filter { current[$0] == nil }
6873 guard !items.isEmpty || !gone.isEmpty else { return }
6974 submit(items, removing: gone)
@@ -76,8 +81,7 @@ final class SpotlightIndexer {
7681 try? JSONEncoder().encode(state).write(to: stateFile, options: .atomic)
7782 }
7883
79 private static func item(_ file: FileEntry, text: String) -> CSSearchableItem {
80 let summary = FileSummary(text)
84 private static func item(_ file: FileEntry, text: String, summary: FileSummary) -> CSSearchableItem {
8185 let attributes = CSSearchableItemAttributeSet(contentType: .text)
8286 attributes.title = summary.title ?? (file.name as NSString).deletingPathExtension
8387 attributes.displayName = attributes.title
Tests/OrgAppTests/AppTests.swift +16 −13
@@ -234,19 +234,6 @@ struct DocumentSessionTests {
234234 #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
235235 }
236236
237 @Test func settingsForAFileUseDefaultsAndSetupFiles() throws {
238 let notes = try Folder()
239 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
240 let viaSetup = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
241 let plain = try notes.write("b.org", "* WAIT Two\n")
242 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
243 session.defaults = try #require(OrgSettings.default.withTodoKeywords("WAIT | OK"))
244 #expect(session.settings(for: viaSetup.path)?.todoSequences.first?.done.first?.name == "FINISHED")
245 #expect(session.settings(for: plain.path)?.todoSequences.first?.done.first?.name == "OK")
246 session.open(plain.path)
247 #expect(session.settings(for: plain.path)?.todoSequences.first?.done.first?.name == "OK")
248 #expect(session.settings(for: notes.url.appendingPathComponent("missing.org").path) == nil)
249 }
250237
251238 @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
252239 let notes = try Folder()
@@ -537,6 +524,22 @@ enum StateBufferCaret {
537524
538525@MainActor
539526struct AgendaModelTests {
527 @Test func entriesKnowTheirDoneKeyword() async throws {
528 let notes = try Folder()
529 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
530 try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
531 let plain = try notes.write("b.org", "* WAIT Two\n")
532 let model = try WorkspaceModel(directory: nil)
533 model.settings = .with(todoKeywords: try #require(OrgSettings.default.withTodoKeywords("WAIT | OK")))
534 try await model.addRoot(notes.url)
535 let agenda = AgendaModel(workspace: model)
536 agenda.mode = .todo(keywords: nil)
537 await agenda.refresh(open: [:])
538 #expect(Dictionary(uniqueKeysWithValues: agenda.list.map { ($0.todo ?? "", $0.doneKeyword) }) == ["NEXT": "FINISHED", "WAIT": "OK"])
539 await agenda.refresh(open: [plain.path: "#+TODO: WAIT | GONE\n* WAIT Two\n"])
540 #expect(agenda.list.first { $0.todo == "WAIT" }?.doneKeyword == "GONE")
541 }
542
540543 @Test func topLevelFilesAndTheOpenBuffer() async throws {
541544 let notes = try Folder()
542545 try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")