diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 87c0fcb1f1f0..dde7e11b9a53 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -42,7 +42,7 @@ reviews: Apply `.github/review-bot-rules/algorithmic-complexity.md` during review. For production code over scalable user data, flag nested full-collection scans, per-target rescans for batch actions, repeated sort/filter/map work in hot paths, in-memory joins that belong in the data store, and unbenchmarked algorithm choices for paths expected to handle roughly 1000 workspaces or similar records. Pass for tiny fixed-size collections, tests and benchmark harnesses, existing inefficient code not worsened, and documented bounds with measurements. - path: "**/*.swift" instructions: | - Apply `.github/review-bot-rules/swift-expensive-sync-load.md` during review. Flag heavy synchronous loaders (the canonical case is `RestorableAgentSessionIndex.load()`: per-record `sysctl` plus disk reads, 350ms-1.8s) added to or moved onto the main actor or interactive paths (workspace/panel/tab/window close, SwiftUI body, didSet, menu evaluation, socket handlers). Require routing through the off-main cached accessor `SharedLiveAgentIndex.shared`. Pass for the cache's own background loader and explicit cold-cache fallbacks guarded by a nil check. + Apply `.github/review-bot-rules/swift-expensive-sync-load.md` during review. Flag heavy synchronous agent-history loads added to or moved onto the main actor or interactive paths (workspace/panel/tab/window close, SwiftUI body, didSet, menu/command-palette/shortcut evaluation, socket handlers). This includes `RestorableAgentSessionIndex.load()`, agent hook/session stores, `agent-turn-diff-baselines.json`, transcripts, trajectory files, workstream/event JSONL logs, broad directory scans, per-record syscalls, and large JSON/JSONL parsing. Require routing through `SharedLiveAgentIndex.shared`, a `Task.detached`/background actor/repository parser, or another off-main cached path. Pass for the cache/background loader itself and explicit cold-cache fallbacks guarded by a nil check. - path: "**/*.{swift,ts,tsx,js,jsx,mjs,cjs}" instructions: | Apply `.github/review-bot-rules/cache-substitution-correctness.md` during review. When the diff replaces a fresh authoritative read with a cached value in a persistence, history, undo, or snapshot path, require explicit handling of cold (never-loaded) and stale (older-than-source) caches, or a documented graceful-degradation rationale. Pass for transient non-persisted UI hints and documented staleness tolerance. @@ -78,7 +78,7 @@ reviews: - name: "cmux expensive synchronous load" mode: error instructions: | - For production Swift changes, fail when the diff adds or moves an expensive synchronous loader onto the main actor or an interactive path per `.github/review-bot-rules/swift-expensive-sync-load.md`: the canonical case is `RestorableAgentSessionIndex.load()` (per-record `sysctl` plus disk reads) on workspace/panel/tab/window close, SwiftUI body/didSet, menu or command-palette evaluation, or socket handlers. Require the off-main cached accessor `SharedLiveAgentIndex.shared`. Pass for the cache's own `Task.detached` loader, explicit cold-cache fallbacks guarded by a nil check, and existing call sites not worsened. + For production Swift changes, fail when the diff adds or moves an expensive synchronous agent-history load onto the main actor or an interactive path per `.github/review-bot-rules/swift-expensive-sync-load.md`: `RestorableAgentSessionIndex.load()`, agent hook/session stores, `agent-turn-diff-baselines.json`, transcripts, trajectory files, workstream/event JSONL logs, broad directory scans, per-record syscalls, or large JSON/JSONL parsing in workspace/panel/tab/window close, SwiftUI body/didSet, menu/command-palette/shortcut evaluation, or socket handlers. Require `SharedLiveAgentIndex.shared`, a `Task.detached`/background actor/repository parser, or another off-main cached path that returns to MainActor only for UI/process launch work. Pass for the cache/background loader itself, explicit cold-cache fallbacks guarded by a nil check, and existing call sites not worsened. - name: "cmux cache substitution correctness" mode: error instructions: | diff --git a/.github/review-bot-rules/swift-expensive-sync-load.md b/.github/review-bot-rules/swift-expensive-sync-load.md index ef1b6e7f4f7e..6bca279085f1 100644 --- a/.github/review-bot-rules/swift-expensive-sync-load.md +++ b/.github/review-bot-rules/swift-expensive-sync-load.md @@ -1,8 +1,12 @@ -# Swift Expensive Synchronous Index Loads +# Swift Expensive Synchronous Agent Loads -Flag heavy synchronous disk/syscall loads on the main actor or in interactive paths. +Flag heavy synchronous agent-history disk, JSON, transcript, trajectory, or syscall loads on the main actor or in interactive paths. -Report a failure when the diff adds or moves a call to an expensive whole-corpus loader onto a latency-sensitive path in non-test Swift. The canonical case is `RestorableAgentSessionIndex.load()`, which reads every agent kind's hook-store file from disk, resolves transcripts, and runs `sysctl(KERN_PROCARGS2)` per recorded session (measured 350ms-1.8s on machines with large agent history, and it scales with agent history, not tab count). Treat any similarly heavy synchronous loader the same way: full-directory scans, per-record syscalls, or broad JSON decode of unbounded files. +Report a failure when the diff adds or moves a call to an expensive whole-corpus loader onto a latency-sensitive path in non-test Swift. The canonical case is `RestorableAgentSessionIndex.load()`, which reads every agent kind's hook-store file from disk, resolves transcripts, and runs `sysctl(KERN_PROCARGS2)` per recorded session (measured 350ms-1.8s on machines with large agent history, and it scales with agent history, not tab count). + +Also fail synchronous parsing or decoding of unbounded agent-owned files on the main actor or from user-input paths. This includes agent hook/session stores, `agent-turn-diff-baselines.json`, transcript files, trajectory files, workstream/event logs, or any large JSON/JSONL file whose size grows with agent history. A single `Data(contentsOf:)`, `String(contentsOf:)`, `JSONSerialization.jsonObject`, `JSONDecoder.decode`, line scan, directory walk, or per-record `fileExists`/stat loop is enough to flag when it can run on `@MainActor`, in menu/command-palette handling, shortcut handling, socket handlers, SwiftUI render paths, close/history paths, or other immediate UI interactions. + +Treat any similarly heavy synchronous loader the same way: full-directory scans, per-record syscalls, broad JSON decode of unbounded files, or parsing that scales with all agent history instead of the focused workspace/surface/session. Interactive / main-actor paths where this must not appear: @@ -14,14 +18,17 @@ Interactive / main-actor paths where this must not appear: Required shape: - Read the off-main, cached accessor instead (in cmux: `SharedLiveAgentIndex.shared`), which loads on a background task and serves a cached result. +- Move unavoidable large-file reads/parses into a non-main `Task.detached`, actor, or repository/service method with an explicit actor hop back to `@MainActor` only for UI/process launch work. +- Bound the scan to the focused workspace, surface, session, or target key as early as practical; avoid sorting or materializing the whole file when only the newest matching record is needed. - A synchronous load is allowed only as a cold-cache fallback guarded by a nil-cache check, or inside the cache's own off-main loader. Such call sites should carry a brief justification comment. Allowed cases: - The cache's own background loader (`Task.detached`). +- A background parser that returns a small value and then hops back to `@MainActor` for UI work. - An explicit cold-cache fallback such as `cache ?? RestorableAgentSessionIndex.load()`. - Existing call sites the PR does not introduce or worsen. -When reporting, name the heavy loader, the interactive path it now runs on, and the cached/off-main accessor that should replace it. +When reporting, name the heavy loader or large agent file, the interactive path it now runs on, and the cached/off-main accessor or background parser that should replace it. Background: this rule exists because a synchronous `RestorableAgentSessionIndex.load()` added to the workspace/tab close paths froze the UI 350ms-1.8s on every close (https://github.com/manaflow-ai/cmux/pull/5669). diff --git a/.greptile/config.json b/.greptile/config.json index 479e08a5d5db..38a2706f9af0 100644 --- a/.greptile/config.json +++ b/.greptile/config.json @@ -60,6 +60,12 @@ "scope": ["**/*.swift", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mjs", "**/*.cjs", "**/*.sh", "**/*.zsh"], "severity": "high" }, + { + "id": "cmux-swift-expensive-sync-load", + "rule": "Flag production Swift that reads, decodes, or scans unbounded agent-history data on the main actor or interactive paths: RestorableAgentSessionIndex.load(), agent hook/session stores, agent-turn-diff-baselines.json, transcript files, trajectory files, workstream/event JSONL logs, broad directory scans, per-record syscalls, or large JSON/JSONL parsing. Require SharedLiveAgentIndex.shared, Task.detached, a background actor/repository parser, or another off-main cached path that returns to MainActor only for UI/process launch work. Pass for the cache/background loader itself, explicit nil-cache fallbacks with justification, and existing call sites not worsened.", + "scope": ["**/*.swift", "**/Package.swift"], + "severity": "high" + }, { "id": "cmux-swiftui-state-layout", "rule": "Flag SwiftUI changes that can cause stale state, broad invalidation, layout instability, or main-thread churn: new ObservableObject/@Published state where @Observable is correct, GeometryReader measurement that changes layout, lazy/list row subtrees holding store references, or state mutation during body rendering.", diff --git a/.greptile/files.json b/.greptile/files.json index b439a3e60a0a..6e6e869d599b 100644 --- a/.greptile/files.json +++ b/.greptile/files.json @@ -30,6 +30,11 @@ "description": "Source-of-truth cmux review rule for scalable collection algorithms and benchmark-backed complexity choices.", "scope": ["**/*.swift", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mjs", "**/*.cjs", "**/*.sh", "**/*.zsh"] }, + { + "path": ".github/review-bot-rules/swift-expensive-sync-load.md", + "description": "Source-of-truth cmux review rule for keeping large agent-history JSON, transcript, trajectory, and syscall loads off MainActor and interactive Swift paths.", + "scope": ["**/*.swift", "**/Package.swift"] + }, { "path": ".github/review-bot-rules/swift-concurrency-modernization.md", "description": "Source-of-truth cmux lint rule for Swift concurrency modernization review.", diff --git a/.greptile/rules.md b/.greptile/rules.md index f65daac2cc01..994bc605188e 100644 --- a/.greptile/rules.md +++ b/.greptile/rules.md @@ -18,7 +18,7 @@ Review production Swift and runtime changes for: - Architectural fixes that patch symptoms while leaving bad state representable. - User-facing errors, alerts, command output, API error bodies, and recovery copy that expose implementation details. - Algorithmic complexity regressions on scalable user-owned collections. -- Expensive synchronous index/disk/syscall loads (such as `RestorableAgentSessionIndex.load()`) on the main actor or interactive paths instead of the off-main cached accessor. +- Expensive synchronous agent-history disk, JSON, transcript, trajectory, JSONL, directory, or syscall loads (such as `RestorableAgentSessionIndex.load()`, hook/session stores, `agent-turn-diff-baselines.json`, transcripts, trajectory files, and workstream/event logs) on the main actor or interactive paths instead of an off-main cached/background accessor. - Substituting a cached value for a fresh authoritative read in persistence/history/undo paths without handling cold and stale caches. - Local/generated artifacts, dependency checkouts, caches, logs, screenshots, temp folders, and scratch directories that accidentally enter source control. - SwiftPM dependency changes that ignore or omit cmux-owned `Package.resolved` lockfiles. @@ -54,6 +54,14 @@ For production code over scalable user-owned collections, flag nested full-colle Pass for tiny fixed-size collections, tests, benchmark harnesses, existing inefficient code not worsened by the PR, and documented bounds backed by measurements. +## Swift Expensive Synchronous Agent Loads + +For production Swift, flag any unbounded agent-history read, decode, parse, directory scan, or per-record syscall that can run on MainActor or from user-input paths. + +Fail synchronous `Data(contentsOf:)`, `String(contentsOf:)`, `JSONSerialization.jsonObject`, `JSONDecoder.decode`, JSONL line scans, transcript/trajectory parsing, `agent-turn-diff-baselines.json` scans, hook/session-store reads, workstream/event log scans, or per-record `fileExists`/stat/sysctl loops when they run in workspace/panel/tab/window close, SwiftUI body/didSet, menu/command-palette/shortcut evaluation, socket handlers, or any immediate UI interaction. These files can grow with all agent history and have caused UI hangs on real machines. + +Require `SharedLiveAgentIndex.shared`, a `Task.detached` parser, a background actor/repository, or another off-main cached path that returns to MainActor only for UI/process launch work. Bound scans by focused workspace/surface/session as early as practical. Pass for the cache/background loader itself, explicit nil-cache fallbacks with a justification, and existing call sites the PR does not worsen. + ## Source Control Artifacts For every changed path, flag local tool output, generated logs, screenshots, recordings, temp folders, dependency checkouts, caches, build output, DerivedData, package-manager downloads, and broad scratch directories that enter source control without a deliberate product, docs, fixture, build, release, or test-system reason. diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index e8a9960fe6cc..7854f64f3cff 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -956,6 +956,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent /// Live `cmux diff` viewer subprocesses, keyed by pid, retained until they exit. /// Declared outside `#if DEBUG` because process retention is production behavior. private var diffViewerProcesses: [Int32: Process] = [:] + /// In-flight agent-aware diff launches, keyed so repeated shortcuts do not fan out large baseline parses. + var openDiffViewerAgentContextTasks: [String: Task] = [:] + var openDiffViewerAgentContextPendingRequests: [String: OpenDiffViewerAgentContextRequest] = [:] #if DEBUG private var didSetupJumpUnreadUITest = false @@ -6076,113 +6079,79 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent let socketPath = TerminalController.shared.activeSocketPath( preferredPath: SocketControlSettings.socketPath() ) - let agentDiffContext = preferAgentContext ? focusedAgentDiffContext(for: workspace) : nil - let cwd = agentDiffContext?.cwd - ?? workspace.resolvedWorkingDirectory() + let fallbackCwd = workspace.resolvedWorkingDirectory() ?? FileManager.default.homeDirectoryForCurrentUser.path + if preferAgentContext, + let surfaceId = workspace.focusedPanelId, + let snapshot = SharedLiveAgentIndex.shared.snapshot(workspaceId: workspace.id, panelId: surfaceId), + let sessionId = Self.normalizedOpenDiffViewerSessionId(snapshot.sessionId) { + let snapshotWorkingDirectory = Self.normalizedOpenDiffViewerPath( + snapshot.workingDirectory ?? snapshot.launchCommand?.workingDirectory + ) + let storeURL = Self.agentTurnDiffBaselineStoreURL() + let workspaceId = workspace.id + let originWindowId = tabManager.flatMap { manager in + mainWindowContexts.values.first { $0.tabManager === manager }?.windowId + } + let taskKey = Self.openDiffViewerAgentContextTaskKey( + workspaceId: workspaceId, + surfaceId: surfaceId, + sessionId: sessionId + ) + let request = OpenDiffViewerAgentContextRequest( + cliURL: cliURL, + socketPath: socketPath, + fallbackCwd: fallbackCwd, + snapshotWorkingDirectory: snapshotWorkingDirectory, + storeURL: storeURL, + workspaceId: workspaceId, + surfaceId: surfaceId, + sessionId: sessionId, + originWindowId: originWindowId + ) + if openDiffViewerAgentContextTasks[taskKey] != nil { + openDiffViewerAgentContextPendingRequests[taskKey] = request + } else { + startOpenDiffViewerAgentContextTask(request, taskKey: taskKey) + } + return true + } + let agentDiffContext = preferAgentContext ? focusedAgentWorkingDirectoryContext(for: workspace) : nil return launchDiffViewerProcess( cliURL: cliURL, socketPath: socketPath, - cwd: cwd, + cwd: agentDiffContext?.cwd ?? fallbackCwd, workspaceId: workspace.id, surfaceId: workspace.focusedPanelId, - useLastTurnSource: agentDiffContext?.useLastTurnSource == true, + useLastTurnSource: false, sessionId: agentDiffContext?.sessionId ) } - private func focusedAgentDiffContext(for workspace: Workspace) -> (cwd: String, useLastTurnSource: Bool, sessionId: String?)? { + private func focusedAgentWorkingDirectoryContext(for workspace: Workspace) -> (cwd: String, sessionId: String?)? { guard let surfaceId = workspace.focusedPanelId else { return nil } guard let snapshot = SharedLiveAgentIndex.shared.snapshot(workspaceId: workspace.id, panelId: surfaceId) else { return nil } - let sessionId = normalizedOpenDiffViewerSessionId(snapshot.sessionId) - if let sessionId, - let repoRoot = latestAgentTurnDiffRepoRoot( - workspaceId: workspace.id, - surfaceId: surfaceId, - sessionId: sessionId - ) { - return (cwd: repoRoot, useLastTurnSource: true, sessionId: sessionId) - } - if let workingDirectory = normalizedOpenDiffViewerPath( + let sessionId = Self.normalizedOpenDiffViewerSessionId(snapshot.sessionId) + if let workingDirectory = Self.normalizedOpenDiffViewerPath( snapshot.workingDirectory ?? snapshot.launchCommand?.workingDirectory ) { - return (cwd: workingDirectory, useLastTurnSource: false, sessionId: sessionId) + return (cwd: workingDirectory, sessionId: sessionId) } return nil } - private func latestAgentTurnDiffRepoRoot(workspaceId: UUID, surfaceId: UUID, sessionId: String) -> String? { - let storeURL = agentTurnDiffBaselineStoreURL() - guard let data = try? Data(contentsOf: storeURL), - let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - let records = object["records"] as? [[String: Any]] else { - return nil - } - let workspaceKey = workspaceId.uuidString.lowercased() - let surfaceKey = surfaceId.uuidString.lowercased() - let candidates = records.compactMap { record -> (repoRoot: String, capturedAt: TimeInterval)? in - guard let recordWorkspace = normalizedOpenDiffViewerIdentifier(record["workspaceId"] as? String), - let recordSurface = normalizedOpenDiffViewerIdentifier(record["surfaceId"] as? String), - let recordSession = normalizedOpenDiffViewerSessionId(record["sessionId"] as? String), - recordWorkspace == workspaceKey, - recordSurface == surfaceKey, - recordSession == sessionId, - let repoRoot = normalizedOpenDiffViewerPath(record["repoRoot"] as? String) else { - return nil - } - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: repoRoot, isDirectory: &isDirectory), - isDirectory.boolValue else { - return nil - } - let capturedAt = (record["capturedAt"] as? NSNumber)?.doubleValue ?? 0 - return (repoRoot, capturedAt) - } - return candidates.max(by: { $0.capturedAt < $1.capturedAt })?.repoRoot - } - - private func agentTurnDiffBaselineStoreURL() -> URL { - let environment = ProcessInfo.processInfo.environment - if let override = normalizedOpenDiffViewerPath(environment["CMUX_AGENT_HOOK_STATE_DIR"]) { - let expandedOverride = (override as NSString).expandingTildeInPath - return URL(fileURLWithPath: expandedOverride, isDirectory: true) - .appendingPathComponent("agent-turn-diff-baselines.json", isDirectory: false) - } - return FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".cmuxterm", isDirectory: true) - .appendingPathComponent("agent-turn-diff-baselines.json", isDirectory: false) - } - - private func normalizedOpenDiffViewerIdentifier(_ value: String?) -> String? { - value? - .trimmingCharacters(in: .whitespacesAndNewlines) - .lowercased() - .nilIfEmpty - } - - private func normalizedOpenDiffViewerSessionId(_ value: String?) -> String? { - value? - .trimmingCharacters(in: .whitespacesAndNewlines) - .nilIfEmpty - } - - private func normalizedOpenDiffViewerPath(_ value: String?) -> String? { - value? - .trimmingCharacters(in: .whitespacesAndNewlines) - .nilIfEmpty - } - @discardableResult - private func launchDiffViewerProcess( + func launchDiffViewerProcess( cliURL: URL, socketPath: String, cwd: String, workspaceId: UUID, surfaceId: UUID?, useLastTurnSource: Bool, - sessionId: String? + sessionId: String?, + focus: Bool = true ) -> Bool { let process = Process() process.executableURL = cliURL @@ -6192,7 +6161,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent useLastTurnSource ? "--last-turn" : "--unstaged", "--cwd", cwd, "--workspace", workspaceId.uuidString, - "--focus", "true", + "--focus", focus ? "true" : "false", ] if let surfaceId { arguments.append(contentsOf: ["--surface", surfaceId.uuidString]) diff --git a/Sources/OpenDiffViewerAgentBaselineLookup.swift b/Sources/OpenDiffViewerAgentBaselineLookup.swift new file mode 100644 index 000000000000..f29840e720d2 --- /dev/null +++ b/Sources/OpenDiffViewerAgentBaselineLookup.swift @@ -0,0 +1,166 @@ +import Foundation +import AppKit +import CmuxFoundation + +extension AppDelegate { + func startOpenDiffViewerAgentContextTask( + _ request: OpenDiffViewerAgentContextRequest, + taskKey: String + ) { + openDiffViewerAgentContextTasks[taskKey] = Task.detached(priority: .userInitiated) { + let repoRoot = Self.latestAgentTurnDiffRepoRoot( + storeURL: request.storeURL, + workspaceId: request.workspaceId, + surfaceId: request.surfaceId, + sessionId: request.sessionId + ) + await MainActor.run { + AppDelegate.shared?.finishOpenDiffViewerAgentContextTask( + request, + taskKey: taskKey, + repoRoot: repoRoot + ) + } + } + } + + func finishOpenDiffViewerAgentContextTask( + _ request: OpenDiffViewerAgentContextRequest, + taskKey: String, + repoRoot: String? + ) { + openDiffViewerAgentContextTasks.removeValue(forKey: taskKey) + let pendingRequest = openDiffViewerAgentContextPendingRequests.removeValue(forKey: taskKey) + if let pendingRequest { + startOpenDiffViewerAgentContextTask(pendingRequest, taskKey: taskKey) + return + } + guard let shouldFocus = openDiffViewerAgentContextShouldFocus( + workspaceId: request.workspaceId, + surfaceId: request.surfaceId, + sessionId: request.sessionId, + originWindowId: request.originWindowId + ) else { + return + } + let cwd = repoRoot ?? request.snapshotWorkingDirectory ?? request.fallbackCwd + let useLastTurnSource = repoRoot != nil + guard launchDiffViewerProcess( + cliURL: request.cliURL, + socketPath: request.socketPath, + cwd: cwd, + workspaceId: request.workspaceId, + surfaceId: request.surfaceId, + useLastTurnSource: useLastTurnSource, + sessionId: request.sessionId, + focus: shouldFocus + ) == true else { + NSSound.beep() + return + } + } + + /// Returns nil when no matching context exists, false when focus moved, and true when it remains focused. + func openDiffViewerAgentContextShouldFocus( + workspaceId: UUID, + surfaceId: UUID, + sessionId: String, + originWindowId: UUID? + ) -> Bool? { + for context in mainWindowContexts.values { + guard let workspace = context.tabManager.tabs.first(where: { + $0.id == workspaceId && $0.panels.keys.contains(surfaceId) + }), + let snapshot = SharedLiveAgentIndex.shared.snapshot(workspaceId: workspaceId, panelId: surfaceId), + Self.normalizedOpenDiffViewerSessionId(snapshot.sessionId) == sessionId else { + continue + } + guard let originWindowId, + context.windowId == originWindowId, + NSApp.isActive, + (context.window?.isKeyWindow == true || context.window?.isMainWindow == true) else { + return false + } + return context.tabManager.selectedWorkspace?.id == workspaceId && + workspace.focusedPanelId == surfaceId + } + return nil + } + + nonisolated static func latestAgentTurnDiffRepoRoot( + storeURL: URL, + workspaceId: UUID, + surfaceId: UUID, + sessionId: String + ) -> String? { + guard let data = try? Data(contentsOf: storeURL), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let records = object["records"] as? [[String: Any]] else { + return nil + } + let workspaceKey = workspaceId.uuidString.lowercased() + let surfaceKey = surfaceId.uuidString.lowercased() + let candidates = records.compactMap { record -> (repoRoot: String, capturedAt: TimeInterval)? in + guard let recordWorkspace = normalizedOpenDiffViewerIdentifier(record["workspaceId"] as? String), + let recordSurface = normalizedOpenDiffViewerIdentifier(record["surfaceId"] as? String), + let recordSession = normalizedOpenDiffViewerSessionId(record["sessionId"] as? String), + recordWorkspace == workspaceKey, + recordSurface == surfaceKey, + recordSession == sessionId, + let repoRoot = normalizedOpenDiffViewerPath(record["repoRoot"] as? String) else { + return nil + } + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: repoRoot, isDirectory: &isDirectory), + isDirectory.boolValue else { + return nil + } + let capturedAt = (record["capturedAt"] as? NSNumber)?.doubleValue ?? 0 + return (repoRoot, capturedAt) + } + return candidates.max(by: { $0.capturedAt < $1.capturedAt })?.repoRoot + } + + nonisolated static func openDiffViewerAgentContextTaskKey( + workspaceId: UUID, + surfaceId: UUID, + sessionId: String + ) -> String { + [ + workspaceId.uuidString.lowercased(), + surfaceId.uuidString.lowercased(), + sessionId + ].joined(separator: ":") + } + + nonisolated static func agentTurnDiffBaselineStoreURL() -> URL { + let environment = ProcessInfo.processInfo.environment + if let override = normalizedOpenDiffViewerPath(environment["CMUX_AGENT_HOOK_STATE_DIR"]) { + let expandedOverride = (override as NSString).expandingTildeInPath + return URL(fileURLWithPath: expandedOverride, isDirectory: true) + .appendingPathComponent("agent-turn-diff-baselines.json", isDirectory: false) + } + return FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent(".cmuxterm", isDirectory: true) + .appendingPathComponent("agent-turn-diff-baselines.json", isDirectory: false) + } + + nonisolated static func normalizedOpenDiffViewerIdentifier(_ value: String?) -> String? { + value? + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + .nilIfEmpty + } + + nonisolated static func normalizedOpenDiffViewerSessionId(_ value: String?) -> String? { + value? + .trimmingCharacters(in: .whitespacesAndNewlines) + .nilIfEmpty + } + + nonisolated static func normalizedOpenDiffViewerPath(_ value: String?) -> String? { + value? + .trimmingCharacters(in: .whitespacesAndNewlines) + .nilIfEmpty + } +} diff --git a/Sources/OpenDiffViewerAgentContextRequest.swift b/Sources/OpenDiffViewerAgentContextRequest.swift new file mode 100644 index 000000000000..6ebb4e58ba89 --- /dev/null +++ b/Sources/OpenDiffViewerAgentContextRequest.swift @@ -0,0 +1,13 @@ +import Foundation + +struct OpenDiffViewerAgentContextRequest: Sendable { + let cliURL: URL + let socketPath: String + let fallbackCwd: String + let snapshotWorkingDirectory: String? + let storeURL: URL + let workspaceId: UUID + let surfaceId: UUID + let sessionId: String + let originWindowId: UUID? +} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index cb8617111abb..63a0eab829a8 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -571,6 +571,8 @@ A9F200000000000000000018 /* OpenCodeEventTextAccumulator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000018 /* OpenCodeEventTextAccumulator.swift */; }; A5E01203A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */; }; A9F200000000000000000019 /* OpenCodeProcessOutputDisposition.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F100000000000000000019 /* OpenCodeProcessOutputDisposition.swift */; }; + ODBG00010000000000000001 /* OpenDiffViewerAgentBaselineLookup.swift in Sources */ = {isa = PBXBuildFile; fileRef = ODBG00010000000000000002 /* OpenDiffViewerAgentBaselineLookup.swift */; }; + ODBG00020000000000000001 /* OpenDiffViewerAgentContextRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = ODBG00020000000000000002 /* OpenDiffViewerAgentContextRequest.swift */; }; D0B1001CA1B2C3D4E5F60001 /* PaneDropRoutingSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B1001DA1B2C3D4E5F60001 /* PaneDropRoutingSupport.swift */; }; A5001400 /* Panel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001410 /* Panel.swift */; }; A5001405 /* PanelContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001415 /* PanelContentView.swift */; }; @@ -1587,6 +1589,8 @@ A9F100000000000000000018 /* OpenCodeEventTextAccumulator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/OpenCodeEventTextAccumulator.swift; sourceTree = ""; }; A5E01204A1B2C3D4E5F60718 /* OpenCodeHookRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenCodeHookRegressionTests.swift; sourceTree = ""; }; A9F100000000000000000019 /* OpenCodeProcessOutputDisposition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/OpenCodeProcessOutputDisposition.swift; sourceTree = ""; }; + ODBG00010000000000000002 /* OpenDiffViewerAgentBaselineLookup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenDiffViewerAgentBaselineLookup.swift; sourceTree = ""; }; + ODBG00020000000000000002 /* OpenDiffViewerAgentContextRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenDiffViewerAgentContextRequest.swift; sourceTree = ""; }; D0B1001DA1B2C3D4E5F60001 /* PaneDropRoutingSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PaneDropRoutingSupport.swift; sourceTree = ""; }; A5001410 /* Panel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/Panel.swift; sourceTree = ""; }; A5001415 /* PanelContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/PanelContentView.swift; sourceTree = ""; }; @@ -2563,6 +2567,8 @@ C4160A030000000000000002 /* AppDelegate+ClosedItemHistory.swift */, C4160A040000000000000002 /* AppDelegate+FocusHistoryContextMenu.swift */, 604500100000000000000006 /* AppDelegate+WindowIdentity.swift */, + ODBG00010000000000000002 /* OpenDiffViewerAgentBaselineLookup.swift */, + ODBG00020000000000000002 /* OpenDiffViewerAgentContextRequest.swift */, C10D00020000000000000002 /* CloudVMActionLauncher.swift */, B37A00000000000000000006 /* MainWindowFocusTypes.swift */, 2F0C05000000000000000001 /* MainWindowFocusController.swift */, @@ -3854,6 +3860,8 @@ A9F200000000000000000017 /* OpenCodeEventStreamParser.swift in Sources */, A9F200000000000000000018 /* OpenCodeEventTextAccumulator.swift in Sources */, A9F200000000000000000019 /* OpenCodeProcessOutputDisposition.swift in Sources */, + ODBG00010000000000000001 /* OpenDiffViewerAgentBaselineLookup.swift in Sources */, + ODBG00020000000000000001 /* OpenDiffViewerAgentContextRequest.swift in Sources */, D0B1001CA1B2C3D4E5F60001 /* PaneDropRoutingSupport.swift in Sources */, A5001400 /* Panel.swift in Sources */, A5001405 /* PanelContentView.swift in Sources */,