Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
1596a0f
test: cover Antigravity hook session snapshot restore
austinywang Sep 7, 2026
84c93ab
test: make the Antigravity hook snapshot restore test compile and kee…
austinywang Sep 8, 2026
c61d601
test: Antigravity hooks must dispatch to the terminal's own cmux first
austinywang Sep 8, 2026
d09f0dc
Route Antigravity hooks through the launching terminal's cmux before …
austinywang Sep 8, 2026
c6afdce
Replay a restored agent's startup input when the login shell drops it
austinywang Sep 8, 2026
230143d
Drop retained restore input on cancelled launches and log restore adm…
austinywang Sep 8, 2026
2dcf3a6
test: Antigravity hooks must fall back to the pinned build when ambie…
austinywang Sep 8, 2026
3040b17
Fall back to the pinned build when ambient hook dispatch fails; carry…
austinywang Sep 8, 2026
f7405bc
Resolve deferred agent restores against the last completed index inst…
austinywang Sep 8, 2026
4c3b807
test: an index that has not caught up with a fresh hook record must n…
austinywang Sep 8, 2026
42fdfa3
Keep agent-hook bindings until the live index has an entry for their …
austinywang Sep 8, 2026
e351484
Merge remote-tracking branch 'origin/main' into issue-5473-antigravit…
austinywang Sep 8, 2026
b1d4551
test: a pane moved after its shell idled must still replay the select…
austinywang Sep 8, 2026
cb383d3
Re-arm the restore selector replay when a pane is adopted after its s…
austinywang Sep 8, 2026
f9f6ea5
test: a fresh Antigravity launch without --conversation must still va…
austinywang Sep 8, 2026
d2ca12b
Accept a bare argv for argv-keyed agent registrations once pid identi…
austinywang Sep 8, 2026
845e8fa
Scope the bare-argv fallback to validations against the current hook …
austinywang Sep 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions CLI/CMUXCLI+AgentHookDefinitions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,16 @@ extension CMUXCLI {
routedArguments: routedArguments,
socketPath: socketPath
)
// The terminal that launched the agent owns the surface. When the agent
// preserved that terminal's cmux environment, dispatch there first so a
// session started from one cmux build (stable, nightly, a tagged dev
// build) is never reported to whichever build last ran `hooks setup`.
// The pinned install remains the fallback for sanitized hook
// environments, and for a stale socket node left by an exited app: the
// ambient invocation must succeed, otherwise the pinned chain runs.
// https://github.com/manaflow-ai/cmux/issues/5473
let ambientGuard = pinnedHookAmbientDispatchGuard
let ambientInvocation = pinnedHookAmbientInvocation(routedArguments: routedArguments)
let dispatch: String
if let cliPath = pinnedAgentHookCLIPath() {
let quotedCLIPath = shellSingleQuote(cliPath)
Expand All @@ -383,13 +393,24 @@ extension CMUXCLI {
routedArguments: routedArguments,
socketPath: socketPath
)
dispatch = "if [ -x \(quotedCLIPath) ]; then \(primaryInvocation); elif command -v cmux >/dev/null 2>&1; then \(fallbackInvocation); else \(noOpSnippet); fi"
dispatch = "if \(ambientGuard) && \(ambientInvocation); then :; elif [ -x \(quotedCLIPath) ]; then \(primaryInvocation); elif command -v cmux >/dev/null 2>&1; then \(fallbackInvocation); else \(noOpSnippet); fi"
} else {
dispatch = "command -v cmux >/dev/null 2>&1 && \(fallbackInvocation) || \(noOpSnippet)"
dispatch = "if \(ambientGuard) && \(ambientInvocation); then :; elif command -v cmux >/dev/null 2>&1; then \(fallbackInvocation); else \(noOpSnippet); fi"
}
return ": \(marker); \(shellTraceStart); printenv \(def.disableEnvVar) | grep -qx 1 && { \(shellTraceDisabled); \(noOpSnippet); } || { \(dispatch); cmux_hook_status=$?; \(shellTraceExit); exit $cmux_hook_status; }"
}

/// Shell test that is true only when the hook inherited a live cmux terminal
/// environment: a socket that exists plus an executable bundled CLI file.
/// `-f` matters because a directory also satisfies `-x`.
static let pinnedHookAmbientDispatchGuard =
"[ -n \"${CMUX_SOCKET_PATH:-}\" ] && [ -S \"$CMUX_SOCKET_PATH\" ] && [ -f \"${CMUX_BUNDLED_CLI_PATH:-}\" ] && [ -x \"$CMUX_BUNDLED_CLI_PATH\" ]"

/// Dispatches through the launching terminal's own cmux build and socket.
static func pinnedHookAmbientInvocation(routedArguments: String) -> String {
"\"$CMUX_BUNDLED_CLI_PATH\" --socket \"$CMUX_SOCKET_PATH\" \(routedArguments)"
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

private static func pinnedHookInvocation(
executable: String,
routedArguments: String,
Expand Down
3 changes: 3 additions & 0 deletions Sources/DockSplitStore+AttentionRouting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ extension DockSplitStore {
mountedTerminal === terminal else {
return
}
// The user (or a socket client) took over the pane: never replay a
// lost restore selector into a line they are typing.
self.restoredAgentLifecycle.clearStartupInput(panelId: terminal.id)
ownerTabManager?.dismissNotificationOnTerminalInteraction(
tabId: self.workspaceId,
surfaceId: terminal.id
Expand Down
47 changes: 45 additions & 2 deletions Sources/DockSplitStore+RestoredAgentLifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ extension DockSplitStore {
switch (state, restoredAgentLifecycle.resumeStatesByPanelId[panelId]) {
case (.commandRunning, .some(.awaitingAutoResumeCommand)):
restoredAgentLifecycle.setResumeState(.autoResumeCommandRunning, panelId: panelId)
restoredAgentLifecycle.clearStartupInput(panelId: panelId)
case (.promptIdle, .some(.awaitingAutoResumeCommand)):
scheduleRestoredStartupInputResend(panelId: panelId)
case (.commandRunning, .some(.manualResumeAvailable)):
restoredAgentLifecycle.setSnapshot(nil, panelId: panelId)
restoredAgentLifecycle.setResumeState(nil, panelId: panelId)
Expand Down Expand Up @@ -135,7 +138,8 @@ extension DockSplitStore {
snapshot: detached.restorableAgent,
resumeState: detached.restorableAgentResumeState,
completedGeneration: detached.restoredAgentCompletedGeneration,
resumeWorkingDirectory: detached.restoredResumeSessionWorkingDirectory
resumeWorkingDirectory: detached.restoredResumeSessionWorkingDirectory,
startupInput: detached.restoredStartupInput
)
managedAgentResumeBindingsByPanelId.removeValue(forKey: detached.panelId)
if let resumeBinding = detached.resumeBinding {
Expand Down Expand Up @@ -200,6 +204,40 @@ extension DockSplitStore {
return true
}

/// Dock twin of `Workspace.scheduleRestoredStartupInputResend(panelId:)`: a
/// login shell that discarded Ghostty's typeahead reports an idle prompt while
/// the launch still awaits its startup input, so replay it once after the
/// shared grace period (https://github.com/manaflow-ai/cmux/issues/5473).
func scheduleRestoredStartupInputResend(panelId: UUID) {
guard restoredAgentLifecycle.armStartupInputResend(panelId: panelId) else { return }
let grace = Workspace.restoredStartupInputResendGrace
DispatchQueue.main.asyncAfter(deadline: .now() + grace) { [weak self] in
Task { @MainActor [weak self] in
self?.resendRestoredStartupInputIfStillIdle(panelId: panelId)
}
}
}

func resendRestoredStartupInputIfStillIdle(panelId: UUID) {
guard let terminal = panels[panelId] as? TerminalPanel,
let input = restoredAgentLifecycle.takeStartupInputForResend(
panelId: panelId,
shellState: terminal.shellActivity.state
) else {
return
}
// The idle prompt came from a live runtime; never queue the selector
// for some future shell of this pane.
guard terminal.surface.surface != nil else { return }
let result = terminal.sendInputResult(input)
#if DEBUG
cmuxDebugLog(
"session.restore.startupInput.resend dock=\(workspaceId.uuidString.prefix(5)) " +
"panel=\(panelId.uuidString.prefix(5)) result=\(result) bytes=\(input.utf8.count)"
)
#endif
}

private func retireAgentHookResumeBinding(
panelId: UUID,
matching restoredAgent: SessionRestorableAgentSnapshot? = nil
Expand Down Expand Up @@ -680,10 +718,13 @@ extension DockSplitStore {
.awaitingAutoResumeCommand,
panelId: panelId
)
let admittedInput = restore.remoteResumeCommandEmbedded ? nil : startupInput
restoredAgentLifecycle.registerStartupInput(admittedInput, panelId: panelId)
let admitted = terminal.surface.admitStartupRestoreRuntime(
initialInput: restore.remoteResumeCommandEmbedded ? nil : startupInput
initialInput: admittedInput
)
if !admitted {
restoredAgentLifecycle.clearStartupInput(panelId: panelId)
if let ownedClaim {
AgentResumeLaunchGuard.shared.releaseResumeLaunch(
kind: ownedClaim.kind,
Expand Down Expand Up @@ -788,6 +829,8 @@ extension DockSplitStore {
restore: DeferredAgentResumeRestore,
startRuntime: Bool = true
) {
// A cancelled launch must never have its selector replayed later.
restoredAgentLifecycle.clearStartupInput(panelId: panelId)
if startRuntime {
(panels[panelId] as? TerminalPanel)?.surface.cancelStartupRestoreAdmission()
} else {
Expand Down
5 changes: 5 additions & 0 deletions Sources/DockSplitStore+SessionRestore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,11 @@ extension DockSplitStore {
panelId: terminal.id,
internallySeededInput: initialInput
)
if willRunAgentInput {
// Keep the typed resume selector so the shell-state handler can
// replay it if the login shell drops the typeahead.
restoredAgentLifecycle.registerStartupInput(initialInput, panelId: terminal.id)
}
if let stableSurfaceId = snapshot.stableSurfaceId,
!excludingStableIdentities.contains(stableSurfaceId) {
terminal.adoptStableSurfaceId(stableSurfaceId)
Expand Down
76 changes: 75 additions & 1 deletion Sources/RestoredAgentLifecycleCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ final class RestoredAgentLifecycleCoordinator {

private var completedGenerationsByPanelId: [UUID: RestoredAgentCompletedGeneration] = [:]

/// Startup input a restored launch types into its shell, retained until shell
/// integration reports the command running. Ghostty writes that input as soon
/// as the PTY exists, and a slow login shell can discard the typeahead while it
/// initializes, which leaves the pane at an idle prompt with nothing typed.
/// The owner replays the retained input once when that happens (#5473).
private var pendingStartupInputsByPanelId: [UUID: String] = [:]
private var armedStartupInputResendPanelIds: Set<UUID> = []
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/// Replaces one panel's mutable snapshot while preserving an in-flight restore target.
func setSnapshot(_ snapshot: SessionRestorableAgentSnapshot?, panelId: UUID) {
let resolvedSnapshot: SessionRestorableAgentSnapshot?
Expand Down Expand Up @@ -182,13 +190,70 @@ final class RestoredAgentLifecycleCoordinator {
invalidatedFingerprintsByPanelId.removeValue(forKey: panelId)
}

/// Retains the startup input a restored launch will type into its shell.
/// Passing `nil` or an empty string forgets any earlier registration.
func registerStartupInput(_ input: String?, panelId: UUID) {
armedStartupInputResendPanelIds.remove(panelId)
guard let input, !input.isEmpty else {
pendingStartupInputsByPanelId.removeValue(forKey: panelId)
return
}
pendingStartupInputsByPanelId[panelId] = input
}

/// Forgets retained startup input once the shell ran it, the user took over
/// the pane, or the launch was abandoned.
func clearStartupInput(panelId: UUID) {
pendingStartupInputsByPanelId.removeValue(forKey: panelId)
armedStartupInputResendPanelIds.remove(panelId)
}

/// The retained startup input, so a pane transfer can carry it to the new owner.
func startupInput(panelId: UUID) -> String? {
pendingStartupInputsByPanelId[panelId]
}

/// Whether a restored launch is still waiting for its typed startup input to run.
func awaitsStartupInput(panelId: UUID) -> Bool {
resumeStatesByPanelId[panelId] == .awaitingAutoResumeCommand &&
pendingStartupInputsByPanelId[panelId] != nil
}

/// Arms one grace-period replay for a launch whose shell reported an idle
/// prompt while the launch still awaits its startup input. Returns `false`
/// when nothing is pending or a replay is already armed.
func armStartupInputResend(panelId: UUID) -> Bool {
guard awaitsStartupInput(panelId: panelId),
!armedStartupInputResendPanelIds.contains(panelId) else {
return false
}
armedStartupInputResendPanelIds.insert(panelId)
return true
}

/// Consumes the retained startup input when the shell is still idle after
/// the grace period and the launch never entered its command phase. A
/// prompt-then-command sequence that settled into `.autoResumeCommandRunning`
/// yields `nil`, and only one replay is ever handed out per restored launch.
func takeStartupInputForResend(
panelId: UUID,
shellState: PanelShellActivityState
) -> String? {
armedStartupInputResendPanelIds.remove(panelId)
guard shellState == .promptIdle, awaitsStartupInput(panelId: panelId) else {
return nil
}
return pendingStartupInputsByPanelId.removeValue(forKey: panelId)
}

/// Removes continuation metadata without discarding an invalidation fingerprint.
func clearSessionRestore(panelId: UUID) {
queuedRestoreSnapshotsByPanelId.removeValue(forKey: panelId)
resumeStatesByPanelId.removeValue(forKey: panelId)
snapshotsByPanelId.removeValue(forKey: panelId)
resumeWorkingDirectoriesByPanelId.removeValue(forKey: panelId)
completedGenerationsByPanelId.removeValue(forKey: panelId)
clearStartupInput(panelId: panelId)
}

/// Resets every restored-session lifecycle collection.
Expand All @@ -199,6 +264,8 @@ final class RestoredAgentLifecycleCoordinator {
invalidatedFingerprintsByPanelId.removeAll(keepingCapacity: false)
resumeWorkingDirectoriesByPanelId.removeAll(keepingCapacity: false)
completedGenerationsByPanelId.removeAll(keepingCapacity: false)
pendingStartupInputsByPanelId.removeAll(keepingCapacity: false)
armedStartupInputResendPanelIds.removeAll(keepingCapacity: false)
}

/// Shell integration has observed the restored launch enter its command
Expand Down Expand Up @@ -263,8 +330,15 @@ final class RestoredAgentLifecycleCoordinator {
snapshot: SessionRestorableAgentSnapshot?,
resumeState: Workspace.RestoredAgentResumeState?,
completedGeneration: RestoredAgentCompletedGeneration?,
resumeWorkingDirectory: String?
resumeWorkingDirectory: String?,
startupInput: String? = nil
) {
// A launch still awaiting its typed selector keeps the replay safety
// net across a Workspace/Dock move; any other phase has nothing to replay.
registerStartupInput(
resumeState == .awaitingAutoResumeCommand ? startupInput : nil,
panelId: panelId
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
replaceQueuedRestoreSnapshot(
Self.retainsStartupRestoreIdentity(resumeState) ? snapshot : nil,
panelId: panelId
Expand Down
Loading
Loading