forked from manaflow-ai/cmux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionIndexStore.swift
More file actions
1636 lines (1514 loc) · 70.4 KB
/
SessionIndexStore.swift
File metadata and controls
1636 lines (1514 loc) · 70.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import Bonsplit
import Combine
import Foundation
import SQLite3
// MARK: - Agents
enum SessionAgent: String, CaseIterable, Identifiable, Hashable, Codable {
case claude
case codex
case opencode
var id: String { rawValue }
var displayName: String {
switch self {
case .claude: return String(localized: "sessionIndex.agent.claude", defaultValue: "Claude Code")
case .codex: return String(localized: "sessionIndex.agent.codex", defaultValue: "Codex")
case .opencode: return String(localized: "sessionIndex.agent.opencode", defaultValue: "OpenCode")
}
}
/// Asset catalog image name for the agent's brand mark.
var assetName: String {
switch self {
case .claude: return "AgentIcons/Claude"
case .codex: return "AgentIcons/Codex"
case .opencode: return "AgentIcons/OpenCode"
}
}
}
// MARK: - Session entry
struct PullRequestLink: Hashable {
let number: Int
let url: String
let repository: String?
}
/// Agent-specific fields used to build the resume command with appropriate flags.
enum AgentSpecifics: Hashable {
case claude(model: String?, permissionMode: String?)
case codex(model: String?, approvalPolicy: String?, sandboxMode: String?, effort: String?)
case opencode(providerModel: String?, agentName: String?)
}
struct SessionEntry: Identifiable, Hashable {
let id: String
let agent: SessionAgent
/// Native session identifier for the agent's CLI (used to build the resume command).
let sessionId: String
let title: String
let cwd: String?
let gitBranch: String?
let pullRequest: PullRequestLink?
let modified: Date
let fileURL: URL?
let specifics: AgentSpecifics
/// Shell command that resumes this session in a new terminal, with the agent's
/// known per-session settings injected as CLI flags.
var resumeCommand: String {
switch specifics {
case let .claude(model, permissionMode):
var parts = ["claude --resume \(sessionId)"]
if let model, !model.isEmpty {
parts.append("--model \(Self.shellQuote(model))")
}
if let permissionMode, !permissionMode.isEmpty {
parts.append("--permission-mode \(Self.shellQuote(permissionMode))")
}
return parts.joined(separator: " ")
case let .codex(model, approval, sandbox, effort):
var parts = ["codex resume \(sessionId)"]
if let model, !model.isEmpty {
parts.append("-m \(Self.shellQuote(model))")
}
if let approval, !approval.isEmpty {
parts.append("-a \(Self.shellQuote(approval))")
}
if let sandbox, !sandbox.isEmpty {
parts.append("-s \(Self.shellQuote(sandbox))")
}
if let effort, !effort.isEmpty {
parts.append("-c model_reasoning_effort=\(Self.shellQuote(effort))")
}
return parts.joined(separator: " ")
case let .opencode(providerModel, agentName):
var parts = ["opencode --session \(sessionId)"]
if let providerModel, !providerModel.isEmpty {
parts.append("-m \(Self.shellQuote(providerModel))")
}
if let agentName, !agentName.isEmpty {
parts.append("--agent \(Self.shellQuote(agentName))")
}
return parts.joined(separator: " ")
}
}
/// Single-quote a value for safe shell injection. Escapes embedded single quotes.
private static func shellQuote(_ value: String) -> String {
if value.range(of: "[^A-Za-z0-9_./:=+-]", options: .regularExpression) == nil {
return value
}
let escaped = value.replacingOccurrences(of: "'", with: #"'\''"#)
return "'\(escaped)'"
}
var displayTitle: String {
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
return String(localized: "sessionIndex.untitled", defaultValue: "Untitled session")
}
return trimmed
}
var cwdLabel: String? {
guard let cwd, !cwd.isEmpty else { return nil }
let home = NSHomeDirectory()
// Compare on a path boundary so /Users/al doesn't get matched by a
// home of /Users/alice (would render as "~ice/foo").
if cwd == home {
return "~"
}
if cwd.hasPrefix(home + "/") {
return "~" + cwd.dropFirst(home.count)
}
return cwd
}
var cwdBasename: String? {
guard let cwd, !cwd.isEmpty else { return nil }
return (cwd as NSString).lastPathComponent
}
}
// MARK: - Parsed metadata cache
/// Process-wide cache for parsed Claude session metadata, keyed by file URL with
/// mtime as the freshness check. Avoids re-reading and re-parsing the same
/// jsonls across pagination calls. Bounded by `maxEntries` to keep memory in
/// check (LRU on insert).
final class ClaudeMetadataCache: @unchecked Sendable {
static let shared = ClaudeMetadataCache()
private let maxEntries = 1000
private let lock = NSLock()
private var entries: [URL: (mtime: Date, entry: SessionEntry)] = [:]
func get(url: URL, mtime: Date) -> SessionEntry? {
lock.lock()
defer { lock.unlock() }
guard let cached = entries[url], cached.mtime == mtime else { return nil }
return cached.entry
}
func put(url: URL, mtime: Date, entry: SessionEntry) {
lock.lock()
defer { lock.unlock() }
entries[url] = (mtime, entry)
if entries.count > maxEntries {
// Evict ~10% (oldest mtimes) to amortize cleanup cost.
let evictCount = entries.count / 10
let oldestKeys = entries
.sorted { $0.value.mtime < $1.value.mtime }
.prefix(evictCount)
.map(\.key)
for k in oldestKeys { entries.removeValue(forKey: k) }
}
}
}
// MARK: - Drag registry
/// Process-wide registry that pairs a synthetic drag UUID with a SessionEntry.
/// Used to forward sessions through bonsplit's external-tab-drop hook (which only
/// carries UUIDs in its payload). Workspace.handleExternalTabDrop consults this
/// to decide whether a drop should spawn a brand new terminal vs. move an existing tab.
final class SessionDragRegistry {
static let shared = SessionDragRegistry()
private let lock = NSLock()
private var pending: [UUID: SessionEntry] = [:]
func register(_ entry: SessionEntry) -> UUID {
let id = UUID()
lock.lock()
pending[id] = entry
lock.unlock()
// Auto-expire so a cancelled drag doesn't leak forever.
DispatchQueue.global().asyncAfter(deadline: .now() + 60) { [weak self] in
self?.lock.lock()
self?.pending.removeValue(forKey: id)
self?.lock.unlock()
}
return id
}
func consume(id: UUID) -> SessionEntry? {
lock.lock()
defer { lock.unlock() }
return pending.removeValue(forKey: id)
}
}
// MARK: - Store
enum SessionGrouping: String, CaseIterable, Identifiable, Codable {
case directory
case agent
var id: String { rawValue }
var label: String {
switch self {
case .directory: return String(localized: "sessionIndex.group.directory", defaultValue: "By folder")
case .agent: return String(localized: "sessionIndex.group.agent", defaultValue: "By agent")
}
}
var symbolName: String {
switch self {
case .directory: return "folder"
case .agent: return "person.2"
}
}
}
/// Identifier for a section in the index. For agent grouping, raw value is `agent:<rawValue>`;
/// for directory grouping, `dir:<absolute path>` (or `dir:` for unknown).
struct SectionKey: Hashable {
let raw: String
static func agent(_ a: SessionAgent) -> SectionKey { SectionKey(raw: "agent:" + a.rawValue) }
static func directory(_ path: String?) -> SectionKey { SectionKey(raw: "dir:" + (path ?? "")) }
}
struct IndexSection: Identifiable, Equatable {
let key: SectionKey
let title: String
let icon: SectionIcon
let entries: [SessionEntry]
var id: SectionKey { key }
}
enum SectionIcon: Equatable {
case agent(SessionAgent)
case folder
}
/// Owns the "which section is currently being dragged" bit, separate from
/// `SessionIndexStore`. Isolating this means drag start/end does not emit
/// `objectWillChange` on the data store, so rows and gaps don't re-render
/// every time a drag begins or clears.
@MainActor
final class SessionDragCoordinator: ObservableObject {
@Published var draggedKey: SectionKey? = nil
}
/// Immutable per-directory snapshot consumed by `SectionPopoverView` for
/// empty-query scrolling. All entries are merged across the three agent
/// sources and sorted by `modified` desc. The popover slices this array
/// in-memory to page, so scrolling fires zero store/disk calls.
struct DirectorySnapshot: Sendable {
let cwd: String // "" represents the unknown-folder bucket
let entries: [SessionEntry]
let errors: [String]
}
@MainActor
final class SessionIndexStore: ObservableObject {
@Published private(set) var entries: [SessionEntry] = [] {
didSet {
guard entries != oldValue else { return }
invalidateSectionsCache()
}
}
@Published private(set) var isLoading: Bool = false
@Published var scopeToCurrentDirectory: Bool = false {
didSet {
guard scopeToCurrentDirectory != oldValue else { return }
invalidateSectionsCache()
}
}
@Published var currentDirectory: String? = nil {
didSet {
guard scopeToCurrentDirectory, currentDirectory != oldValue else { return }
invalidateSectionsCache()
}
}
@Published var grouping: SessionGrouping {
didSet {
guard grouping != oldValue else { return }
UserDefaults.standard.set(grouping.rawValue, forKey: Self.groupingKey)
invalidateSectionsCache()
// Switching into directory grouping can expose cwds that were never
// backfilled while the user was viewing agent grouping.
if grouping == .directory { backfillDirectoryOrderFromEntries() }
}
}
/// Persisted order for agent sections.
@Published var agentOrder: [SessionAgent] {
didSet {
guard agentOrder != oldValue else { return }
Self.persistAgentOrder(agentOrder)
invalidateSectionsCache()
}
}
/// Persisted order for directory sections (absolute paths; "" means "no folder").
@Published var directoryOrder: [String] {
didSet {
guard directoryOrder != oldValue else { return }
Self.persistDirectoryOrder(directoryOrder)
invalidateSectionsCache()
}
}
private static let groupingKey = "sessionIndex.grouping"
private static let agentOrderDefaultsKey = "sessionIndex.agentOrder"
private static let directoryOrderDefaultsKey = "sessionIndex.directoryOrder"
private var sectionsCacheRevision: UInt64 = 0
private var cachedSectionsRevision: UInt64?
private var cachedSections: [IndexSection] = []
init() {
self.agentOrder = Self.loadAgentOrder()
self.directoryOrder = Self.loadDirectoryOrder()
let storedGrouping = UserDefaults.standard.string(forKey: Self.groupingKey)
self.grouping = SessionGrouping(rawValue: storedGrouping ?? "") ?? .directory
}
/// Returns the sections for the current grouping mode, in the user-saved order.
func sectionsForCurrentGrouping() -> [IndexSection] {
if cachedSectionsRevision == sectionsCacheRevision {
return cachedSections
}
let visible = filteredEntriesForCurrentScope()
let sections: [IndexSection]
switch grouping {
case .agent:
sections = agentOrder.map { agent in
IndexSection(
key: .agent(agent),
title: agent.displayName,
icon: .agent(agent),
entries: visible.filter { $0.agent == agent }
)
}
case .directory:
let buckets = Dictionary(grouping: visible) { $0.cwd ?? "" }
// Any cwds that aren't yet in the saved order still need to show
// up. They get appended by most-recent activity, purely locally,
// without mutating `directoryOrder` from inside this view-body
// computation — scheduling a Task here created a state-update
// feedback loop that pegged the main thread at 100% CPU.
// Persistent backfill happens via `backfillDirectoryOrderFromEntries`,
// called from `reload()` and `grouping.didSet`.
let knownPaths = Set(directoryOrder)
let unknownSorted = buckets.keys
.filter { !knownPaths.contains($0) }
.sorted { lhs, rhs in
let lMax = buckets[lhs]?.map(\.modified).max() ?? .distantPast
let rMax = buckets[rhs]?.map(\.modified).max() ?? .distantPast
return lMax > rMax
}
sections = (directoryOrder + unknownSorted)
.filter { buckets[$0] != nil }
.map { path in
IndexSection(
key: .directory(path.isEmpty ? nil : path),
title: directoryDisplayName(path),
icon: .folder,
entries: buckets[path] ?? []
)
}
}
cachedSections = sections
cachedSectionsRevision = sectionsCacheRevision
return sections
}
/// Extend `directoryOrder` with any cwds seen in `entries` that aren't
/// already tracked. Kept out of the view-body path: it mutates `@Published`
/// state and must only run in response to real data changes (new scan
/// results, grouping switch) — not on every SwiftUI update tick.
private func backfillDirectoryOrderFromEntries() {
var seen = Set(directoryOrder)
var additions: [(path: String, latest: Date)] = []
for entry in entries {
let path = entry.cwd ?? ""
if seen.insert(path).inserted {
additions.append((path, entry.modified))
} else if let idx = additions.firstIndex(where: { $0.path == path }),
additions[idx].latest < entry.modified {
additions[idx].latest = entry.modified
}
}
guard !additions.isEmpty else { return }
additions.sort { $0.latest > $1.latest }
directoryOrder.append(contentsOf: additions.map(\.path))
}
private func invalidateSectionsCache() {
sectionsCacheRevision &+= 1
}
private func filteredEntriesForCurrentScope() -> [SessionEntry] {
guard scopeToCurrentDirectory, let dir = normalizedDirectory(currentDirectory) else {
return entries
}
return entries.filter { entry in
guard let cwd = normalizedDirectory(entry.cwd) else { return false }
return cwd == dir || cwd.hasPrefix(dir + "/")
}
}
private func directoryDisplayName(_ path: String) -> String {
if path.isEmpty {
return String(localized: "sessionIndex.directory.unknown", defaultValue: "(no folder)")
}
return (path as NSString).lastPathComponent
}
/// Move `key` so it lands immediately before `referenceKey` in the
/// persisted order (or at the end if `referenceKey` is nil). Anchoring
/// to a neighbor key (rather than a positional index) means scope filters
/// can hide some sections without corrupting reorders: hidden sections
/// keep their relative position to their visible neighbors.
func moveSection(_ key: SectionKey, before referenceKey: SectionKey?) {
switch grouping {
case .agent:
guard key.raw.hasPrefix("agent:"),
let agent = SessionAgent(rawValue: String(key.raw.dropFirst("agent:".count))) else { return }
guard let oldIndex = agentOrder.firstIndex(of: agent) else { return }
var next = agentOrder
next.remove(at: oldIndex)
if let referenceKey,
referenceKey.raw.hasPrefix("agent:"),
let refAgent = SessionAgent(rawValue: String(referenceKey.raw.dropFirst("agent:".count))),
let refIndex = next.firstIndex(of: refAgent) {
next.insert(agent, at: refIndex)
} else {
next.append(agent)
}
if next != agentOrder { agentOrder = next }
case .directory:
guard key.raw.hasPrefix("dir:") else { return }
let path = String(key.raw.dropFirst("dir:".count))
guard let oldIndex = directoryOrder.firstIndex(of: path) else { return }
var next = directoryOrder
next.remove(at: oldIndex)
if let referenceKey,
referenceKey.raw.hasPrefix("dir:") {
let refPath = String(referenceKey.raw.dropFirst("dir:".count))
if let refIndex = next.firstIndex(of: refPath) {
next.insert(path, at: refIndex)
} else {
next.append(path)
}
} else {
next.append(path)
}
if next != directoryOrder { directoryOrder = next }
}
}
private static func loadAgentOrder() -> [SessionAgent] {
let stored = UserDefaults.standard.array(forKey: agentOrderDefaultsKey) as? [String] ?? []
var ordered: [SessionAgent] = stored.compactMap { SessionAgent(rawValue: $0) }
for agent in SessionAgent.allCases where !ordered.contains(agent) {
ordered.append(agent)
}
var seen = Set<SessionAgent>()
ordered = ordered.filter { seen.insert($0).inserted }
return ordered
}
private static func loadDirectoryOrder() -> [String] {
UserDefaults.standard.array(forKey: directoryOrderDefaultsKey) as? [String] ?? []
}
private static func persistAgentOrder(_ order: [SessionAgent]) {
UserDefaults.standard.set(order.map { $0.rawValue }, forKey: agentOrderDefaultsKey)
}
private static func persistDirectoryOrder(_ order: [String]) {
UserDefaults.standard.set(order, forKey: directoryOrderDefaultsKey)
}
private var loadTask: Task<Void, Never>?
func reload() {
loadTask?.cancel()
isLoading = true
directorySnapshotGeneration += 1
invalidateDirectorySnapshots()
loadTask = Task.detached(priority: .userInitiated) { [weak self] in
let scanned = await Self.scanAll()
await MainActor.run {
guard let self else { return }
if Task.isCancelled { return }
self.entries = scanned
self.isLoading = false
self.backfillDirectoryOrderFromEntries()
}
}
}
// MARK: - Agent resume command lookup
/// Find the most recent session entries for a specific agent and cwd.
/// Runs the same loaders used by the sidebar scan but scoped to a single
/// agent + cwd, so it's cheap. Called from Workspace when an agent PID is
/// registered to cache the resume command off the autosave hot path.
nonisolated static func latestEntries(
agent: SessionAgent, cwd: String, limit: Int = 1
) async -> [SessionEntry] {
let bag = ErrorBag()
switch agent {
case .claude:
return await loadClaudeEntries(needle: "", cwdFilter: cwd, offset: 0, limit: limit)
case .codex:
return await loadCodexEntries(needle: "", cwdFilter: cwd, offset: 0, limit: limit, errorBag: bag)
case .opencode:
return loadOpenCodeEntries(needle: "", cwdFilter: cwd, offset: 0, limit: limit, errorBag: bag)
}
}
// MARK: - Directory snapshot cache
private var directorySnapshotCache: [String: DirectorySnapshot] = [:]
private var directorySnapshotLRU: [String] = []
/// Bumped on every `reload()`. Snapshot builds capture this at start;
/// if it changes before the build completes (reload raced with an
/// in-flight build), the build's result is discarded instead of
/// being written back into the cache — otherwise the stale
/// pre-reload result would repopulate the cache after invalidation
/// and be reused on the next popover open.
private var directorySnapshotGeneration: Int = 0
private static let directorySnapshotCacheCapacity = 16
/// Return a cached or freshly-built merged snapshot for a cwd-scoped
/// directory. Used by the Show-more popover's empty-query scroll
/// path: the popover slices this array in memory instead of asking
/// the store for more pages on every scroll, eliminating the O(n²)
/// repeated-refetch-and-merge behavior.
func loadDirectorySnapshot(cwd: String?) async -> DirectorySnapshot {
let key = cwd ?? ""
if let cached = touchDirectorySnapshotLRU(key) {
return cached
}
let generation = directorySnapshotGeneration
let bag = ErrorBag()
// The per-agent loaders interpret `cwdFilter == nil` as "no filter,
// return all entries". When `cwd` is nil here we specifically mean
// the "(no folder)" bucket — entries that genuinely have no cwd.
// Fetch unfiltered and post-filter locally to preserve that scope.
let noFolderScope = (cwd == nil) || ((cwd ?? "").isEmpty)
let cwdFilter = noFolderScope ? nil : cwd
// Large limit so every per-agent loader returns all matching rows.
// Claude's `searchMaxFiles` cap still applies (currently 1500); if
// anyone has more Claude sessions in a single cwd we'll bump it.
let bigLimit = 10_000
async let c = Self.timedAgent(
needle: "", agent: .claude, cwdFilter: cwdFilter,
offset: 0, limit: bigLimit, errorBag: bag
)
async let x = Self.timedAgent(
needle: "", agent: .codex, cwdFilter: cwdFilter,
offset: 0, limit: bigLimit, errorBag: bag
)
async let o = Self.timedAgent(
needle: "", agent: .opencode, cwdFilter: cwdFilter,
offset: 0, limit: bigLimit, errorBag: bag
)
var merged = (await c) + (await x) + (await o)
if Task.isCancelled {
return DirectorySnapshot(cwd: key, entries: [], errors: [])
}
if noFolderScope {
merged = merged.filter { ($0.cwd ?? "").isEmpty }
}
let sorted = merged.sorted { $0.modified > $1.modified }
let snapshot = DirectorySnapshot(cwd: key, entries: sorted, errors: bag.snapshot())
// Only cache this result if no `reload()` raced in while the
// build was running. Otherwise the caller gets a fresh snapshot
// but the cache stays invalidated; the next open will rebuild.
if generation == directorySnapshotGeneration {
storeDirectorySnapshot(key: key, snapshot: snapshot)
}
return snapshot
}
private func touchDirectorySnapshotLRU(_ key: String) -> DirectorySnapshot? {
guard let cached = directorySnapshotCache[key] else { return nil }
if let idx = directorySnapshotLRU.firstIndex(of: key) {
directorySnapshotLRU.remove(at: idx)
}
directorySnapshotLRU.append(key)
return cached
}
private func storeDirectorySnapshot(key: String, snapshot: DirectorySnapshot) {
if directorySnapshotCache[key] == nil,
directorySnapshotCache.count >= Self.directorySnapshotCacheCapacity,
let oldestKey = directorySnapshotLRU.first {
directorySnapshotCache.removeValue(forKey: oldestKey)
directorySnapshotLRU.removeFirst()
}
directorySnapshotCache[key] = snapshot
if let idx = directorySnapshotLRU.firstIndex(of: key) {
directorySnapshotLRU.remove(at: idx)
}
directorySnapshotLRU.append(key)
}
private func invalidateDirectorySnapshots() {
directorySnapshotCache.removeAll()
directorySnapshotLRU.removeAll()
}
private func normalizedDirectory(_ value: String?) -> String? {
guard let value, !value.isEmpty else { return nil }
var path = (value as NSString).standardizingPath
if path.count > 1 && path.hasSuffix("/") {
path.removeLast()
}
return path
}
// MARK: - Scanning
private static let perAgentLimit = 30
private static let headByteCap = 64 * 1024
private static let tailByteCap = 32 * 1024
/// Hard cap on candidate files inspected per call to keep deep-page searches bounded.
private static let searchMaxFiles = 1500
private static func scanAll() async -> [SessionEntry] {
// Initial scan errors are silently ignored — UI just shows the cached
// entries we did get. Errors get surfaced when the user actively
// searches via the popover.
let bag = ErrorBag()
async let claude = loadClaudeEntries(needle: "", cwdFilter: nil, offset: 0, limit: perAgentLimit)
async let codex = loadCodexEntries(needle: "", cwdFilter: nil, offset: 0, limit: perAgentLimit, errorBag: bag)
async let opencode = loadOpenCodeEntries(needle: "", cwdFilter: nil, offset: 0, limit: perAgentLimit, errorBag: bag)
let combined = await claude + codex + opencode
return combined.sorted { $0.modified > $1.modified }
}
private struct ClaudeParsed {
var title: String = ""
var cwd: String?
var branch: String?
var pr: PullRequestLink?
var model: String?
var permissionMode: String?
}
nonisolated private static func extractClaudeMetadata(head: String, tail: String, projectDir: String) -> ClaudeParsed {
var out = ClaudeParsed()
out.cwd = decodeClaudeProjectDir(projectDir)
for line in head.split(separator: "\n", omittingEmptySubsequences: true) {
guard let data = line.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue }
if let cwdField = obj["cwd"] as? String, !cwdField.isEmpty {
out.cwd = cwdField
}
if let branchField = obj["gitBranch"] as? String, !branchField.isEmpty {
out.branch = branchField
}
if let mode = obj["permissionMode"] as? String, !mode.isEmpty {
out.permissionMode = mode
}
if (obj["type"] as? String) == "assistant",
let message = obj["message"] as? [String: Any],
let model = message["model"] as? String, !model.isEmpty {
out.model = model
}
if out.title.isEmpty,
(obj["type"] as? String) == "user",
let message = obj["message"] as? [String: Any],
(message["role"] as? String) == "user" {
if let content = message["content"] as? String, !content.isEmpty {
out.title = content
} else if let parts = message["content"] as? [[String: Any]] {
for part in parts {
if (part["type"] as? String) == "text",
let text = part["text"] as? String, !text.isEmpty {
out.title = text
break
}
}
}
}
}
for line in tail.split(separator: "\n", omittingEmptySubsequences: true) {
guard let data = line.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue }
let type = obj["type"] as? String
if type == "pr-link", let number = obj["prNumber"] as? Int,
let url = obj["prUrl"] as? String {
out.pr = PullRequestLink(
number: number,
url: url,
repository: obj["prRepository"] as? String
)
}
if let branchField = obj["gitBranch"] as? String, !branchField.isEmpty {
out.branch = branchField
}
if let mode = obj["permissionMode"] as? String, !mode.isEmpty {
out.permissionMode = mode
}
if (obj["type"] as? String) == "assistant",
let message = obj["message"] as? [String: Any],
let model = message["model"] as? String, !model.isEmpty {
out.model = model
}
}
// Strip the [1m] suffix some Claude internal model IDs carry (claude-opus-4-7[1m]).
if let m = out.model, let bracket = m.firstIndex(of: "[") {
out.model = String(m[..<bracket])
}
return out
}
/// Returns a usable user-prompt string from a Codex `user_message` /
/// `response_item.input_text` payload, or nil when the message is just an
/// envelope/system wrapper (`<environment_context>...`, `<user_instructions>`,
/// `<permissions>`, AGENTS.md preamble) that we don't want to surface as a
/// session title.
nonisolated private static func realCodexUserMessage(_ raw: String) -> String? {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
let envelopePrefixes = [
"<environment_context",
"<user_instructions",
"<permissions",
"<system",
"# AGENTS.md",
]
for prefix in envelopePrefixes where trimmed.hasPrefix(prefix) {
return nil
}
return trimmed
}
nonisolated private static func decodeClaudeProjectDir(_ raw: String) -> String? {
// Claude encodes cwd by replacing "/" with "-" and prefixing "-"
// e.g. "-Users-lawrence-fun-cmuxterm-hq" -> "/Users/lawrence/fun/cmuxterm-hq".
// The encoding is lossy: a real path segment containing "-"
// (e.g. "my-cool-project") collapses to multiple segments
// ("/my/cool/project") on decode, which is wrong. Only return the
// candidate if it actually exists on disk; otherwise let the caller
// fall back to the JSONL `cwd` field.
guard !raw.isEmpty else { return nil }
let stripped = raw.hasPrefix("-") ? String(raw.dropFirst()) : raw
let candidate = "/" + stripped.replacingOccurrences(of: "-", with: "/")
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: candidate, isDirectory: &isDir),
isDir.boolValue else {
return nil
}
return candidate
}
/// Inverse of `decodeClaudeProjectDir`. Used as a fast path: when filtering
/// by cwd we can skip enumerating other project dirs entirely.
nonisolated private static func encodeClaudeProjectDir(_ path: String) -> String {
// "/Users/x/y" -> "-Users-x-y"
return path.replacingOccurrences(of: "/", with: "-")
}
// MARK: Codex
private struct CodexParsed {
var sessionId: String = ""
/// First user message — used only if Codex never assigns a thread_name.
var firstUserMessage: String = ""
/// Codex-generated session title (`event_msg.thread_name_updated`). Wins over firstUserMessage.
var threadName: String = ""
var cwd: String?
var branch: String?
var model: String?
var approvalPolicy: String?
var sandboxMode: String?
var effort: String?
var title: String {
threadName.isEmpty ? firstUserMessage : threadName
}
}
/// Cheap cwd peek for Codex rollouts. `session_meta` is always the first line
/// of the file, but the line itself can be 30+ KB (it embeds the full system
/// prompt). Read up to 64 KB to cover that, parse the JSON, return cwd.
nonisolated private static func peekCodexSessionMetaCwd(url: URL) -> String? {
let head = readFileHead(url: url, byteCap: headByteCap)
guard let nl = head.firstIndex(of: "\n") else { return nil }
let firstLine = head[..<nl]
guard let data = firstLine.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
(obj["type"] as? String) == "session_meta",
let payload = obj["payload"] as? [String: Any],
let cwd = payload["cwd"] as? String,
!cwd.isEmpty else {
return nil
}
return cwd
}
/// Stream lines from `url` until we have everything we need. The first user_message
/// can sit ~100 KB into a Codex rollout (after huge base_instructions + AGENTS.md),
/// so a fixed head buffer is unreliable.
nonisolated private static func extractCodexMetadata(url: URL) -> CodexParsed {
var out = CodexParsed()
let maxBytes = 4 * 1024 * 1024
forEachJSONLine(url: url, maxBytes: maxBytes) { obj in
let type = obj["type"] as? String
let payload = obj["payload"] as? [String: Any]
if type == "session_meta", let p = payload {
if let c = p["cwd"] as? String, !c.isEmpty { out.cwd = c }
if let id = p["id"] as? String, !id.isEmpty { out.sessionId = id }
if let git = p["git"] as? [String: Any],
let branch = git["branch"] as? String, !branch.isEmpty {
out.branch = branch
}
}
if type == "turn_context", let p = payload {
if let m = p["model"] as? String, !m.isEmpty { out.model = m }
if let a = p["approval_policy"] as? String, !a.isEmpty { out.approvalPolicy = a }
if let sandbox = p["sandbox_policy"] as? [String: Any],
let s = sandbox["type"] as? String, !s.isEmpty {
out.sandboxMode = s
}
if let e = p["effort"] as? String, !e.isEmpty { out.effort = e }
}
if type == "event_msg", let p = payload,
(p["type"] as? String) == "thread_name_updated",
let name = p["thread_name"] as? String, !name.isEmpty {
out.threadName = name
}
if out.firstUserMessage.isEmpty, type == "event_msg", let p = payload,
(p["type"] as? String) == "user_message",
let msg = p["message"] as? String,
let real = realCodexUserMessage(msg) {
out.firstUserMessage = real
}
if out.firstUserMessage.isEmpty, type == "response_item", let p = payload,
(p["type"] as? String) == "message",
(p["role"] as? String) == "user",
let content = p["content"] as? [[String: Any]] {
for part in content {
guard (part["type"] as? String) == "input_text",
let text = part["text"] as? String,
let real = realCodexUserMessage(text) else { continue }
out.firstUserMessage = real
break
}
}
// Stop early once we have a real thread name + the launch metadata. If no
// thread name appears we keep streaming until we at least have a user
// message — Codex emits thread_name_updated late in newer versions but it's
// still typically within the first few KB of events.
return !out.threadName.isEmpty
&& out.cwd != nil
&& out.branch != nil
&& !out.sessionId.isEmpty
&& out.model != nil
}
return out
}
/// Stream JSON-lines from the start of `url`. `body` returns true to stop early.
/// Caps total bytes read at `maxBytes`.
nonisolated private static func forEachJSONLine(
url: URL,
maxBytes: Int,
body: ([String: Any]) -> Bool
) {
guard let handle = try? FileHandle(forReadingFrom: url) else { return }
defer { try? handle.close() }
var leftover = Data()
var totalRead = 0
let chunkSize = 64 * 1024
while totalRead < maxBytes {
let chunk: Data
if #available(macOS 10.15.4, *) {
chunk = (try? handle.read(upToCount: chunkSize)) ?? Data()
} else {
chunk = handle.readData(ofLength: chunkSize)
}
if chunk.isEmpty { break }
totalRead += chunk.count
leftover.append(chunk)
while let nl = leftover.firstIndex(of: 0x0a) {
let lineData = leftover.subdata(in: 0..<nl)
leftover.removeSubrange(0..<(nl + 1))
if lineData.isEmpty { continue }
if let obj = try? JSONSerialization.jsonObject(with: lineData) as? [String: Any] {
if body(obj) { return }
}
}
}
// Flush trailing line if no newline at EOF.
if !leftover.isEmpty,
let obj = try? JSONSerialization.jsonObject(with: leftover) as? [String: Any] {
_ = body(obj)
}
}
// MARK: OpenCode
nonisolated private static func parseOpenCodeAssistant(_ raw: String?) -> (String?, String?) {
guard let raw, let data = raw.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return (nil, nil)
}
let modelID = obj["modelID"] as? String
let providerID = obj["providerID"] as? String
let agentName = obj["agent"] as? String
let providerModel: String? = {
switch (providerID, modelID) {
case let (p?, m?) where !p.isEmpty && !m.isEmpty: return "\(p)/\(m)"
case let (_, m?) where !m.isEmpty: return m
default: return nil
}
}()
return (providerModel, agentName?.isEmpty == false ? agentName : nil)
}
nonisolated private static func sqliteText(_ stmt: OpaquePointer, _ index: Int32) -> String? {
guard let cString = sqlite3_column_text(stmt, index) else { return nil }
return String(cString: cString)
}
nonisolated private static func sqliteMessage(_ db: OpaquePointer?) -> String? {
guard let db, let cString = sqlite3_errmsg(db) else { return nil }
return String(cString: cString)
}
// MARK: - Deep search (popover "Show more")
enum SearchScope {
case agent(SessionAgent)
/// Filter by absolute cwd; nil/"" = unknown-folder bucket.
case directory(String?)
}
/// What the popover gets back. `errors` is non-empty when one or more
/// agents failed to read their data source (schema mismatch, file missing,
/// SQL error). UI should surface them so users see why the list looks
/// short or empty rather than thinking nothing matched.
struct SearchOutcome: Sendable {
var entries: [SessionEntry]
var errors: [String]
}
/// Thread-safe accumulator passed down to per-agent helpers so they can
/// report failures (e.g. SQL prepare errors when an agent bumps its
/// schema) without requiring the helpers to throw across actor boundaries.
final class ErrorBag: @unchecked Sendable {
private let lock = NSLock()
private var messages: [String] = []
func add(_ msg: String) {
lock.lock(); defer { lock.unlock() }
messages.append(msg)
}
func snapshot() -> [String] {
lock.lock(); defer { lock.unlock() }
return messages
}
}
/// Paginated on-demand search across the full filesystem (Claude/Codex) and
/// SQLite (OpenCode). Empty query is allowed and returns the most-recent
/// entries (used when the user just opens the popover and scrolls).
/// Returns up to `limit` entries sorted by mtime desc, skipping the first
/// `offset` matches.
func searchSessions(
query: String,
scope: SearchScope,
offset: Int,
limit: Int
) async -> SearchOutcome {
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
let needle = trimmed.lowercased()
let bag = ErrorBag()
#if DEBUG