From bfcfac853021bf92df94148323d147d872ebcbfc Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 17:02:27 -0700 Subject: [PATCH 1/8] test: cover Vault restore-verb resume path --- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/SessionEntryResumeLaunchTests.swift | 145 ++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 cmuxTests/SessionEntryResumeLaunchTests.swift diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index dc8f2bde9719..3a8a60cbc302 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1814,6 +1814,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C71510010000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C71510020000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift */; }; E7A5F1A10000000000000001 /* SessionCustomSidebarPanelSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A5F1A10000000000000002 /* SessionCustomSidebarPanelSnapshot.swift */; }; A74770010000000000000003 /* SessionDisplaySnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = A74770010000000000000004 /* SessionDisplaySnapshot.swift */; }; + 992300019923000199230001 /* SessionEntryResumeLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 992300019923000199230002 /* SessionEntryResumeLaunchTests.swift */; }; 85000000000000000000002A /* SessionIndexEntryProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85000000000000000000001A /* SessionIndexEntryProjection.swift */; }; 850000000000000000000028 /* SessionIndexJSONLReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850000000000000000000018 /* SessionIndexJSONLReader.swift */; }; 850000000000000000000004 /* SessionIndexJSONLReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850000000000000000000003 /* SessionIndexJSONLReaderTests.swift */; }; @@ -4483,6 +4484,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C71510020000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionContentWidthSettingsFileStoreTests.swift; sourceTree = ""; }; E7A5F1A10000000000000002 /* SessionCustomSidebarPanelSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionCustomSidebarPanelSnapshot.swift; sourceTree = ""; }; A74770010000000000000004 /* SessionDisplaySnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionDisplaySnapshot.swift; sourceTree = ""; }; + 992300019923000199230002 /* SessionEntryResumeLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionEntryResumeLaunchTests.swift; sourceTree = ""; }; 85000000000000000000001A /* SessionIndexEntryProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionIndexEntryProjection.swift; sourceTree = ""; }; 850000000000000000000018 /* SessionIndexJSONLReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionIndexJSONLReader.swift; sourceTree = ""; }; 850000000000000000000003 /* SessionIndexJSONLReaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionIndexJSONLReaderTests.swift; sourceTree = ""; }; @@ -7546,6 +7548,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 85FA9F7370322CC65A15774E /* AgentResumeLivenessTests.swift */, 8837A0020000000000000002 /* AgentResumeReturnShellStartupTests.swift */, 9200B0019200B0019200B002 /* ResumeLauncherCwdConsistencyTests.swift */, + 992300019923000199230002 /* SessionEntryResumeLaunchTests.swift */, B714B27E46014592B9CB2D3A /* WorkspaceIsStaleAgentHookBindingTests.swift */, D3610B010000000000000002 /* AgentSessionAutoResumeSettingsTests.swift */, 842300000000000000000002 /* SurfaceResumeExitedAgentLivenessTests.swift */, @@ -11050,6 +11053,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C0DE1A070000000000000001 /* SavedLayoutStoreTests.swift in Sources */, 3865A0043865A0043865A004 /* SearchIndexTests.swift in Sources */, C71510010000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift in Sources */, + 992300019923000199230001 /* SessionEntryResumeLaunchTests.swift in Sources */, 850000000000000000000004 /* SessionIndexJSONLReaderTests.swift in Sources */, 850000000000000000000006 /* SessionIndexSnapshotLoaderTests.swift in Sources */, 850000000000000000000008 /* SessionIndexSyntheticCorpus.swift in Sources */, diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift new file mode 100644 index 000000000000..43ea3c10b7aa --- /dev/null +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -0,0 +1,145 @@ +import CMUXAgentLaunch +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@MainActor +@Suite(.serialized) +struct SessionEntryResumeLaunchTests { + @Test("Vault resume plans the short restore verb with structured Codex settings") + func vaultResumeUsesShortRestoreVerb() throws { + let entry = SessionEntry( + id: "codex:vault-session", + agent: .codex, + sessionId: "vault-session", + title: "Resume me", + cwd: "/tmp/vault-project", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_000), + fileURL: nil, + specifics: .codex( + model: "gpt-5.5", + approvalPolicy: "never", + sandboxMode: "disabled", + effort: "high" + ) + ) + + let launch = try #require(entry.resumeLaunch) + #expect( + launch.initialInput + == " \(AgentRestoreLaunch.cliStartupExecutableToken) restore codex vault-session\n" + ) + #expect(launch.workingDirectory == "/tmp/vault-project") + #expect(!launch.initialInput.contains("cd --")) + #expect(!launch.initialInput.contains("codex resume")) + + let snapshot = try #require(launch.startupRestoreAgent) + let arguments = try #require(snapshot.preparedResumeArguments( + launchCommand: snapshot.launchCommand, + workingDirectory: snapshot.workingDirectory, + observedPermissionMode: snapshot.permissionMode + )) + #expect(Array(arguments.prefix(3)) == ["codex", "resume", "vault-session"]) + #expect(arguments.contains("gpt-5.5")) + #expect(arguments.contains("--dangerously-bypass-approvals-and-sandbox")) + #expect(arguments.contains("model_reasoning_effort=high")) + } + + @Test("Registered Vault agents use structured restore argv") + func registeredAgentUsesStructuredRestore() throws { + let registration = CmuxVaultAgentRegistration( + id: "my-agent", + name: "My Agent", + detect: CmuxVaultAgentDetectRule(processName: "my-agent"), + sessionIdSource: .argvOption("--session"), + resumeCommand: "{{executable}} --session {{sessionId}} --profile fast", + cwd: .preserve + ) + let entry = SessionEntry( + id: "my-agent:custom-session", + agent: .registered(RegisteredSessionAgent(registration: registration)), + sessionId: "custom-session", + title: "Custom session", + cwd: "/tmp/custom-project", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_001), + fileURL: nil, + specifics: .registered(registration) + ) + + let launch = try #require(entry.resumeLaunch) + #expect( + launch.initialInput + == " \(AgentRestoreLaunch.cliStartupExecutableToken) restore my-agent custom-session\n" + ) + let snapshot = try #require(launch.startupRestoreAgent) + #expect( + snapshot.preparedResumeArguments( + launchCommand: snapshot.launchCommand, + workingDirectory: snapshot.workingDirectory, + observedPermissionMode: snapshot.permissionMode + ) == ["my-agent", "--session", "custom-session", "--profile", "fast"] + ) + } + + @Test("Restore responder resolves a Vault startup snapshot without restored-panel state") + func responderResolvesVaultStartupSnapshot() throws { + let entry = SessionEntry( + id: "claude:vault-claude-session", + agent: .claude, + sessionId: "vault-claude-session", + title: "Claude session", + cwd: "/tmp", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_002), + fileURL: nil, + specifics: .claude( + model: "sonnet", + permissionMode: "acceptEdits", + configDirectoryForResume: "/tmp/claude-config" + ) + ) + let launch = try #require(entry.resumeLaunch) + let snapshot = try #require(launch.startupRestoreAgent) + let workspace = Workspace( + workingDirectory: launch.workingDirectory, + initialTerminalInput: launch.initialInput, + initialTerminalStartupRestoreAgent: snapshot + ) + defer { workspace.teardownAllPanels() } + let panelID = try #require(workspace.focusedPanelId) + #expect(workspace.restoredAgentSnapshotsByPanelId[panelID] == nil) + + let tabManager = TabManager(autoWelcomeIfNeeded: false) + defer { tabManager.tabs.forEach { $0.teardownAllPanels() } } + let target = ControlSurfaceResumeTarget.workspace( + tabManager: tabManager, + workspace: workspace, + surfaceID: panelID + ) + let record = try #require(TerminalController.shared.controlSurfaceRestoreRecord( + target: target, + binding: nil + )) + + #expect(record.modeRawValue == AgentRestoreRequestMode.resumeAgent.rawValue) + #expect(record.kind == "claude") + #expect(record.checkpointID == "vault-claude-session") + #expect(record.source == "vault") + #expect(record.workingDirectory == "/tmp") + #expect(record.permissionMode == "acceptEdits") + #expect(record.environment["CLAUDE_CONFIG_DIR"] == "/tmp/claude-config") + #expect(record.preparedArguments?.contains("--resume") == true) + #expect(record.preparedArguments?.contains("vault-claude-session") == true) + #expect(record.legacyCommand == nil) + } +} From 63f31dcbae49dbb550ab4bfb8b160b09071cd93a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 17:39:44 -0700 Subject: [PATCH 2/8] fix: route Vault resume through restore verb --- Sources/ControlSurfaceResumeTarget.swift | 49 +++- Sources/HermesAgentIndex.swift | 2 +- Sources/Panels/TerminalPanel.swift | 18 +- Sources/SessionEntryResumeLaunch.swift | 222 ++++++++++++++++++ Sources/SessionIndexModels.swift | 67 +----- Sources/SessionIndexView.swift | 13 +- Sources/TabManager.swift | 4 + Sources/Workspace.swift | 25 +- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/SessionEntryResumeLaunchTests.swift | 5 +- 10 files changed, 328 insertions(+), 81 deletions(-) create mode 100644 Sources/SessionEntryResumeLaunch.swift diff --git a/Sources/ControlSurfaceResumeTarget.swift b/Sources/ControlSurfaceResumeTarget.swift index 7db9b750525f..ec373efaa5c6 100644 --- a/Sources/ControlSurfaceResumeTarget.swift +++ b/Sources/ControlSurfaceResumeTarget.swift @@ -54,6 +54,15 @@ enum ControlSurfaceResumeTarget { } } + var startupRestoreAgent: SessionRestorableAgentSnapshot? { + switch self { + case .workspace(_, let workspace, let surfaceID): + workspace.terminalPanel(for: surfaceID)?.startupRestoreAgent + case .dock(_, let dock, let surfaceID): + (dock.panels[surfaceID] as? TerminalPanel)?.startupRestoreAgent + } + } + var restoredResumeWorkingDirectory: String? { switch self { case .workspace(_, let workspace, let surfaceID): @@ -265,7 +274,7 @@ extension TerminalController { ) } - private func controlSurfaceRestoreRecord( + func controlSurfaceRestoreRecord( target: ControlSurfaceResumeTarget, binding: SurfaceResumeBindingSnapshot? ) -> ControlSurfaceRestoreRecord? { @@ -280,18 +289,38 @@ extension TerminalController { // conversation. Reuse the session-restore identity gate so the record // returned to the CLI always agrees with the binding that generated its // typed `cmux restore ` selector. - let compatibleAgent: SessionRestorableAgentSnapshot? = - if binding == nil || binding?.isAgentHookBinding == true { - Workspace.restorableAgentForSessionRestore( - target.restorableAgent, - resumeBinding: binding + let compatibleAgent: ( + snapshot: SessionRestorableAgentSnapshot, + source: String, + restoredWorkingDirectory: String? + )? + if binding == nil || binding?.isAgentHookBinding == true { + // A lifecycle snapshot supersedes startup provenance after + // the Vault-created surface has advanced into restore/hibernation state. + if let restoredAgent = Workspace.restorableAgentForSessionRestore( + target.restorableAgent, + resumeBinding: binding + ) { + compatibleAgent = ( + restoredAgent, + "session-snapshot", + target.restoredResumeWorkingDirectory ) + } else if let startupAgent = Workspace.restorableAgentForSessionRestore( + target.startupRestoreAgent, + resumeBinding: binding + ) { + compatibleAgent = (startupAgent, "vault", nil) } else { - nil + compatibleAgent = nil } - if let agent = compatibleAgent { + } else { + compatibleAgent = nil + } + if let compatibleAgent { + let agent = compatibleAgent.snapshot let launchCommand = binding?.launchCommand ?? agent.launchCommand - let workingDirectory = target.restoredResumeWorkingDirectory + let workingDirectory = compatibleAgent.restoredWorkingDirectory ?? binding?.cwd ?? agent.workingDirectory ?? launchCommand?.workingDirectory @@ -310,7 +339,7 @@ extension TerminalController { modeRawValue: mode.rawValue, kind: agent.kind.rawValue, checkpointID: agent.sessionId, - source: "session-snapshot", + source: compatibleAgent.source, workingDirectory: workingDirectory, environment: binding?.environment ?? [:], launchCommand: launchCommand.map { diff --git a/Sources/HermesAgentIndex.swift b/Sources/HermesAgentIndex.swift index bf5159d83621..ca8adebcb609 100644 --- a/Sources/HermesAgentIndex.swift +++ b/Sources/HermesAgentIndex.swift @@ -73,7 +73,7 @@ extension SessionEntry { // indexed Hermes profile and cmux hooks belong to the resumed process, // even when another Hermes installation appears earlier on PATH. The // wrapper token is POSIX-only, so keep it inside a portable /bin/sh - // command before the cwd guard is added by resumeCommandWithCwd. + // command before the cwd guard is added by copyResumeCommand. var parts = [AgentResumeArgv.hermesWrapperShellExecutableToken] let profilePin = HermesAgentResumeProfilePin( hermesHome: hermesHome, diff --git a/Sources/Panels/TerminalPanel.swift b/Sources/Panels/TerminalPanel.swift index 4d6a46102934..c24a10e0b838 100644 --- a/Sources/Panels/TerminalPanel.swift +++ b/Sources/Panels/TerminalPanel.swift @@ -28,6 +28,10 @@ final class TerminalPanel: Panel, ObservableObject { /// The workspace ID this panel belongs to private(set) var workspaceId: UUID + /// Surface-scoped structured state consumed by an initial `cmux restore` selector. + /// Vault-created panels keep this separate from persisted relaunch snapshots. + let startupRestoreAgent: SessionRestorableAgentSnapshot? + var ownedSessionScrollbackReplayFileURL: URL? = nil /// The workspace-env key/value pairs this panel inherited from its workspace's /// `workspaceEnvironment` at creation. The same panel travels when a surface is @@ -145,10 +149,15 @@ final class TerminalPanel: Panel, ObservableObject { surface.requestedWorkingDirectory } - init(workspaceId: UUID, surface: TerminalSurface) { + init( + workspaceId: UUID, + surface: TerminalSurface, + startupRestoreAgent: SessionRestorableAgentSnapshot? = nil + ) { self.id = surface.id self.workspaceId = workspaceId self.surface = surface + self.startupRestoreAgent = startupRestoreAgent // Subscribe to surface's search state changes surface.$searchState .sink { [weak self] state in @@ -170,6 +179,7 @@ final class TerminalPanel: Panel, ObservableObject { initialCommand: String? = nil, tmuxStartCommand: String? = nil, initialInput: String? = nil, + startupRestoreAgent: SessionRestorableAgentSnapshot? = nil, initialEnvironmentOverrides: [String: String] = [:], additionalEnvironment: [String: String] = [:], focusPlacement: TerminalSurfaceFocusPlacement = .workspace, @@ -190,7 +200,11 @@ final class TerminalPanel: Panel, ObservableObject { focusPlacement: focusPlacement, runtimeSpawnPolicy: runtimeSpawnPolicy, preparePaneHost: { Self.prepareNotificationScrollReplay(for: $0, environment: additionalEnvironment) } ) - self.init(workspaceId: workspaceId, surface: surface) + self.init( + workspaceId: workspaceId, + surface: surface, + startupRestoreAgent: startupRestoreAgent + ) if Self.startsAtOwnedPrompt( configTemplate: configTemplate, initialCommand: initialCommand, diff --git a/Sources/SessionEntryResumeLaunch.swift b/Sources/SessionEntryResumeLaunch.swift new file mode 100644 index 000000000000..704a25282774 --- /dev/null +++ b/Sources/SessionEntryResumeLaunch.swift @@ -0,0 +1,222 @@ +import CMUXAgentLaunch +import Foundation + +/// The terminal startup plan shared by every Vault resume entry point. +struct SessionEntryResumeLaunch: Sendable { + enum Strategy: Sendable, Equatable { + case restoreVerb + case legacyCommand + } + + let strategy: Strategy + let initialInput: String + let workingDirectory: String? + let startupRestoreAgent: SessionRestorableAgentSnapshot? +} + +private struct SessionEntryResumeSnapshotComponents { + let arguments: [String] + let environment: [String: String] + let registration: CmuxVaultAgentRegistration? + let permissionMode: String? +} + +extension SessionEntry { + /// Builds the same surface-scoped restore selector used by relaunch restore. + /// + /// Registered agents deliberately fall back to the quarantined copyable + /// shell command only when their registration cannot produce structured argv. + var resumeLaunch: SessionEntryResumeLaunch? { + guard let snapshot = vaultResumeSnapshot else { + return legacyResumeLaunch + } + if let preparedArguments = snapshot.preparedResumeArguments( + launchCommand: snapshot.launchCommand, + workingDirectory: snapshot.workingDirectory, + observedPermissionMode: snapshot.permissionMode + ), !preparedArguments.isEmpty, + let initialInput = snapshot.resumeStartupInput(useLocalRestoreVerb: true) { + return SessionEntryResumeLaunch( + strategy: .restoreVerb, + initialInput: initialInput, + workingDirectory: resumeWorkingDirectory, + startupRestoreAgent: snapshot + ) + } + + return legacyResumeLaunch + } + + private var legacyResumeLaunch: SessionEntryResumeLaunch? { + guard let legacyCommand = copyResumeCommand else { return nil } + return SessionEntryResumeLaunch( + strategy: .legacyCommand, + initialInput: legacyCommand + "\n", + workingDirectory: resumeWorkingDirectory, + startupRestoreAgent: nil + ) + } + + private var vaultResumeSnapshot: SessionRestorableAgentSnapshot? { + let components: SessionEntryResumeSnapshotComponents + switch specifics { + case let .claude(model, permissionMode, configDirectoryForResume): + var arguments = ["claude"] + if let model = Self.nonEmptyResumeValue(model) { + arguments.append(contentsOf: ["--model", model]) + } + let environment = Self.nonEmptyResumeValue(configDirectoryForResume) + .map { ["CLAUDE_CONFIG_DIR": $0] } ?? [:] + components = SessionEntryResumeSnapshotComponents( + arguments: arguments, + environment: environment, + registration: nil, + permissionMode: Self.nonEmptyResumeValue(permissionMode) + ) + case let .codex(model, approvalPolicy, sandboxMode, effort): + var arguments = ["codex"] + if let model = Self.nonEmptyResumeValue(model) { + arguments.append(contentsOf: ["-m", model]) + } + arguments.append(contentsOf: Self.codexApprovalSandboxArgumentTokens( + approvalPolicy: approvalPolicy, + sandboxMode: sandboxMode + )) + if let effort = Self.nonEmptyResumeValue(effort) { + arguments.append(contentsOf: ["-c", "model_reasoning_effort=\(effort)"]) + } + components = SessionEntryResumeSnapshotComponents( + arguments: arguments, + environment: [:], + registration: nil, + permissionMode: nil + ) + case let .grok(model, permissionMode, sandboxMode, grokHome): + var arguments = ["grok"] + if let model = Self.nonEmptyResumeValue(model) { + arguments.append(contentsOf: ["-m", model]) + } + if let permissionMode = Self.nonEmptyResumeValue(permissionMode) { + arguments.append(contentsOf: ["--permission-mode", permissionMode]) + } + if let sandboxMode = Self.nonEmptyResumeValue(sandboxMode) { + arguments.append(contentsOf: ["--sandbox", sandboxMode]) + } + let environment = Self.nonEmptyResumeValue(grokHome) + .map { ["GROK_HOME": $0] } ?? [:] + components = SessionEntryResumeSnapshotComponents( + arguments: arguments, + environment: environment, + registration: nil, + permissionMode: nil + ) + case let .opencode(providerModel, agentName): + var arguments = ["opencode"] + if let providerModel = Self.nonEmptyResumeValue(providerModel) { + arguments.append(contentsOf: ["-m", providerModel]) + } + if let agentName = Self.nonEmptyResumeValue(agentName) { + arguments.append(contentsOf: ["--agent", agentName]) + } + components = SessionEntryResumeSnapshotComponents( + arguments: arguments, + environment: [:], + registration: nil, + permissionMode: nil + ) + case .rovodev: + components = SessionEntryResumeSnapshotComponents( + arguments: ["acli", "rovodev", "run"], + environment: [:], + registration: nil, + permissionMode: nil + ) + case let .hermesAgent(source, model, hermesHome): + var arguments = ["hermes"] + if source == "tui" { + arguments.append("--tui") + } + if let model = Self.nonEmptyResumeValue(model) { + arguments.append(contentsOf: ["--model", model]) + } + let environment = Self.nonEmptyResumeValue(hermesHome) + .map { ["HERMES_HOME": $0] } ?? [:] + components = SessionEntryResumeSnapshotComponents( + arguments: arguments, + environment: environment, + registration: nil, + permissionMode: nil + ) + case .registered(let registration): + components = SessionEntryResumeSnapshotComponents( + arguments: [registration.defaultExecutable], + environment: [:], + registration: registration, + permissionMode: nil + ) + } + + guard let kind = RestorableAgentKind( + persistedRawValue: agent.rawValue, + registration: components.registration + ) else { + return nil + } + let workingDirectory = resumeWorkingDirectory + return SessionRestorableAgentSnapshot( + kind: kind, + sessionId: sessionId, + workingDirectory: workingDirectory, + launchCommand: AgentLaunchCommandSnapshot( + arguments: components.arguments, + workingDirectory: workingDirectory, + environment: components.environment.isEmpty ? nil : components.environment, + source: "vault" + ), + registration: components.registration, + permissionMode: components.permissionMode + ) + } + + /// Sandbox-policy values the Codex CLI `--sandbox` flag accepts. + /// + /// cmux captures Codex's internal sandbox-policy `type`, which also includes + /// values such as `disabled` and `managed` that the CLI rejects. + private static let codexCLISandboxModes: Set = [ + "read-only", + "workspace-write", + "danger-full-access", + ] + + /// Returns a structured argument vector for the captured Codex policy. + /// + /// The captured `(approval: "never", sandbox: "disabled")` pair is the exact + /// inverse of `--dangerously-bypass-approvals-and-sandbox`, so it becomes that + /// one flag instead of the invalid `-a never -s disabled` combination. + static func codexApprovalSandboxArgumentTokens( + approvalPolicy: String?, + sandboxMode: String? + ) -> [String] { + if approvalPolicy == "never", sandboxMode == "disabled" { + return ["--dangerously-bypass-approvals-and-sandbox"] + } + + var arguments: [String] = [] + if let approvalPolicy, !approvalPolicy.isEmpty { + arguments.append(contentsOf: ["-a", approvalPolicy]) + } + if let sandboxMode, !sandboxMode.isEmpty, + codexCLISandboxModes.contains(sandboxMode) { + arguments.append(contentsOf: ["-s", sandboxMode]) + } + return arguments + } + + private static func nonEmptyResumeValue(_ value: String?) -> String? { + guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { + return nil + } + return value + } +} diff --git a/Sources/SessionIndexModels.swift b/Sources/SessionIndexModels.swift index 223611d5c1b2..029adc46cfc9 100644 --- a/Sources/SessionIndexModels.swift +++ b/Sources/SessionIndexModels.swift @@ -297,22 +297,24 @@ struct SessionEntry: Identifiable, Hashable, Sendable { ) } - /// Shell command that resumes this session in a new terminal, with the agent's - /// known per-session settings injected as CLI flags. + /// Compatibility name for the copyable resume command. + /// + /// Runtime Vault resume must use `resumeLaunch`; this rendered shell command + /// remains only for Copy Resume Command and its explicit unsupported-agent fallback. var resumeCommand: String? { - resumeCommandWithCwd + copyResumeCommand } - /// Shell command that resumes this session after guarding the launch directory. - var resumeCommandWithCwd: String? { - guard let command = resumeCommandWithoutWorkingDirectory else { return nil } + /// Shell command exposed by the Copy Resume Command menu item. + var copyResumeCommand: String? { + guard let command = copyResumeCommandWithoutWorkingDirectory else { return nil } guard let cwd = resumeWorkingDirectory else { return command } return TerminalStartupWorkingDirectoryPrefix.prefix(command, workingDirectory: cwd) } - private var resumeCommandWithoutWorkingDirectory: String? { + private var copyResumeCommandWithoutWorkingDirectory: String? { switch specifics { case let .claude(model, permissionMode, configDirectoryForResume): // Route through the wrapper resolver token so a manually-resumed claude session @@ -321,7 +323,7 @@ struct SessionEntry: Identifiable, Hashable, Sendable { // `$SHELL -lic` restore launcher). The token is POSIX-only and this command // is typed into — and copy-pasted into — the user's own shell (fish/csh // included), so the rendered command is wrapped in `/bin/sh -c '…'` to parse - // everywhere; the `cd` guard stays outside in `resumeCommandWithCwd`. + // everywhere; the `cd` guard stays outside in `copyResumeCommand`. // https://github.com/manaflow-ai/cmux/issues/5639 var parts = ["\(AgentResumeArgv.claudeWrapperShellExecutableToken) --resume \(sessionId)"] if let model, !model.isEmpty { @@ -347,15 +349,15 @@ struct SessionEntry: Identifiable, Hashable, Sendable { // POSIX-only and this command is typed into / copy-pasted into the // user's own shell (fish/csh included), so the rendered command is // wrapped in `/bin/sh -c '…'`; the `cd` guard stays outside in - // `resumeCommandWithCwd`. https://github.com/manaflow-ai/cmux/issues/5639 + // `copyResumeCommand`. https://github.com/manaflow-ai/cmux/issues/5639 var parts = ["\(AgentResumeArgv.codexWrapperShellExecutableToken) resume \(sessionId)", AgentResumeArgv.codexUpdateCheckSuppressionOverride.joined(separator: " ")] if let model, !model.isEmpty { parts.append("-m \(Self.shellQuote(model))") } - parts.append(contentsOf: Self.codexApprovalSandboxArguments( + parts.append(contentsOf: Self.codexApprovalSandboxArgumentTokens( approvalPolicy: approval, sandboxMode: sandbox - )) + ).map(Self.shellQuote)) if let effort, !effort.isEmpty { parts.append("-c model_reasoning_effort=\(Self.shellQuote(effort))") } @@ -461,49 +463,6 @@ struct SessionEntry: Identifiable, Hashable, Sendable { TerminalStartupShellQuoting.shellToken(value, allowingBareASCII: true) } - /// Sandbox-policy values the Codex CLI `--sandbox` flag accepts. - /// - /// cmux captures Codex's *internal* sandbox-policy `type`, which is a - /// superset of the CLI vocabulary (it also includes `disabled`, `managed`, - /// and may grow further). Those extra types have no `--sandbox` equivalent - /// and must never be forwarded as `-s`, or Codex rejects the resumed command - /// (see https://github.com/manaflow-ai/cmux/issues/5262). - static let codexCLISandboxModes: Set = [ - "read-only", - "workspace-write", - "danger-full-access", - ] - - /// Builds the approval/sandbox CLI tokens for a `codex resume` command from - /// the per-session policy cmux captured, always yielding a valid invocation. - /// - /// A `--dangerously-bypass-approvals-and-sandbox` launch round-trips to a - /// captured `(approval: "never", sandbox: "disabled")`. This reproduces that - /// single combined flag rather than the invalid, contradictory `-a never -s - /// disabled`. Sandbox types with no CLI equivalent (`disabled`, `managed`, - /// future values) are dropped instead of emitted as an invalid `-s`; valid - /// values pass through unchanged. - static func codexApprovalSandboxArguments( - approvalPolicy: String?, - sandboxMode: String? - ) -> [String] { - // The exact inverse of `--dangerously-bypass-approvals-and-sandbox`: - // emit that one flag and nothing else, since `-a`/`-s` here would be both - // invalid (`-s disabled`) and contradictory with the bypass flag. - if approvalPolicy == "never", sandboxMode == "disabled" { - return ["--dangerously-bypass-approvals-and-sandbox"] - } - - var parts: [String] = [] - if let approvalPolicy, !approvalPolicy.isEmpty { - parts.append("-a \(shellQuote(approvalPolicy))") - } - if let sandboxMode, !sandboxMode.isEmpty, codexCLISandboxModes.contains(sandboxMode) { - parts.append("-s \(shellQuote(sandboxMode))") - } - return parts - } - var displayTitle: String { let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) if agent == .claude { diff --git a/Sources/SessionIndexView.swift b/Sources/SessionIndexView.swift index 8b45551c15e3..00289a769de4 100644 --- a/Sources/SessionIndexView.swift +++ b/Sources/SessionIndexView.swift @@ -10,9 +10,8 @@ import UniformTypeIdentifiers @MainActor enum SessionEntryResumeCoordinator { static func resume(_ entry: SessionEntry, tabManager: TabManager) { - guard let resumeCommand = entry.resumeCommandWithCwd else { return } - let inputWithReturn = resumeCommand + "\n" - let targetCwd = entry.resumeWorkingDirectory + guard let launch = entry.resumeLaunch else { return } + let targetCwd = launch.workingDirectory let selected = tabManager.selectedWorkspace let selectedTab = tabManager.selectedTabId.flatMap { id in @@ -36,14 +35,16 @@ enum SessionEntryResumeCoordinator { inPane: paneId, focus: true, workingDirectory: targetCwd, - initialInput: inputWithReturn + initialInput: launch.initialInput, + startupRestoreAgent: launch.startupRestoreAgent ) return } tabManager.addWorkspace( workingDirectory: targetCwd, - initialTerminalInput: inputWithReturn + initialTerminalInput: launch.initialInput, + initialTerminalStartupRestoreAgent: launch.startupRestoreAgent ) } } @@ -689,7 +690,7 @@ private func sessionRowMenuItems(entry: SessionEntry, onResume: ((SessionEntry) Text(String(localized: "sessionIndex.row.copyPath", defaultValue: "Copy File Path")) } } - if let resumeCommand = entry.resumeCommand { + if let resumeCommand = entry.copyResumeCommand { Button { let pb = NSPasteboard.general pb.clearContents() diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index d18b53fc1660..6c0d36ac9eb0 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -998,6 +998,7 @@ class TabManager: ObservableObject { initialSurface: NewWorkspaceInitialSurface = .terminal, initialTerminalCommand: String?, initialTerminalInput: String? = nil, + initialTerminalStartupRestoreAgent: SessionRestorableAgentSnapshot? = nil, initialTerminalEnvironment: [String: String], initialBrowserURL: URL? = nil, initialBrowserOmnibarVisible: Bool = true, @@ -1014,6 +1015,7 @@ class TabManager: ObservableObject { initialSurface: initialSurface, initialTerminalCommand: initialTerminalCommand, initialTerminalInput: initialTerminalInput, + initialTerminalStartupRestoreAgent: initialTerminalStartupRestoreAgent, initialTerminalEnvironment: initialTerminalEnvironment, initialBrowserURL: initialBrowserURL, initialBrowserOmnibarVisible: initialBrowserOmnibarVisible, @@ -1157,6 +1159,7 @@ class TabManager: ObservableObject { initialSurface: NewWorkspaceInitialSurface = .terminal, initialTerminalCommand: String? = nil, initialTerminalInput: String? = nil, + initialTerminalStartupRestoreAgent: SessionRestorableAgentSnapshot? = nil, initialTerminalEnvironment: [String: String] = [:], initialBrowserURL: URL? = nil, initialBrowserOmnibarVisible: Bool = true, @@ -1240,6 +1243,7 @@ class TabManager: ObservableObject { initialSurface: initialSurface, initialTerminalCommand: initialTerminalCommand, initialTerminalInput: initialTerminalInput, + initialTerminalStartupRestoreAgent: initialTerminalStartupRestoreAgent, initialTerminalEnvironment: initialTerminalEnvironment, initialBrowserURL: initialBrowserURL, initialBrowserOmnibarVisible: initialBrowserOmnibarVisible, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index d49ab48c4999..6eaefb5557ee 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -3212,6 +3212,7 @@ final class Workspace: Identifiable, ObservableObject { initialSurface: NewWorkspaceInitialSurface = .terminal, initialTerminalCommand: String? = nil, initialTerminalInput: String? = nil, + initialTerminalStartupRestoreAgent: SessionRestorableAgentSnapshot? = nil, initialTerminalEnvironment: [String: String] = [:], initialBrowserURL: URL? = nil, initialBrowserOmnibarVisible: Bool = true, @@ -3356,6 +3357,7 @@ final class Workspace: Identifiable, ObservableObject { portOrdinal: portOrdinal, initialCommand: initialTerminalCommand, initialInput: initialTerminalInput, + startupRestoreAgent: initialTerminalStartupRestoreAgent, initialEnvironmentOverrides: Self.startupEnvironment( workspaceEnvironment: sanitizedWorkspaceEnvironment, overlaying: initialTerminalEnvironment @@ -7835,6 +7837,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: String? = nil, tmuxStartCommand: String? = nil, initialInput: String? = nil, + startupRestoreAgent: SessionRestorableAgentSnapshot? = nil, startupEnvironment: [String: String] = [:], runtimeSpawnPolicy: TerminalSurfaceRuntimeSpawnPolicy = .immediate, autoRefreshMetadata: Bool = true, @@ -7854,6 +7857,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: initialCommand, tmuxStartCommand: tmuxStartCommand, initialInput: initialInput, + startupRestoreAgent: startupRestoreAgent, startupEnvironment: startupEnvironment, runtimeSpawnPolicy: runtimeSpawnPolicy, autoRefreshMetadata: autoRefreshMetadata, @@ -7868,7 +7872,7 @@ final class Workspace: Identifiable, ObservableObject { ).panel } - /// Like ``newTerminalSurface(inPane:focus:workingDirectory:initialCommand:tmuxStartCommand:initialInput:startupEnvironment:autoRefreshMetadata:preserveFocusWhenUnfocused:remotePTYSessionID:suppressWorkspaceRemoteStartupCommand:)`` + /// Like ``newTerminalSurface(inPane:focus:workingDirectory:initialCommand:tmuxStartCommand:initialInput:startupRestoreAgent:startupEnvironment:autoRefreshMetadata:preserveFocusWhenUnfocused:remotePTYSessionID:suppressWorkspaceRemoteStartupCommand:)`` /// but distinguishes a request routed to the remote tmux mirror from a genuine /// failure, so socket/CLI handlers can report the routed request as accepted. func newTerminalSurfaceOutcome( @@ -7878,6 +7882,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: String? = nil, tmuxStartCommand: String? = nil, initialInput: String? = nil, + startupRestoreAgent: SessionRestorableAgentSnapshot? = nil, startupEnvironment: [String: String] = [:], runtimeSpawnPolicy: TerminalSurfaceRuntimeSpawnPolicy = .immediate, autoRefreshMetadata: Bool = true, @@ -7927,6 +7932,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: initialCommand, tmuxStartCommand: tmuxStartCommand, initialInput: initialInput, + startupRestoreAgent: startupRestoreAgent, startupEnvironment: startupEnvironment, runtimeSpawnPolicy: runtimeSpawnPolicy, autoRefreshMetadata: autoRefreshMetadata, @@ -7949,6 +7955,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: String?, tmuxStartCommand: String?, initialInput: String?, + startupRestoreAgent: SessionRestorableAgentSnapshot?, startupEnvironment: [String: String], runtimeSpawnPolicy: TerminalSurfaceRuntimeSpawnPolicy, autoRefreshMetadata: Bool, @@ -8018,6 +8025,7 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: startupCommand, tmuxStartCommand: tmuxStartCommand, initialInput: initialInput, + startupRestoreAgent: startupRestoreAgent, additionalEnvironment: effectiveStartupEnvironment, runtimeSpawnPolicy: runtimeSpawnPolicy ) @@ -11387,15 +11395,15 @@ final class Workspace: Identifiable, ObservableObject { entry: SessionEntry, destination: BonsplitController.ExternalTabDropRequest.Destination ) -> Bool { - guard let resumeCommand = entry.resumeCommand else { return false } - let inputWithReturn = resumeCommand + "\n" + guard let launch = entry.resumeLaunch else { return false } switch destination { case .insert(let paneId, _): let panel = newTerminalSurface( inPane: paneId, focus: true, - workingDirectory: entry.resumeWorkingDirectory, - initialInput: inputWithReturn + workingDirectory: launch.workingDirectory, + initialInput: launch.initialInput, + startupRestoreAgent: launch.startupRestoreAgent ) return panel != nil case .split(let paneId, let orientation, let insertFirst): @@ -11403,8 +11411,9 @@ final class Workspace: Identifiable, ObservableObject { targetPane: paneId, orientation: orientation, insertFirst: insertFirst, - workingDirectory: entry.resumeWorkingDirectory, - initialInput: inputWithReturn + workingDirectory: launch.workingDirectory, + initialInput: launch.initialInput, + startupRestoreAgent: launch.startupRestoreAgent ) return panel != nil } @@ -11506,6 +11515,7 @@ final class Workspace: Identifiable, ObservableObject { insertFirst: Bool, workingDirectory: String?, initialInput: String?, + startupRestoreAgent: SessionRestorableAgentSnapshot? = nil, remoteStartupCommand: String? = nil ) -> TerminalPanel? { var inheritedConfig = inheritedTerminalConfig(inPane: paneId) @@ -11529,6 +11539,7 @@ final class Workspace: Identifiable, ObservableObject { portOrdinal: portOrdinal, initialCommand: startupCommand, initialInput: initialInput, + startupRestoreAgent: startupRestoreAgent, additionalEnvironment: effectiveStartupEnvironment ) configureNewTerminalPanel(newPanel) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 3a8a60cbc302..e2f773e91a09 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -1814,6 +1814,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C71510010000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C71510020000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift */; }; E7A5F1A10000000000000001 /* SessionCustomSidebarPanelSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A5F1A10000000000000002 /* SessionCustomSidebarPanelSnapshot.swift */; }; A74770010000000000000003 /* SessionDisplaySnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = A74770010000000000000004 /* SessionDisplaySnapshot.swift */; }; + 992300019923000199230003 /* SessionEntryResumeLaunch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 992300019923000199230004 /* SessionEntryResumeLaunch.swift */; }; 992300019923000199230001 /* SessionEntryResumeLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 992300019923000199230002 /* SessionEntryResumeLaunchTests.swift */; }; 85000000000000000000002A /* SessionIndexEntryProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85000000000000000000001A /* SessionIndexEntryProjection.swift */; }; 850000000000000000000028 /* SessionIndexJSONLReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850000000000000000000018 /* SessionIndexJSONLReader.swift */; }; @@ -4484,6 +4485,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C71510020000000000000001 /* SessionContentWidthSettingsFileStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionContentWidthSettingsFileStoreTests.swift; sourceTree = ""; }; E7A5F1A10000000000000002 /* SessionCustomSidebarPanelSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionCustomSidebarPanelSnapshot.swift; sourceTree = ""; }; A74770010000000000000004 /* SessionDisplaySnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionDisplaySnapshot.swift; sourceTree = ""; }; + 992300019923000199230004 /* SessionEntryResumeLaunch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionEntryResumeLaunch.swift; sourceTree = ""; }; 992300019923000199230002 /* SessionEntryResumeLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionEntryResumeLaunchTests.swift; sourceTree = ""; }; 85000000000000000000001A /* SessionIndexEntryProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionIndexEntryProjection.swift; sourceTree = ""; }; 850000000000000000000018 /* SessionIndexJSONLReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionIndexJSONLReader.swift; sourceTree = ""; }; @@ -6381,6 +6383,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 9090F0019090F0019090F001 /* AgentHibernationPanelState.swift */, 9090F0029090F0029090F002 /* AgentHibernationResumePreparation.swift */, F0ACC0E0000000000000002 /* CachedAgentProcessIdentityValidator.swift */, + 992300019923000199230004 /* SessionEntryResumeLaunch.swift */, B3575000000000000000000B /* SessionIndexModels.swift */, F0ACC0DE0000000000000008 /* SharedLiveAgentIndexLoader.swift */, B3575000000000000000000D /* VaultAgentRegistry+Campfire.swift */, @@ -9717,6 +9720,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C71500040000000000000001 /* SessionContentWidthPresentation.swift in Sources */, E7A5F1A10000000000000001 /* SessionCustomSidebarPanelSnapshot.swift in Sources */, A74770010000000000000003 /* SessionDisplaySnapshot.swift in Sources */, + 992300019923000199230003 /* SessionEntryResumeLaunch.swift in Sources */, 85000000000000000000002A /* SessionIndexEntryProjection.swift in Sources */, 850000000000000000000028 /* SessionIndexJSONLReader.swift in Sources */, 850000000000000000000029 /* SessionIndexJSONLReadMetrics.swift in Sources */, diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift index 43ea3c10b7aa..4c533769d215 100644 --- a/cmuxTests/SessionEntryResumeLaunchTests.swift +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -32,6 +32,7 @@ struct SessionEntryResumeLaunchTests { ) let launch = try #require(entry.resumeLaunch) + #expect(launch.strategy == .restoreVerb) #expect( launch.initialInput == " \(AgentRestoreLaunch.cliStartupExecutableToken) restore codex vault-session\n" @@ -76,6 +77,7 @@ struct SessionEntryResumeLaunchTests { ) let launch = try #require(entry.resumeLaunch) + #expect(launch.strategy == .restoreVerb) #expect( launch.initialInput == " \(AgentRestoreLaunch.cliStartupExecutableToken) restore my-agent custom-session\n" @@ -137,7 +139,8 @@ struct SessionEntryResumeLaunchTests { #expect(record.source == "vault") #expect(record.workingDirectory == "/tmp") #expect(record.permissionMode == "acceptEdits") - #expect(record.environment["CLAUDE_CONFIG_DIR"] == "/tmp/claude-config") + #expect(record.environment.isEmpty) + #expect(record.launchCommand?.environment?["CLAUDE_CONFIG_DIR"] == "/tmp/claude-config") #expect(record.preparedArguments?.contains("--resume") == true) #expect(record.preparedArguments?.contains("vault-claude-session") == true) #expect(record.legacyCommand == nil) From 28638efb9250b5fc1ce472cb070c6d5c418bc315 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 19:49:33 -0700 Subject: [PATCH 3/8] test: cover Vault restore persistence lifecycle --- cmuxTests/SessionEntryResumeLaunchTests.swift | 76 ++++++++++++++++++- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift index 4c533769d215..eb0317303f12 100644 --- a/cmuxTests/SessionEntryResumeLaunchTests.swift +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -78,6 +78,7 @@ struct SessionEntryResumeLaunchTests { let launch = try #require(entry.resumeLaunch) #expect(launch.strategy == .restoreVerb) + #expect(launch.workingDirectory == "/tmp/custom-project") #expect( launch.initialInput == " \(AgentRestoreLaunch.cliStartupExecutableToken) restore my-agent custom-session\n" @@ -92,8 +93,8 @@ struct SessionEntryResumeLaunchTests { ) } - @Test("Restore responder resolves a Vault startup snapshot without restored-panel state") - func responderResolvesVaultStartupSnapshot() throws { + @Test("Restore responder resolves a Vault snapshot through lifecycle state") + func responderResolvesVaultLifecycleSnapshot() throws { let entry = SessionEntry( id: "claude:vault-claude-session", agent: .claude, @@ -119,7 +120,10 @@ struct SessionEntryResumeLaunchTests { ) defer { workspace.teardownAllPanels() } let panelID = try #require(workspace.focusedPanelId) - #expect(workspace.restoredAgentSnapshotsByPanelId[panelID] == nil) + #expect( + workspace.restoredAgentSnapshotsByPanelId[panelID]?.sessionId + == "vault-claude-session" + ) let tabManager = TabManager(autoWelcomeIfNeeded: false) defer { tabManager.tabs.forEach { $0.teardownAllPanels() } } @@ -136,7 +140,7 @@ struct SessionEntryResumeLaunchTests { #expect(record.modeRawValue == AgentRestoreRequestMode.resumeAgent.rawValue) #expect(record.kind == "claude") #expect(record.checkpointID == "vault-claude-session") - #expect(record.source == "vault") + #expect(record.source == "session-snapshot") #expect(record.workingDirectory == "/tmp") #expect(record.permissionMode == "acceptEdits") #expect(record.environment.isEmpty) @@ -144,5 +148,69 @@ struct SessionEntryResumeLaunchTests { #expect(record.preparedArguments?.contains("--resume") == true) #expect(record.preparedArguments?.contains("vault-claude-session") == true) #expect(record.legacyCommand == nil) + + workspace.clearRestoredAgentSnapshot(panelId: panelID) + #expect(TerminalController.shared.controlSurfaceRestoreRecord( + target: target, + binding: nil + ) == nil) + } + + @Test("Vault-restored chats persist and resume after a session round trip") + func vaultRestorePersistsAcrossRelaunch() throws { + let sessionID = "vault-persisted-session" + let entry = SessionEntry( + id: "codex:\(sessionID)", + agent: .codex, + sessionId: sessionID, + title: "Persisted Vault session", + cwd: "/tmp/vault-persisted-project", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_003), + fileURL: nil, + specifics: .codex( + model: "gpt-5.5", + approvalPolicy: "never", + sandboxMode: "disabled", + effort: "high" + ) + ) + let launch = try #require(entry.resumeLaunch) + let restorableAgent = try #require(launch.startupRestoreAgent) + + let defaultsName = "cmux-vault-restore-persistence-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: defaultsName)) + defer { defaults.removePersistentDomain(forName: defaultsName) } + defaults.set(true, forKey: AgentSessionAutoResumeSettings.autoResumeAgentSessionsKey) + + let source = Workspace( + workingDirectory: launch.workingDirectory, + initialTerminalInput: launch.initialInput, + initialTerminalStartupRestoreAgent: restorableAgent, + agentSessionAutoResumeDefaults: defaults + ) + defer { source.teardownAllPanels() } + let sourcePanelID = try #require(source.focusedPanelId) + let persisted = source.sessionSnapshot(includeScrollback: false) + #expect( + persisted.panels.first { $0.id == sourcePanelID }?.terminal?.agent?.sessionId + == sessionID + ) + + let encoded = try JSONEncoder().encode(persisted) + let decoded = try JSONDecoder().decode(SessionWorkspaceSnapshot.self, from: encoded) + let restored = Workspace(agentSessionAutoResumeDefaults: defaults) + defer { restored.teardownAllPanels() } + let restoredPanelIDs = restored.restoreSessionSnapshot(decoded) + let restoredPanelID = try #require(restoredPanelIDs[sourcePanelID]) + let restoredPanel = try #require(restored.terminalPanel(for: restoredPanelID)) + + #expect(restoredPanel.surface.debugInitialInputForTesting() == launch.initialInput) + #expect( + restored.sessionSnapshot(includeScrollback: false) + .panels.first { $0.id == restoredPanelID }?.terminal?.agent?.sessionId + == sessionID + ) } } From 8935a7b69e8df1636f318c8c9bacb6bdbd48d313 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 20:10:05 -0700 Subject: [PATCH 4/8] fix: persist Vault restores in agent lifecycle --- Sources/ControlSurfaceResumeTarget.swift | 16 ------ Sources/Panels/TerminalPanel.swift | 15 +----- Sources/Workspace.swift | 27 ++++++++-- cmuxTests/SessionEntryResumeLaunchTests.swift | 53 +++++++++++++++++++ cmuxTests/WorkspaceUnitTests.swift | 4 ++ 5 files changed, 83 insertions(+), 32 deletions(-) diff --git a/Sources/ControlSurfaceResumeTarget.swift b/Sources/ControlSurfaceResumeTarget.swift index ec373efaa5c6..9d248f981312 100644 --- a/Sources/ControlSurfaceResumeTarget.swift +++ b/Sources/ControlSurfaceResumeTarget.swift @@ -54,15 +54,6 @@ enum ControlSurfaceResumeTarget { } } - var startupRestoreAgent: SessionRestorableAgentSnapshot? { - switch self { - case .workspace(_, let workspace, let surfaceID): - workspace.terminalPanel(for: surfaceID)?.startupRestoreAgent - case .dock(_, let dock, let surfaceID): - (dock.panels[surfaceID] as? TerminalPanel)?.startupRestoreAgent - } - } - var restoredResumeWorkingDirectory: String? { switch self { case .workspace(_, let workspace, let surfaceID): @@ -295,8 +286,6 @@ extension TerminalController { restoredWorkingDirectory: String? )? if binding == nil || binding?.isAgentHookBinding == true { - // A lifecycle snapshot supersedes startup provenance after - // the Vault-created surface has advanced into restore/hibernation state. if let restoredAgent = Workspace.restorableAgentForSessionRestore( target.restorableAgent, resumeBinding: binding @@ -306,11 +295,6 @@ extension TerminalController { "session-snapshot", target.restoredResumeWorkingDirectory ) - } else if let startupAgent = Workspace.restorableAgentForSessionRestore( - target.startupRestoreAgent, - resumeBinding: binding - ) { - compatibleAgent = (startupAgent, "vault", nil) } else { compatibleAgent = nil } diff --git a/Sources/Panels/TerminalPanel.swift b/Sources/Panels/TerminalPanel.swift index c24a10e0b838..a93cc9cf2fe4 100644 --- a/Sources/Panels/TerminalPanel.swift +++ b/Sources/Panels/TerminalPanel.swift @@ -28,10 +28,6 @@ final class TerminalPanel: Panel, ObservableObject { /// The workspace ID this panel belongs to private(set) var workspaceId: UUID - /// Surface-scoped structured state consumed by an initial `cmux restore` selector. - /// Vault-created panels keep this separate from persisted relaunch snapshots. - let startupRestoreAgent: SessionRestorableAgentSnapshot? - var ownedSessionScrollbackReplayFileURL: URL? = nil /// The workspace-env key/value pairs this panel inherited from its workspace's /// `workspaceEnvironment` at creation. The same panel travels when a surface is @@ -151,13 +147,11 @@ final class TerminalPanel: Panel, ObservableObject { init( workspaceId: UUID, - surface: TerminalSurface, - startupRestoreAgent: SessionRestorableAgentSnapshot? = nil + surface: TerminalSurface ) { self.id = surface.id self.workspaceId = workspaceId self.surface = surface - self.startupRestoreAgent = startupRestoreAgent // Subscribe to surface's search state changes surface.$searchState .sink { [weak self] state in @@ -179,7 +173,6 @@ final class TerminalPanel: Panel, ObservableObject { initialCommand: String? = nil, tmuxStartCommand: String? = nil, initialInput: String? = nil, - startupRestoreAgent: SessionRestorableAgentSnapshot? = nil, initialEnvironmentOverrides: [String: String] = [:], additionalEnvironment: [String: String] = [:], focusPlacement: TerminalSurfaceFocusPlacement = .workspace, @@ -200,11 +193,7 @@ final class TerminalPanel: Panel, ObservableObject { focusPlacement: focusPlacement, runtimeSpawnPolicy: runtimeSpawnPolicy, preparePaneHost: { Self.prepareNotificationScrollReplay(for: $0, environment: additionalEnvironment) } ) - self.init( - workspaceId: workspaceId, - surface: surface, - startupRestoreAgent: startupRestoreAgent - ) + self.init(workspaceId: workspaceId, surface: surface) if Self.startsAtOwnedPrompt( configTemplate: configTemplate, initialCommand: initialCommand, diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 6eaefb5557ee..605b4c66cc63 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -3357,7 +3357,6 @@ final class Workspace: Identifiable, ObservableObject { portOrdinal: portOrdinal, initialCommand: initialTerminalCommand, initialInput: initialTerminalInput, - startupRestoreAgent: initialTerminalStartupRestoreAgent, initialEnvironmentOverrides: Self.startupEnvironment( workspaceEnvironment: sanitizedWorkspaceEnvironment, overlaying: initialTerminalEnvironment @@ -3381,6 +3380,14 @@ final class Workspace: Identifiable, ObservableObject { bindSurface(tabId, toPanelId: terminalPanel.id) initialTabId = tabId rememberTerminalConfigInheritanceSource(terminalPanel) + if let initialTerminalStartupRestoreAgent { + seedSessionRestoredAgentState( + panelId: terminalPanel.id, + restorableAgent: initialTerminalStartupRestoreAgent, + willRunStartupCommand: false, + willRunStartupInput: initialTerminalInput != nil + ) + } } } @@ -8025,7 +8032,6 @@ final class Workspace: Identifiable, ObservableObject { initialCommand: startupCommand, tmuxStartCommand: tmuxStartCommand, initialInput: initialInput, - startupRestoreAgent: startupRestoreAgent, additionalEnvironment: effectiveStartupEnvironment, runtimeSpawnPolicy: runtimeSpawnPolicy ) @@ -8063,6 +8069,14 @@ final class Workspace: Identifiable, ObservableObject { } bindSurface(newTabId, toPanelId: newPanel.id) + if let startupRestoreAgent { + seedSessionRestoredAgentState( + panelId: newPanel.id, + restorableAgent: startupRestoreAgent, + willRunStartupCommand: false, + willRunStartupInput: initialInput != nil + ) + } publishCmuxSurfaceCreated(newPanel.id, paneId: paneId, kind: "terminal", origin: "terminal_tab", focused: shouldFocusNewTab) // bonsplit's createTab may not reliably emit didSelectTab, and its internal selection @@ -11539,7 +11553,6 @@ final class Workspace: Identifiable, ObservableObject { portOrdinal: portOrdinal, initialCommand: startupCommand, initialInput: initialInput, - startupRestoreAgent: startupRestoreAgent, additionalEnvironment: effectiveStartupEnvironment ) configureNewTerminalPanel(newPanel) @@ -11569,6 +11582,14 @@ final class Workspace: Identifiable, ObservableObject { } return nil } + if let startupRestoreAgent { + seedSessionRestoredAgentState( + panelId: newPanel.id, + restorableAgent: startupRestoreAgent, + willRunStartupCommand: false, + willRunStartupInput: initialInput != nil + ) + } publishCmuxSplitCreated(newPaneId, sourcePaneId: paneId, orientation: orientation, surfaceId: newPanel.id, kind: "terminal", origin: "terminal_split", focused: true) bonsplitController.selectTab(newTab.id) diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift index eb0317303f12..1043b680ee63 100644 --- a/cmuxTests/SessionEntryResumeLaunchTests.swift +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -213,4 +213,57 @@ struct SessionEntryResumeLaunchTests { == sessionID ) } + + @Test("Vault tab and split placements seed persistent lifecycle state") + func vaultPlacementPathsSeedLifecycleState() throws { + let sessionID = "vault-placement-session" + let entry = SessionEntry( + id: "codex:\(sessionID)", + agent: .codex, + sessionId: sessionID, + title: "Placed Vault session", + cwd: "/tmp/vault-placement-project", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_004), + fileURL: nil, + specifics: .codex( + model: nil, + approvalPolicy: nil, + sandboxMode: nil, + effort: nil + ) + ) + let launch = try #require(entry.resumeLaunch) + let restorableAgent = try #require(launch.startupRestoreAgent) + let workspace = Workspace() + defer { workspace.teardownAllPanels() } + let initialPanelID = try #require(workspace.focusedPanelId) + let paneID = try #require(workspace.paneId(forPanelId: initialPanelID)) + + let tabPanel = try #require(workspace.newTerminalSurface( + inPane: paneID, + focus: true, + workingDirectory: launch.workingDirectory, + initialInput: launch.initialInput, + startupRestoreAgent: restorableAgent + )) + let splitPanel = try #require(workspace.splitPaneWithNewTerminal( + targetPane: paneID, + orientation: .horizontal, + insertFirst: false, + workingDirectory: launch.workingDirectory, + initialInput: launch.initialInput, + startupRestoreAgent: restorableAgent + )) + let persisted = workspace.sessionSnapshot(includeScrollback: false) + + for panelID in [tabPanel.id, splitPanel.id] { + #expect(workspace.restoredAgentSnapshotsByPanelId[panelID]?.sessionId == sessionID) + #expect( + persisted.panels.first { $0.id == panelID }?.terminal?.agent?.sessionId + == sessionID + ) + } + } } diff --git a/cmuxTests/WorkspaceUnitTests.swift b/cmuxTests/WorkspaceUnitTests.swift index 004bbb268d3e..84ab466ffbfc 100644 --- a/cmuxTests/WorkspaceUnitTests.swift +++ b/cmuxTests/WorkspaceUnitTests.swift @@ -3318,6 +3318,7 @@ final class WorkspaceCreationPlacementTests: XCTestCase { initialSurface: NewWorkspaceInitialSurface, initialTerminalCommand: String?, initialTerminalInput: String?, + initialTerminalStartupRestoreAgent: SessionRestorableAgentSnapshot?, initialTerminalEnvironment: [String: String], initialBrowserURL: URL?, initialBrowserOmnibarVisible: Bool, @@ -3335,6 +3336,7 @@ final class WorkspaceCreationPlacementTests: XCTestCase { initialSurface: initialSurface, initialTerminalCommand: initialTerminalCommand, initialTerminalInput: initialTerminalInput, + initialTerminalStartupRestoreAgent: initialTerminalStartupRestoreAgent, initialTerminalEnvironment: initialTerminalEnvironment, initialBrowserURL: initialBrowserURL, initialBrowserOmnibarVisible: initialBrowserOmnibarVisible, @@ -3631,6 +3633,7 @@ final class WorkspaceCreationConfigSanitizationTests: XCTestCase { initialSurface: NewWorkspaceInitialSurface, initialTerminalCommand: String?, initialTerminalInput: String?, + initialTerminalStartupRestoreAgent: SessionRestorableAgentSnapshot?, initialTerminalEnvironment: [String: String], initialBrowserURL: URL?, initialBrowserOmnibarVisible: Bool, @@ -3648,6 +3651,7 @@ final class WorkspaceCreationConfigSanitizationTests: XCTestCase { initialSurface: initialSurface, initialTerminalCommand: initialTerminalCommand, initialTerminalInput: initialTerminalInput, + initialTerminalStartupRestoreAgent: initialTerminalStartupRestoreAgent, initialTerminalEnvironment: initialTerminalEnvironment, initialBrowserURL: initialBrowserURL, initialBrowserOmnibarVisible: initialBrowserOmnibarVisible, From 7c866e496c13f77802894f564792c2a20d9c2305 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 20:10:17 -0700 Subject: [PATCH 5/8] refactor: quarantine Vault copy resume commands --- Sources/SessionEntryResumeLaunch.swift | 19 +++++++++++++++++-- Sources/SessionIndexModels.swift | 8 -------- .../ClaudeConfigDirectoryPathTests.swift | 4 ++-- cmuxTests/HermesFirstClassSupportTests.swift | 8 ++++---- cmuxTests/PiVaultAgentPersistenceTests.swift | 18 +++++++++--------- ...storableAgentHookProviderHermesTests.swift | 2 +- cmuxTests/RovoDevSessionIndexTests.swift | 2 +- cmuxTests/SessionIndexViewTests.swift | 14 +++++++------- cmuxTests/SessionPersistenceTests.swift | 4 ++-- 9 files changed, 43 insertions(+), 36 deletions(-) diff --git a/Sources/SessionEntryResumeLaunch.swift b/Sources/SessionEntryResumeLaunch.swift index 704a25282774..d6e33717a345 100644 --- a/Sources/SessionEntryResumeLaunch.swift +++ b/Sources/SessionEntryResumeLaunch.swift @@ -2,22 +2,34 @@ import CMUXAgentLaunch import Foundation /// The terminal startup plan shared by every Vault resume entry point. -struct SessionEntryResumeLaunch: Sendable { +nonisolated struct SessionEntryResumeLaunch: Sendable { + /// How the terminal starts the selected Vault session. enum Strategy: Sendable, Equatable { + /// Resolve structured argv and environment through `cmux restore`. case restoreVerb + /// Type the quarantined copyable command for an unsupported registration. case legacyCommand } + /// The selected structured or compatibility launch strategy. let strategy: Strategy + /// Input queued into the new terminal, including its trailing return. let initialInput: String + /// The directory requested for the new terminal surface. let workingDirectory: String? + /// Lifecycle state used by the restore responder and session persistence. let startupRestoreAgent: SessionRestorableAgentSnapshot? } -private struct SessionEntryResumeSnapshotComponents { +/// Agent-specific launch fields used to assemble one restorable snapshot. +nonisolated private struct SessionEntryResumeSnapshotComponents { + /// Captured executable and option arguments before resume arguments are applied. let arguments: [String] + /// Replay-safe environment required by the agent profile. let environment: [String: String] + /// Registration metadata for custom Vault agents. let registration: CmuxVaultAgentRegistration? + /// Captured permission mode when the agent exposes one separately from argv. let permissionMode: String? } @@ -47,6 +59,7 @@ extension SessionEntry { return legacyResumeLaunch } + /// Builds the explicit compatibility launch for an unsupported registration. private var legacyResumeLaunch: SessionEntryResumeLaunch? { guard let legacyCommand = copyResumeCommand else { return nil } return SessionEntryResumeLaunch( @@ -57,6 +70,7 @@ extension SessionEntry { ) } + /// Converts this Vault record into the lifecycle snapshot consumed by restore. private var vaultResumeSnapshot: SessionRestorableAgentSnapshot? { let components: SessionEntryResumeSnapshotComponents switch specifics { @@ -212,6 +226,7 @@ extension SessionEntry { return arguments } + /// Normalizes optional Vault metadata before it enters structured launch state. private static func nonEmptyResumeValue(_ value: String?) -> String? { guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { diff --git a/Sources/SessionIndexModels.swift b/Sources/SessionIndexModels.swift index 029adc46cfc9..51c8ccf3518f 100644 --- a/Sources/SessionIndexModels.swift +++ b/Sources/SessionIndexModels.swift @@ -297,14 +297,6 @@ struct SessionEntry: Identifiable, Hashable, Sendable { ) } - /// Compatibility name for the copyable resume command. - /// - /// Runtime Vault resume must use `resumeLaunch`; this rendered shell command - /// remains only for Copy Resume Command and its explicit unsupported-agent fallback. - var resumeCommand: String? { - copyResumeCommand - } - /// Shell command exposed by the Copy Resume Command menu item. var copyResumeCommand: String? { guard let command = copyResumeCommandWithoutWorkingDirectory else { return nil } diff --git a/cmuxTests/ClaudeConfigDirectoryPathTests.swift b/cmuxTests/ClaudeConfigDirectoryPathTests.swift index b74fbd2de2c6..5a85c5d5e1a6 100644 --- a/cmuxTests/ClaudeConfigDirectoryPathTests.swift +++ b/cmuxTests/ClaudeConfigDirectoryPathTests.swift @@ -56,7 +56,7 @@ final class ClaudeConfigDirectoryPathTests: XCTestCase { XCTAssertNil(ClaudeConfigurationRoot.configuredResumeDirectory(root.appendingPathComponent(".claude").path)) let command = try XCTUnwrap( - makeClaudeSessionEntry(fileURL: transcriptURL).resumeCommand + makeClaudeSessionEntry(fileURL: transcriptURL).copyResumeCommand ) XCTAssertFalse(command.contains("CLAUDE_CONFIG_DIR=")) @@ -113,7 +113,7 @@ final class ClaudeConfigDirectoryPathTests: XCTestCase { makeClaudeSessionEntry( fileURL: transcriptURL, configDirectoryForResume: resumeConfigDir - ).resumeCommand + ).copyResumeCommand ) XCTAssertTrue(command.contains("CLAUDE_CONFIG_DIR=\(configDir.path)")) diff --git a/cmuxTests/HermesFirstClassSupportTests.swift b/cmuxTests/HermesFirstClassSupportTests.swift index b282261b22e3..4cb5a8a67a35 100644 --- a/cmuxTests/HermesFirstClassSupportTests.swift +++ b/cmuxTests/HermesFirstClassSupportTests.swift @@ -1158,7 +1158,7 @@ struct HermesFirstClassSupportTests { posixCommand: "env HERMES_HOME=\(expectedHome) \(AgentResumeArgv.hermesWrapperShellExecutableToken) --profile default --resume indexed-session --model test-model" ) #expect( - entry.resumeCommand + entry.copyResumeCommand == "cd -- \(expectedCWD) 2>/dev/null || [ ! -d \(expectedCWD) ] && \(expectedResume)" ) } @@ -1205,7 +1205,7 @@ struct HermesFirstClassSupportTests { specifics: .hermesAgent(source: "tui", model: nil, hermesHome: nil) ) let expectedHome = HermesAgentSessionResolver.hermesHome(env: ["HOME": NSHomeDirectory()]) - let resumeCommand = try #require(entry.resumeCommand) + let resumeCommand = try #require(entry.copyResumeCommand) let result = try runProcess( executablePath: "/bin/sh", arguments: ["-c", resumeCommand], @@ -1283,7 +1283,7 @@ struct HermesFirstClassSupportTests { hermesHome: hermesHome.path ) ) - let resumeCommand = try #require(entry.resumeCommand) + let resumeCommand = try #require(entry.copyResumeCommand) return try runProcess( executablePath: "/bin/sh", arguments: ["-c", resumeCommand], @@ -1316,7 +1316,7 @@ struct HermesFirstClassSupportTests { let expectedResume = AgentResumeArgv.portableHermesResumeShellCommand( posixCommand: "env HERMES_HOME=/tmp/hermes/profiles/coder \(AgentResumeArgv.hermesWrapperShellExecutableToken) --tui --resume indexed-session" ) - #expect(entry.resumeCommand == expectedResume) + #expect(entry.copyResumeCommand == expectedResume) } @MainActor diff --git a/cmuxTests/PiVaultAgentPersistenceTests.swift b/cmuxTests/PiVaultAgentPersistenceTests.swift index f295c789b4ae..db8dc7b86be7 100644 --- a/cmuxTests/PiVaultAgentPersistenceTests.swift +++ b/cmuxTests/PiVaultAgentPersistenceTests.swift @@ -105,7 +105,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(entry.title, "Implement Antigravity notifications") XCTAssertEqual(entry.cwd, "/tmp/antigravity repo") XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/antigravity repo' 2>/dev/null || [ ! -d '/tmp/antigravity repo' ] && 'agy' '--conversation' 'antigravity-conversation-123'" ) } @@ -147,7 +147,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { ) XCTAssertEqual(filtered.map(\.sessionId), ["conversation-b"]) XCTAssertEqual( - filtered.first?.resumeCommand, + filtered.first?.copyResumeCommand, "cd -- '/tmp/antigravity repo' 2>/dev/null || [ ! -d '/tmp/antigravity repo' ] && 'agy' '--conversation' 'conversation-b'" ) } @@ -256,7 +256,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { let entry = try XCTUnwrap(entries.first) XCTAssertEqual(entry.sessionId, "native-session-123") - XCTAssertEqual(entry.resumeCommand, "cd -- '/tmp/acme' 2>/dev/null || [ ! -d '/tmp/acme' ] && 'acme-agent' '--session' 'native-session-123'") + XCTAssertEqual(entry.copyResumeCommand, "cd -- '/tmp/acme' 2>/dev/null || [ ! -d '/tmp/acme' ] && 'acme-agent' '--session' 'native-session-123'") } func testBuiltInGrokRegistrationUsesNativeSessionDirectory() { @@ -414,7 +414,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { ) XCTAssertNil(entry.resumeWorkingDirectory) - XCTAssertEqual(entry.resumeCommand, "'acme-agent' '--session' 'session-123'") + XCTAssertEqual(entry.copyResumeCommand, "'acme-agent' '--session' 'session-123'") } func testRegisteredAgentJSONLNativeSessionIDOverridesPathFallback() async throws { @@ -682,7 +682,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(entry.gitBranch, "issue-4394-grok-vault-resume") XCTAssertEqual(entry.fileURL?.resolvingSymlinksInPath(), historyURL.resolvingSymlinksInPath()) XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/grok repo' 2>/dev/null || [ ! -d '/tmp/grok repo' ] && 'env' 'GROK_HOME=\(grokHome.path)' 'grok' '-r' 'grok-session-123' '-m' 'grok-4' '--permission-mode' 'auto' '--sandbox' 'danger-full-access'" ) } @@ -834,7 +834,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(entry.title, "Find sessions under shell GROK_HOME") XCTAssertEqual(entry.cwd, cwd) XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/grok observed home' 2>/dev/null || [ ! -d '/tmp/grok observed home' ] && 'env' 'GROK_HOME=\(grokHome.path)' 'grok' '-r' '\(sessionId)' '-m' 'grok-4' '--permission-mode' 'auto' '--sandbox' 'danger-full-access'" ) } @@ -895,7 +895,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(entry.sessionId, sessionId) XCTAssertEqual(entry.title, "Find sessions under custom hook state") XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/grok custom state' 2>/dev/null || [ ! -d '/tmp/grok custom state' ] && 'env' 'GROK_HOME=\(grokHome.path)' 'grok' '-r' '\(sessionId)' '-m' 'grok-4'" ) } @@ -946,7 +946,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(entry.cwd, cwd) XCTAssertEqual(entry.gitBranch, "issue-4394-grok-vault-resume") XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/custom grok repo' 2>/dev/null || [ ! -d '/tmp/custom grok repo' ] && 'env' 'GROK_HOME=\(tempDir.path)' 'custom-grok' '-r' '\(sessionId)'" ) } @@ -1108,7 +1108,7 @@ final class PiVaultAgentPersistenceTests: XCTestCase { XCTAssertEqual(loadedAgent.kind.rawValue, "pi") XCTAssertEqual(loadedAgent.sessionId, sessionPath) XCTAssertEqual( - loadedAgent.resumeCommand, + loadedAgent.copyResumeCommand, TerminalStartupWorkingDirectoryPrefix.prefix( "'env' 'PI_CODING_AGENT_SESSION_DIR=\(tempDir.path)' '/opt/homebrew/bin/pi' '--session' '\(sessionPath)' '--session-dir' '\(tempDir.path)'", workingDirectory: "/tmp/pi repo" diff --git a/cmuxTests/RestorableAgentHookProviderHermesTests.swift b/cmuxTests/RestorableAgentHookProviderHermesTests.swift index a6d0de55c1ba..d6a66187968d 100644 --- a/cmuxTests/RestorableAgentHookProviderHermesTests.swift +++ b/cmuxTests/RestorableAgentHookProviderHermesTests.swift @@ -92,7 +92,7 @@ extension SocketListenerAcceptPolicyTests { let expectedResume = AgentResumeArgv.portableHermesResumeShellCommand( posixCommand: "env HERMES_HOME='/tmp/hermes home' \(AgentResumeArgv.hermesWrapperShellExecutableToken) --profile default --tui --resume hermes-session-123 --model gpt-5.4" ) - XCTAssertEqual(entry.resumeCommand, expectedResume) + XCTAssertEqual(entry.copyResumeCommand, expectedResume) } func testHermesAgentResumeCommandPreservesSubrouterBaseURLs() { diff --git a/cmuxTests/RovoDevSessionIndexTests.swift b/cmuxTests/RovoDevSessionIndexTests.swift index 52614e9973f0..a9337a4b743c 100644 --- a/cmuxTests/RovoDevSessionIndexTests.swift +++ b/cmuxTests/RovoDevSessionIndexTests.swift @@ -123,7 +123,7 @@ final class RovoDevSessionIndexTests: XCTestCase { XCTAssertEqual(entry.cwd, "/tmp/rovo repo") XCTAssertEqual(entry.fileURL?.lastPathComponent, "session_context.json") XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd -- '/tmp/rovo repo' 2>/dev/null || [ ! -d '/tmp/rovo repo' ] && acli rovodev run --restore 'session with space'" ) } diff --git a/cmuxTests/SessionIndexViewTests.swift b/cmuxTests/SessionIndexViewTests.swift index 2d06b41bd8dd..a5a6f951839c 100644 --- a/cmuxTests/SessionIndexViewTests.swift +++ b/cmuxTests/SessionIndexViewTests.swift @@ -88,7 +88,7 @@ struct SessionIndexViewTests { ) #expect( - entry.resumeCommand + entry.copyResumeCommand == posixShWrappedForTest("env CLAUDE_CONFIG_DIR='\(configDir.path)' CMUX_PRESERVE_CLAUDE_AUTH_SELECTION_ENV=1 CMUX_PRESERVE_CLAUDE_AUTH_SELECTION_ENV_KEYS=CLAUDE_CONFIG_DIR \"$([ -x \"${CMUX_CLAUDE_WRAPPER_SHIM:-}\" ] && printf '%s' \"$CMUX_CLAUDE_WRAPPER_SHIM\" || printf claude)\" --resume claude-session-123") ) } @@ -121,7 +121,7 @@ struct SessionIndexViewTests { ) #expect( - entry.resumeCommand + entry.copyResumeCommand == posixShWrappedForTest("env CLAUDE_CONFIG_DIR='\(configDir.path)' CMUX_PRESERVE_CLAUDE_AUTH_SELECTION_ENV=1 CMUX_PRESERVE_CLAUDE_AUTH_SELECTION_ENV_KEYS=CLAUDE_CONFIG_DIR \"$([ -x \"${CMUX_CLAUDE_WRAPPER_SHIM:-}\" ] && printf '%s' \"$CMUX_CLAUDE_WRAPPER_SHIM\" || printf claude)\" --resume claude-session-123") ) } @@ -141,7 +141,7 @@ struct SessionIndexViewTests { ) #expect( - entry.resumeCommand + entry.copyResumeCommand == "'env' 'GROK_HOME=/tmp/grok home' 'grok' '-r' 'grok-session-123' '-m' 'grok-4' '--permission-mode' 'auto' '--sandbox' 'danger-full-access'" ) } @@ -167,7 +167,7 @@ struct SessionIndexViewTests { ) ) - let command = entry.resumeCommand ?? "" + let command = entry.copyResumeCommand ?? "" // The codex resume now routes the codex executable through the cmux codex // wrapper token and wraps the rendered command in `/bin/sh -c '…'` so a // resumed codex session keeps its hooks (issue #5639). Assert the inner @@ -199,7 +199,7 @@ struct SessionIndexViewTests { ) ) - let command = entry.resumeCommand ?? "" + let command = entry.copyResumeCommand ?? "" let inner = Self.unwrapPortableShellCommand(command) #expect( inner @@ -225,7 +225,7 @@ struct SessionIndexViewTests { ) ) #expect( - Self.unwrapPortableShellCommand(readOnly.resumeCommand ?? "") + Self.unwrapPortableShellCommand(readOnly.copyResumeCommand ?? "") == "\(AgentResumeArgv.codexWrapperShellExecutableToken) resume codex-ro -c check_for_update_on_startup=false -a untrusted -s read-only" ) @@ -241,7 +241,7 @@ struct SessionIndexViewTests { ) ) #expect( - Self.unwrapPortableShellCommand(dangerFullAccess.resumeCommand ?? "") + Self.unwrapPortableShellCommand(dangerFullAccess.copyResumeCommand ?? "") == "\(AgentResumeArgv.codexWrapperShellExecutableToken) resume codex-dfa -c check_for_update_on_startup=false -m gpt-5.5 -a never -s danger-full-access" ) } diff --git a/cmuxTests/SessionPersistenceTests.swift b/cmuxTests/SessionPersistenceTests.swift index 93c80c628c37..d8f6f3b402f2 100644 --- a/cmuxTests/SessionPersistenceTests.swift +++ b/cmuxTests/SessionPersistenceTests.swift @@ -2475,7 +2475,7 @@ final class SocketListenerAcceptPolicyTests: XCTestCase { ) XCTAssertEqual( - entry.resumeCommand, + entry.copyResumeCommand, "cd /Users/tiffanysun/fun && /bin/sh -c " + shellQuotedForTest("\(AgentResumeArgv.claudeWrapperShellExecutableToken) --resume a22293b7-bcef-4707-8439-2f538c8517a4") ) @@ -2507,7 +2507,7 @@ final class SocketListenerAcceptPolicyTests: XCTestCase { ) ) - let command = try XCTUnwrap(entry.resumeCommand) + let command = try XCTUnwrap(entry.copyResumeCommand) XCTAssertTrue( command.utf8.allSatisfy { $0 < 0x80 }, "Terminal startup input must stay ASCII-only so UTF-8 paths are reconstructed by the shell instead of being mojibaked before execution." From 78b2492d2e53b1f12d89e933ba8ec9fda296f5a1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 20:13:43 -0700 Subject: [PATCH 6/8] test: cover Vault restore fallback and placement --- cmuxTests/SessionEntryResumeLaunchTests.swift | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift index 1043b680ee63..8fa63e14720b 100644 --- a/cmuxTests/SessionEntryResumeLaunchTests.swift +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -93,6 +93,38 @@ struct SessionEntryResumeLaunchTests { ) } + @Test("Unencodable custom Vault kinds use the explicit legacy strategy") + func unencodableCustomKindUsesLegacyFallback() throws { + let registration = CmuxVaultAgentRegistration( + id: "legacy agent", + name: "Legacy Agent", + detect: CmuxVaultAgentDetectRule(processName: "legacy-agent"), + sessionIdSource: .argvOption("--session"), + resumeCommand: "{{executable}} --session {{sessionId}}", + cwd: .preserve + ) + let entry = SessionEntry( + id: "legacy agent:legacy-session", + agent: .registered(RegisteredSessionAgent(registration: registration)), + sessionId: "legacy-session", + title: "Legacy session", + cwd: "/tmp/legacy-project", + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_002), + fileURL: nil, + specifics: .registered(registration) + ) + + let copiedCommand = try #require(entry.copyResumeCommand) + let launch = try #require(entry.resumeLaunch) + #expect(launch.strategy == .legacyCommand) + #expect(launch.initialInput == copiedCommand + "\n") + #expect(launch.workingDirectory == "/tmp/legacy-project") + #expect(launch.startupRestoreAgent == nil) + #expect(!launch.initialInput.contains(" restore legacy agent ")) + } + @Test("Restore responder resolves a Vault snapshot through lifecycle state") func responderResolvesVaultLifecycleSnapshot() throws { let entry = SessionEntry( @@ -154,6 +186,10 @@ struct SessionEntryResumeLaunchTests { target: target, binding: nil ) == nil) + #expect( + workspace.sessionSnapshot(includeScrollback: false) + .panels.first { $0.id == panelID }?.terminal?.agent == nil + ) } @Test("Vault-restored chats persist and resume after a session round trip") @@ -266,4 +302,86 @@ struct SessionEntryResumeLaunchTests { ) } } + + @Test("Vault coordinator preserves matching-cwd and new-workspace placement") + func coordinatorPreservesWorkingDirectoryPlacement() throws { + let matchingDirectory = "/tmp/vault-coordinator-match" + let manager = TabManager( + initialWorkingDirectory: matchingDirectory, + autoWelcomeIfNeeded: false + ) + defer { manager.tabs.forEach { $0.teardownAllPanels() } } + let originalWorkspace = try #require(manager.selectedWorkspace) + let originalPanelID = try #require(originalWorkspace.focusedPanelId) + + let matchingEntry = SessionEntry( + id: "codex:matching-session", + agent: .codex, + sessionId: "matching-session", + title: "Matching session", + cwd: matchingDirectory, + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_005), + fileURL: nil, + specifics: .codex( + model: nil, + approvalPolicy: nil, + sandboxMode: nil, + effort: nil + ) + ) + let matchingLaunch = try #require(matchingEntry.resumeLaunch) + + SessionEntryResumeCoordinator.resume(matchingEntry, tabManager: manager) + + #expect(manager.tabs.count == 1) + #expect(manager.selectedWorkspace === originalWorkspace) + let matchingPanelID = try #require(originalWorkspace.focusedPanelId) + #expect(matchingPanelID != originalPanelID) + #expect( + originalWorkspace.restoredAgentSnapshotsByPanelId[matchingPanelID]?.sessionId + == "matching-session" + ) + #expect( + originalWorkspace.terminalPanel(for: matchingPanelID)? + .surface.debugInitialInputForTesting() == matchingLaunch.initialInput + ) + + let differentDirectory = "/tmp/vault-coordinator-new-workspace" + let differentEntry = SessionEntry( + id: "codex:different-session", + agent: .codex, + sessionId: "different-session", + title: "Different session", + cwd: differentDirectory, + gitBranch: nil, + pullRequest: nil, + modified: Date(timeIntervalSince1970: 1_800_000_006), + fileURL: nil, + specifics: .codex( + model: nil, + approvalPolicy: nil, + sandboxMode: nil, + effort: nil + ) + ) + let differentLaunch = try #require(differentEntry.resumeLaunch) + + SessionEntryResumeCoordinator.resume(differentEntry, tabManager: manager) + + #expect(manager.tabs.count == 2) + let createdWorkspace = try #require(manager.selectedWorkspace) + #expect(createdWorkspace !== originalWorkspace) + #expect(createdWorkspace.currentDirectory == differentDirectory) + let createdPanelID = try #require(createdWorkspace.focusedPanelId) + #expect( + createdWorkspace.restoredAgentSnapshotsByPanelId[createdPanelID]?.sessionId + == "different-session" + ) + #expect( + createdWorkspace.terminalPanel(for: createdPanelID)? + .surface.debugInitialInputForTesting() == differentLaunch.initialInput + ) + } } From 85f460a7a12ae8b2790d94b7edd6e38976c7ba1c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 20:33:58 -0700 Subject: [PATCH 7/8] test: cover Vault restore cwd lifecycle --- cmuxTests/SessionEntryResumeLaunchTests.swift | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/cmuxTests/SessionEntryResumeLaunchTests.swift b/cmuxTests/SessionEntryResumeLaunchTests.swift index 8fa63e14720b..2863703d1f62 100644 --- a/cmuxTests/SessionEntryResumeLaunchTests.swift +++ b/cmuxTests/SessionEntryResumeLaunchTests.swift @@ -228,6 +228,10 @@ struct SessionEntryResumeLaunchTests { ) defer { source.teardownAllPanels() } let sourcePanelID = try #require(source.focusedPanelId) + #expect( + source.restoredResumeSessionWorkingDirectoriesByPanelId[sourcePanelID] + == launch.workingDirectory + ) let persisted = source.sessionSnapshot(includeScrollback: false) #expect( persisted.panels.first { $0.id == sourcePanelID }?.terminal?.agent?.sessionId @@ -243,6 +247,10 @@ struct SessionEntryResumeLaunchTests { let restoredPanel = try #require(restored.terminalPanel(for: restoredPanelID)) #expect(restoredPanel.surface.debugInitialInputForTesting() == launch.initialInput) + #expect( + restored.restoredResumeSessionWorkingDirectoriesByPanelId[restoredPanelID] + == launch.workingDirectory + ) #expect( restored.sessionSnapshot(includeScrollback: false) .panels.first { $0.id == restoredPanelID }?.terminal?.agent?.sessionId @@ -253,12 +261,20 @@ struct SessionEntryResumeLaunchTests { @Test("Vault tab and split placements seed persistent lifecycle state") func vaultPlacementPathsSeedLifecycleState() throws { let sessionID = "vault-placement-session" + let workingDirectory = FileManager.default.temporaryDirectory + .appending(path: "cmux-vault-placement-\(UUID().uuidString)", directoryHint: .isDirectory) + .path + try FileManager.default.createDirectory( + atPath: workingDirectory, + withIntermediateDirectories: true + ) + defer { try? FileManager.default.removeItem(atPath: workingDirectory) } let entry = SessionEntry( id: "codex:\(sessionID)", agent: .codex, sessionId: sessionID, title: "Placed Vault session", - cwd: "/tmp/vault-placement-project", + cwd: workingDirectory, gitBranch: nil, pullRequest: nil, modified: Date(timeIntervalSince1970: 1_800_000_004), @@ -296,11 +312,25 @@ struct SessionEntryResumeLaunchTests { for panelID in [tabPanel.id, splitPanel.id] { #expect(workspace.restoredAgentSnapshotsByPanelId[panelID]?.sessionId == sessionID) + #expect( + workspace.restoredResumeSessionWorkingDirectoriesByPanelId[panelID] + == workingDirectory + ) #expect( persisted.panels.first { $0.id == panelID }?.terminal?.agent?.sessionId == sessionID ) } + + workspace.restoredAgentResumeStatesByPanelId[tabPanel.id] = .autoResumeCommandRunning + workspace.panelDirectories[tabPanel.id] = FileManager.default.homeDirectoryForCurrentUser.path + workspace.foregroundProcessWorkingDirectoryProvider = { _ in nil } + let inheritedSplit = try #require(workspace.newTerminalSplit( + from: tabPanel.id, + orientation: .vertical, + focus: false + )) + #expect(inheritedSplit.requestedWorkingDirectory == workingDirectory) } @Test("Vault coordinator preserves matching-cwd and new-workspace placement") @@ -343,6 +373,10 @@ struct SessionEntryResumeLaunchTests { originalWorkspace.restoredAgentSnapshotsByPanelId[matchingPanelID]?.sessionId == "matching-session" ) + #expect( + originalWorkspace.restoredResumeSessionWorkingDirectoriesByPanelId[matchingPanelID] + == matchingDirectory + ) #expect( originalWorkspace.terminalPanel(for: matchingPanelID)? .surface.debugInitialInputForTesting() == matchingLaunch.initialInput @@ -379,6 +413,10 @@ struct SessionEntryResumeLaunchTests { createdWorkspace.restoredAgentSnapshotsByPanelId[createdPanelID]?.sessionId == "different-session" ) + #expect( + createdWorkspace.restoredResumeSessionWorkingDirectoriesByPanelId[createdPanelID] + == differentDirectory + ) #expect( createdWorkspace.terminalPanel(for: createdPanelID)? .surface.debugInitialInputForTesting() == differentLaunch.initialInput From 6c194c4e17fc93daa800899552687cb403e9c2bf Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Mon, 10 Aug 2026 20:42:49 -0700 Subject: [PATCH 8/8] fix: unify restored-agent cwd lifecycle --- Sources/DockSplitStore+Reset.swift | 5 +- ...ockSplitStore+RestoredAgentLifecycle.swift | 10 +-- Sources/DockSplitStore+SessionRestore.swift | 33 ++-------- Sources/DockSplitStore+SurfaceResume.swift | 4 +- Sources/DockSplitStore.swift | 5 +- .../RestoredAgentLifecycleCoordinator.swift | 63 ++++++++++++++++++- Sources/Workspace+AgentLifecycle.swift | 29 ++++----- Sources/Workspace+PanelLifecycle.swift | 4 +- Sources/Workspace.swift | 48 ++++++-------- ...ompletedRestoredAgentGenerationTests.swift | 3 +- 10 files changed, 111 insertions(+), 93 deletions(-) diff --git a/Sources/DockSplitStore+Reset.swift b/Sources/DockSplitStore+Reset.swift index 28eea2172e15..9c8aac14753c 100644 --- a/Sources/DockSplitStore+Reset.swift +++ b/Sources/DockSplitStore+Reset.swift @@ -22,14 +22,11 @@ extension DockSplitStore { agentRuntimeByPanelId.removeAll() agentNeedsInputAttention.replace(with: []) restoredTerminalScrollbackByPanelId.removeAll() - restoredAgentLifecycle.snapshotsByPanelId.removeAll() - restoredAgentLifecycle.resumeStatesByPanelId.removeAll() - restoredAgentLifecycle.invalidatedFingerprintsByPanelId.removeAll() + restoredAgentLifecycle.removeAllSessionRestores() surfaceResumeBindingsByPanelId.removeAll() managedAgentResumeBindingsByPanelId.removeAll() invalidatedCachedTransferAgentSessionPanelIds.removeAll() replacedCachedTransferAgentSessionPanelIds.removeAll() - restoredResumeSessionWorkingDirectoriesByPanelId.removeAll() panelCancellables.values.forEach { $0.cancel() } panelCancellables.removeAll() } diff --git a/Sources/DockSplitStore+RestoredAgentLifecycle.swift b/Sources/DockSplitStore+RestoredAgentLifecycle.swift index 9da8a4311312..530b757f3fcd 100644 --- a/Sources/DockSplitStore+RestoredAgentLifecycle.swift +++ b/Sources/DockSplitStore+RestoredAgentLifecycle.swift @@ -8,14 +8,12 @@ extension DockSplitStore { func clearSessionRestoreState(panelId: UUID) { discardPendingTerminalTitleUpdate(panelId: panelId) restoredTerminalScrollbackByPanelId.removeValue(forKey: panelId) - restoredAgentLifecycle.snapshotsByPanelId.removeValue(forKey: panelId) - restoredAgentLifecycle.resumeStatesByPanelId.removeValue(forKey: panelId) + restoredAgentLifecycle.clearSessionRestore(panelId: panelId) restoredAgentLifecycle.invalidatedFingerprintsByPanelId.removeValue(forKey: panelId) surfaceResumeBindingsByPanelId.removeValue(forKey: panelId) managedAgentResumeBindingsByPanelId.removeValue(forKey: panelId) invalidatedCachedTransferAgentSessionPanelIds.remove(panelId) replacedCachedTransferAgentSessionPanelIds.remove(panelId) - restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: panelId) agentRuntimeByPanelId.removeValue(forKey: panelId) syncAgentNeedsInputAttention(panelId: panelId, runtime: nil) restoredPanelTitleBoundariesByPanelId.removeValue(forKey: panelId) @@ -133,7 +131,8 @@ extension DockSplitStore { panelId: detached.panelId, snapshot: detached.restorableAgent, resumeState: detached.restorableAgentResumeState, - completedGeneration: detached.restoredAgentCompletedGeneration + completedGeneration: detached.restoredAgentCompletedGeneration, + resumeWorkingDirectory: detached.restoredResumeSessionWorkingDirectory ) managedAgentResumeBindingsByPanelId.removeValue(forKey: detached.panelId) if let resumeBinding = detached.resumeBinding { @@ -142,9 +141,6 @@ extension DockSplitStore { if let transferredManagedBinding = detached.resolvedManagedAgentResumeBinding { managedAgentResumeBindingsByPanelId[detached.panelId] = transferredManagedBinding } - if let directory = detached.restoredResumeSessionWorkingDirectory { - restoredResumeSessionWorkingDirectoriesByPanelId[detached.panelId] = directory - } if let runtime = detached.agentRuntime { agentRuntimeByPanelId[detached.panelId] = runtime } else { diff --git a/Sources/DockSplitStore+SessionRestore.swift b/Sources/DockSplitStore+SessionRestore.swift index 69cbd4142139..78840e0b7534 100644 --- a/Sources/DockSplitStore+SessionRestore.swift +++ b/Sources/DockSplitStore+SessionRestore.swift @@ -328,12 +328,14 @@ extension DockSplitStore { let willRunAgentInput = agentLaunch?.initialInput != nil || (bindingLaunch?.initialInput != nil && resumeBinding?.isAgentHookBinding == true) - seedSessionRestoredAgentState( + restoredAgentLifecycle.seedSessionRestore( panelId: terminal.id, - restorableAgent: restorableAgent, - resumeBinding: managedResumeBinding ?? resumeBinding, + snapshot: restorableAgent, + manualResumeAvailable: restorableAgent != nil || + (managedResumeBinding ?? resumeBinding)?.isAgentHookBinding == true, willRunStartupCommand: willRunAgentCommand, - willRunStartupInput: willRunAgentInput + willRunStartupInput: willRunAgentInput, + resumeWorkingDirectory: resumeSessionWorkingDirectory ) if let hibernation, let restorableAgent, restorableAgent.resumeCommand != nil { terminal.enterAgentHibernation( @@ -342,10 +344,6 @@ extension DockSplitStore { hibernatedAt: Date(timeIntervalSince1970: hibernation.hibernatedAt) ) } - if willRunAgentCommand || willRunAgentInput, - let resumeSessionWorkingDirectory { - restoredResumeSessionWorkingDirectoriesByPanelId[terminal.id] = resumeSessionWorkingDirectory - } recordSessionResumeIntent( panelId: terminal.id, restorableAgent: restorableAgent, @@ -427,25 +425,6 @@ extension DockSplitStore { bonsplitController.selectTab(tabId) } - private func seedSessionRestoredAgentState( - panelId: UUID, - restorableAgent: SessionRestorableAgentSnapshot?, - resumeBinding: SurfaceResumeBindingSnapshot?, - willRunStartupCommand: Bool, - willRunStartupInput: Bool - ) { - restoredAgentLifecycle.snapshotsByPanelId[panelId] = restorableAgent - if willRunStartupCommand { - restoredAgentLifecycle.resumeStatesByPanelId[panelId] = .autoResumeCommandRunning - } else if willRunStartupInput { - restoredAgentLifecycle.resumeStatesByPanelId[panelId] = .awaitingAutoResumeCommand - } else if restorableAgent != nil || resumeBinding?.isAgentHookBinding == true { - restoredAgentLifecycle.resumeStatesByPanelId[panelId] = .manualResumeAvailable - } else { - restoredAgentLifecycle.resumeStatesByPanelId.removeValue(forKey: panelId) - } - } - private func sessionAgentAlreadyActive( restorableAgent: SessionRestorableAgentSnapshot?, snapshotPanelId: UUID, diff --git a/Sources/DockSplitStore+SurfaceResume.swift b/Sources/DockSplitStore+SurfaceResume.swift index bb771da24a85..07f1df7a6296 100644 --- a/Sources/DockSplitStore+SurfaceResume.swift +++ b/Sources/DockSplitStore+SurfaceResume.swift @@ -79,10 +79,8 @@ extension DockSplitStore { } private func clearRestoredAgentContinuationState(panelId: UUID) { - restoredAgentLifecycle.snapshotsByPanelId.removeValue(forKey: panelId) - restoredAgentLifecycle.resumeStatesByPanelId.removeValue(forKey: panelId) + restoredAgentLifecycle.clearSessionRestore(panelId: panelId) restoredAgentLifecycle.invalidatedFingerprintsByPanelId.removeValue(forKey: panelId) - restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: panelId) } @discardableResult diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index e67a34154590..980f4795ba89 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -79,7 +79,10 @@ final class DockSplitStore: BonsplitDelegate { @ObservationIgnored var managedAgentResumeBindingsByPanelId: [UUID: SurfaceResumeBindingSnapshot] = [:] @ObservationIgnored var invalidatedCachedTransferAgentSessionPanelIds: Set = [] @ObservationIgnored var replacedCachedTransferAgentSessionPanelIds: Set = [] - @ObservationIgnored var restoredResumeSessionWorkingDirectoriesByPanelId: [UUID: String] = [:] + var restoredResumeSessionWorkingDirectoriesByPanelId: [UUID: String] { + get { restoredAgentLifecycle.resumeWorkingDirectoriesByPanelId } + set { restoredAgentLifecycle.resumeWorkingDirectoriesByPanelId = newValue } + } var hasLoadedConfiguration = false var configurationLoadTask: Task? var configurationIdentityTask: Task? diff --git a/Sources/RestoredAgentLifecycleCoordinator.swift b/Sources/RestoredAgentLifecycleCoordinator.swift index 195d149cbd72..bd3e32d433a8 100644 --- a/Sources/RestoredAgentLifecycleCoordinator.swift +++ b/Sources/RestoredAgentLifecycleCoordinator.swift @@ -38,6 +38,9 @@ final class RestoredAgentLifecycleCoordinator { } } var invalidatedFingerprintsByPanelId: [UUID: Int] = [:] + /// Local resume targets retained while a restored launch owns the terminal. + /// Split and tab creation use these to recover from transient shell cwd reports. + var resumeWorkingDirectoriesByPanelId: [UUID: String] = [:] private var completedGenerationsByPanelId: [UUID: RestoredAgentCompletedGeneration] = [:] @@ -100,6 +103,53 @@ final class RestoredAgentLifecycleCoordinator { completedGenerationsByPanelId[panelId] } + /// Installs all lifecycle metadata for one newly restored terminal. + func seedSessionRestore( + panelId: UUID, + snapshot: SessionRestorableAgentSnapshot?, + manualResumeAvailable: Bool, + willRunStartupCommand: Bool, + willRunStartupInput: Bool, + resumeWorkingDirectory: String? + ) { + let resumeState: Workspace.RestoredAgentResumeState? + if willRunStartupCommand { + resumeState = .autoResumeCommandRunning + } else if willRunStartupInput { + resumeState = .awaitingAutoResumeCommand + } else if manualResumeAvailable { + resumeState = .manualResumeAvailable + } else { + resumeState = nil + } + snapshotsByPanelId[panelId] = snapshot + resumeStatesByPanelId[panelId] = resumeState + + let ownsStartupResume = resumeState == .awaitingAutoResumeCommand || + resumeState == .autoResumeCommandRunning + replaceResumeWorkingDirectory( + ownsStartupResume ? resumeWorkingDirectory : nil, + panelId: panelId + ) + invalidatedFingerprintsByPanelId.removeValue(forKey: panelId) + } + + /// Removes continuation metadata without discarding an invalidation fingerprint. + func clearSessionRestore(panelId: UUID) { + snapshotsByPanelId.removeValue(forKey: panelId) + resumeStatesByPanelId.removeValue(forKey: panelId) + resumeWorkingDirectoriesByPanelId.removeValue(forKey: panelId) + } + + /// Resets every restored-session lifecycle collection. + func removeAllSessionRestores() { + snapshotsByPanelId.removeAll(keepingCapacity: false) + resumeStatesByPanelId.removeAll(keepingCapacity: false) + invalidatedFingerprintsByPanelId.removeAll(keepingCapacity: false) + resumeWorkingDirectoriesByPanelId.removeAll(keepingCapacity: false) + completedGenerationsByPanelId.removeAll(keepingCapacity: false) + } + /// Shell integration has observed the restored launch enter its command /// phase and has not subsequently reported the prompt returning. func confirmsRunningRestoredCommand(panelId: UUID) -> Bool { @@ -126,7 +176,8 @@ final class RestoredAgentLifecycleCoordinator { panelId: UUID, snapshot: SessionRestorableAgentSnapshot?, resumeState: Workspace.RestoredAgentResumeState?, - completedGeneration: RestoredAgentCompletedGeneration? + completedGeneration: RestoredAgentCompletedGeneration?, + resumeWorkingDirectory: String? ) { if let snapshot { snapshotsByPanelId[panelId] = snapshot @@ -145,6 +196,16 @@ final class RestoredAgentLifecycleCoordinator { } else { resumeStatesByPanelId.removeValue(forKey: panelId) } + replaceResumeWorkingDirectory(resumeWorkingDirectory, panelId: panelId) + } + + private func replaceResumeWorkingDirectory(_ directory: String?, panelId: UUID) { + guard let directory = directory?.trimmingCharacters(in: .whitespacesAndNewlines), + !directory.isEmpty else { + resumeWorkingDirectoriesByPanelId.removeValue(forKey: panelId) + return + } + resumeWorkingDirectoriesByPanelId[panelId] = directory } private func observationSupersedesCompletion( diff --git a/Sources/Workspace+AgentLifecycle.swift b/Sources/Workspace+AgentLifecycle.swift index aa33c264af15..2ba3a282093c 100644 --- a/Sources/Workspace+AgentLifecycle.swift +++ b/Sources/Workspace+AgentLifecycle.swift @@ -495,23 +495,17 @@ extension Workspace { panelId: UUID, restorableAgent: SessionRestorableAgentSnapshot?, willRunStartupCommand: Bool, - willRunStartupInput: Bool + willRunStartupInput: Bool, + resumeSessionWorkingDirectory: String? ) { - if let restorableAgent { - restoredAgentSnapshotsByPanelId[panelId] = restorableAgent - } else { - restoredAgentSnapshotsByPanelId.removeValue(forKey: panelId) - } - if willRunStartupCommand { - restoredAgentResumeStatesByPanelId[panelId] = .autoResumeCommandRunning - } else if willRunStartupInput { - restoredAgentResumeStatesByPanelId[panelId] = .awaitingAutoResumeCommand - } else if restorableAgent != nil { - restoredAgentResumeStatesByPanelId[panelId] = .manualResumeAvailable - } else { - restoredAgentResumeStatesByPanelId.removeValue(forKey: panelId) - } - invalidatedRestoredAgentFingerprintsByPanelId.removeValue(forKey: panelId) + restoredAgentLifecycle.seedSessionRestore( + panelId: panelId, + snapshot: restorableAgent, + manualResumeAvailable: restorableAgent != nil, + willRunStartupCommand: willRunStartupCommand, + willRunStartupInput: willRunStartupInput, + resumeWorkingDirectory: resumeSessionWorkingDirectory + ) } func seedDetachedRestoredAgentState(from detached: DetachedSurfaceTransfer) { @@ -525,7 +519,8 @@ extension Workspace { panelId: detached.panelId, snapshot: detached.restorableAgent, resumeState: detached.restorableAgentResumeState, - completedGeneration: detached.restoredAgentCompletedGeneration + completedGeneration: detached.restoredAgentCompletedGeneration, + resumeWorkingDirectory: detached.restoredResumeSessionWorkingDirectory ) invalidatedRestoredAgentFingerprintsByPanelId.removeValue(forKey: detached.panelId) } diff --git a/Sources/Workspace+PanelLifecycle.swift b/Sources/Workspace+PanelLifecycle.swift index d3dfb77a65ff..9a786e0b1e35 100644 --- a/Sources/Workspace+PanelLifecycle.swift +++ b/Sources/Workspace+PanelLifecycle.swift @@ -347,9 +347,7 @@ extension Workspace { /// Clears a panel's restored agent snapshot and resume metadata. func clearRestoredAgentSnapshot(panelId: UUID) { - restoredAgentSnapshotsByPanelId.removeValue(forKey: panelId) - restoredAgentResumeStatesByPanelId.removeValue(forKey: panelId) - restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: panelId) + restoredAgentLifecycle.clearSessionRestore(panelId: panelId) } func refreshTrackedAgentPorts() { diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 8adb4d33a115..fba2f79b3406 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -209,12 +209,9 @@ extension Workspace { debugSessionSnapshotScrollbackFallbackPanelIds.removeAll(keepingCapacity: false) debugSessionSnapshotSyntheticScrollbackByPanelId.removeAll(keepingCapacity: false) #endif - restoredAgentSnapshotsByPanelId.removeAll(keepingCapacity: false) - restoredAgentResumeStatesByPanelId.removeAll(keepingCapacity: false) - invalidatedRestoredAgentFingerprintsByPanelId.removeAll(keepingCapacity: false) + restoredAgentLifecycle.removeAllSessionRestores() surfaceResumeBindingsByPanelId.removeAll(keepingCapacity: false) restoredGuardedWorkingDirectoriesByPanelId.removeAll(keepingCapacity: false) - restoredResumeSessionWorkingDirectoriesByPanelId.removeAll(keepingCapacity: false) restoredPanelTitleBoundariesByPanelId.removeAll(keepingCapacity: false) panelShellActivityStates.removeAll(keepingCapacity: false) @@ -1730,7 +1727,10 @@ extension Workspace { panelId: terminalPanel.id, restorableAgent: restorableAgent, willRunStartupCommand: restoredAgentWillRunStartupCommand, - willRunStartupInput: restoredAgentWillRunStartupInput + willRunStartupInput: restoredAgentWillRunStartupInput, + resumeSessionWorkingDirectory: restoredDirectoryIsLocalPath + ? resumeSessionWorkingDirectory + : nil ) if let restoredHibernation, restorableAgent.resumeCommand != nil { @@ -1745,23 +1745,12 @@ extension Workspace { panelId: terminalPanel.id, restorableAgent: nil, willRunStartupCommand: restoredAgentWillRunStartupCommand, - willRunStartupInput: restoredAgentWillRunStartupInput + willRunStartupInput: restoredAgentWillRunStartupInput, + resumeSessionWorkingDirectory: restoredDirectoryIsLocalPath + ? resumeSessionWorkingDirectory + : nil ) } - // While an auto-resumed agent-hook or restorable-agent launcher - // holds the pane's foreground no prompt runs, so a stray - // post-restore report can park the tracked cwd on the surface - // default with nothing left to repair it. Keep the resolved - // session directory for the run's lifetime so split/new-tab - // inheritance can rescue it (#7155). - if restoredAgentWillRunStartupCommand || restoredAgentWillRunStartupInput, - restoredDirectoryIsLocalPath, - let resumeSessionDirectory = resumeSessionWorkingDirectory?.trimmingCharacters(in: .whitespacesAndNewlines), - !resumeSessionDirectory.isEmpty { - restoredResumeSessionWorkingDirectoriesByPanelId[terminalPanel.id] = resumeSessionDirectory - } else { - restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: terminalPanel.id) - } terminalPanel.restoreSessionTextBoxDraft(snapshot.terminal?.textBoxDraft) applySessionPanelMetadata(snapshot, toPanelId: terminalPanel.id) armRestoredPanelTitleBoundary( @@ -2648,7 +2637,10 @@ final class Workspace: Identifiable, ObservableObject { /// The session directory each restored auto-resume launcher targets, kept /// for the resumed run so split/new-tab cwd inheritance can rescue a /// clobbered tracked cwd while the agent holds the pane's foreground (#7155). - var restoredResumeSessionWorkingDirectoriesByPanelId: [UUID: String] = [:] + var restoredResumeSessionWorkingDirectoriesByPanelId: [UUID: String] { + get { restoredAgentLifecycle.resumeWorkingDirectoriesByPanelId } + set { restoredAgentLifecycle.resumeWorkingDirectoriesByPanelId = newValue } + } enum RestoredAgentResumeState: Equatable { case manualResumeAvailable, awaitingAutoResumeCommand, autoResumeCommandRunning, observedAgentCommandRunning, completedAgentExit } @@ -3387,7 +3379,8 @@ final class Workspace: Identifiable, ObservableObject { panelId: terminalPanel.id, restorableAgent: initialTerminalStartupRestoreAgent, willRunStartupCommand: false, - willRunStartupInput: initialTerminalInput != nil + willRunStartupInput: initialTerminalInput != nil, + resumeSessionWorkingDirectory: initialTerminalStartupRestoreAgent.workingDirectory ) } } @@ -8079,7 +8072,8 @@ final class Workspace: Identifiable, ObservableObject { panelId: newPanel.id, restorableAgent: startupRestoreAgent, willRunStartupCommand: false, - willRunStartupInput: initialInput != nil + willRunStartupInput: initialInput != nil, + resumeSessionWorkingDirectory: startupRestoreAgent.workingDirectory ) } publishCmuxSurfaceCreated(newPanel.id, paneId: paneId, kind: "terminal", origin: "terminal_tab", focused: shouldFocusNewTab) @@ -9886,11 +9880,6 @@ final class Workspace: Identifiable, ObservableObject { surfaceId: detached.panelId ) seedDetachedRestoredAgentState(from: detached) - if let resumeSessionWorkingDirectory = detached.restoredResumeSessionWorkingDirectory { - restoredResumeSessionWorkingDirectoriesByPanelId[detached.panelId] = resumeSessionWorkingDirectory - } else { - restoredResumeSessionWorkingDirectoriesByPanelId.removeValue(forKey: detached.panelId) - } let transferredResumeBinding: SurfaceResumeBindingSnapshot? = { if let resumeBinding = detached.resumeBinding, !resumeBinding.isProcessDetected { @@ -11592,7 +11581,8 @@ final class Workspace: Identifiable, ObservableObject { panelId: newPanel.id, restorableAgent: startupRestoreAgent, willRunStartupCommand: false, - willRunStartupInput: initialInput != nil + willRunStartupInput: initialInput != nil, + resumeSessionWorkingDirectory: startupRestoreAgent.workingDirectory ) } publishCmuxSplitCreated(newPaneId, sourcePaneId: paneId, orientation: orientation, surfaceId: newPanel.id, kind: "terminal", origin: "terminal_split", focused: true) diff --git a/cmuxTests/CompletedRestoredAgentGenerationTests.swift b/cmuxTests/CompletedRestoredAgentGenerationTests.swift index d144a278b21f..5ad6b8ed7686 100644 --- a/cmuxTests/CompletedRestoredAgentGenerationTests.swift +++ b/cmuxTests/CompletedRestoredAgentGenerationTests.swift @@ -112,7 +112,8 @@ struct CompletedRestoredAgentGenerationTests { panelId: panelId, snapshot: snapshot, resumeState: .completedAgentExit, - completedGeneration: transferredGeneration + completedGeneration: transferredGeneration, + resumeWorkingDirectory: nil ) let replacementIdentity = AgentPIDProcessIdentity( pid: 654,