diff --git a/src/main/ipc/pty/ipc/spawn-commit-persist.ts b/src/main/ipc/pty/ipc/spawn-commit-persist.ts index be9cb31394ae..ff7b68396072 100644 --- a/src/main/ipc/pty/ipc/spawn-commit-persist.ts +++ b/src/main/ipc/pty/ipc/spawn-commit-persist.ts @@ -41,16 +41,18 @@ export async function persistPtyIpcSpawnCommit(ctx: PtyIpcSpawnState): Promise<{ daemon: ctx.isDaemonHostSpawn, reattach: ctx.result.isReattach ?? false }) - recordCodexPaneAccountForSpawn({ - ptyId: ctx.result.id, - isDaemonHostSpawn: ctx.isDaemonHostSpawn, - isReattach: ctx.result.isReattach === true, - pinnedByResume: ctx.codexResumeHomeSelected, - launchCodexHomePath: ctx.selectedCodexHomePath, - launchEnv: ctx.baseEnv, - target: ctx.codexSelectionTarget, - settings: ctx.deps.getSettings?.() - }) + if (!ctx.result.agentResumeUnavailable) { + recordCodexPaneAccountForSpawn({ + ptyId: ctx.result.id, + isDaemonHostSpawn: ctx.isDaemonHostSpawn, + isReattach: ctx.result.isReattach === true, + pinnedByResume: ctx.codexResumeHomeSelected, + launchCodexHomePath: ctx.selectedCodexHomePath, + launchEnv: ctx.baseEnv, + target: ctx.codexSelectionTarget, + settings: ctx.deps.getSettings?.() + }) + } ptyOwnership.set(ctx.result.id, args.connectionId ?? null) if (ctx.result.incarnationId) { ptyIncarnationById.set(ctx.result.id, ctx.result.incarnationId) diff --git a/src/main/ipc/pty/ipc/spawn-commit.ts b/src/main/ipc/pty/ipc/spawn-commit.ts index f02eb215c877..0b1b6f0db266 100644 --- a/src/main/ipc/pty/ipc/spawn-commit.ts +++ b/src/main/ipc/pty/ipc/spawn-commit.ts @@ -27,6 +27,7 @@ import { persistPtyIpcSpawnCommit } from './spawn-commit-persist' export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise { const args = ctx.args + const agentResumeDeclined = ctx.result.agentResumeUnavailable === true const { rendererPreSignaled, rendererAlreadyRegistered } = await persistPtyIpcSpawnCommit(ctx) // Why: seed the headless emulator before registerPty so concurrent live PTY data lands on top of the seed, not replacing it (mobile keeps the daemon-restored scrollback). @@ -76,15 +77,17 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise 0 && args.worktreeId.length <= 512 ) { - const agentLaunchAuthority = admitRendererAgentLaunchAuthority({ - launchToken: args.launchToken, - spawnEnv: ctx.spawnEnv, - launchAgent: args.launchAgent, - launchConfig: ctx.effectiveLaunchConfig, - isReattach: ctx.result.isReattach === true, - hasStablePaneOwner: ctx.stablePaneOwner !== null, - incarnationId: ctx.result.incarnationId - }) + const agentLaunchAuthority = agentResumeDeclined + ? null + : admitRendererAgentLaunchAuthority({ + launchToken: args.launchToken, + spawnEnv: ctx.spawnEnv, + launchAgent: args.launchAgent, + launchConfig: ctx.effectiveLaunchConfig, + isReattach: ctx.result.isReattach === true, + hasStablePaneOwner: ctx.stablePaneOwner !== null, + incarnationId: ctx.result.incarnationId + }) const providerReattachLaunchIdentity = admitProviderReattachLaunchIdentity({ isReattach: ctx.result.isReattach === true, launchAgent: ctx.result.launchAgent, @@ -125,13 +128,13 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise { owner: stablePaneOwnerCandidate, worktreeId: args.worktreeId, connectionId: args.connectionId, + paneKey: ctx.reservationPaneKey, resolveOwner: () => resolveStablePaneOwner( ctx.deps.runtime, diff --git a/src/main/ipc/pty/ipc/spawn-options.ts b/src/main/ipc/pty/ipc/spawn-options.ts index ed75b989f6d6..7be95e5b04d2 100644 --- a/src/main/ipc/pty/ipc/spawn-options.ts +++ b/src/main/ipc/pty/ipc/spawn-options.ts @@ -77,6 +77,9 @@ export async function buildPtyIpcSpawnOptions( if (isTuiAgent(args.launchAgent)) { ctx.spawnOptions.launchAgent = args.launchAgent } + if (args.resumeProviderSession !== undefined) { + ctx.spawnOptions.resumeProviderSession = args.resumeProviderSession + } if (args.worktreeId !== undefined) { ctx.spawnOptions.worktreeId = args.worktreeId } diff --git a/src/main/ipc/pty/pane/relay-pty-mint-epoch.ts b/src/main/ipc/pty/pane/relay-pty-mint-epoch.ts new file mode 100644 index 000000000000..569a62a13012 --- /dev/null +++ b/src/main/ipc/pty/pane/relay-pty-mint-epoch.ts @@ -0,0 +1,171 @@ +import type { IPtyProvider, PtySpawnOptions } from '../../../providers/types' +import { parseAppSshPtyId } from '../../../providers/ssh-pty-id' + +const RELAY_STATUS_TIMEOUT_MS = 2_000 +// A missed pane/connection teardown must not retain one tombstone per session. +const MAX_RETIRED_RELAY_OWNERS = 256 +const relayMintEpochByProvider = new WeakMap>() +const retiredRelayOwnerByPane = new Map() + +function retiredRelayOwnerKey(connectionId: string, paneKey: string): string { + return `${connectionId}\0${paneKey}` +} + +function parseRelayPtyMintEpoch(relayPtyId: string): string | undefined { + const match = /^pty2:([^:]+):(\d+)$/.exec(relayPtyId) + if (!match || !Number.isSafeInteger(Number(match[2]))) { + return undefined + } + try { + const epoch = decodeURIComponent(match[1]) + return epoch.length > 0 ? epoch : undefined + } catch { + return undefined + } +} + +function readRelayMintEpoch(provider: IPtyProvider): Promise { + const cached = relayMintEpochByProvider.get(provider) + if (cached) { + return cached + } + const read = provider + .requestHostRpc?.('relay.status', {}, { timeoutMs: RELAY_STATUS_TIMEOUT_MS }) + .then((status) => { + if (!status || typeof status !== 'object') { + return undefined + } + const epoch = (status as { ptyIdMintEpoch?: unknown }).ptyIdMintEpoch + return typeof epoch === 'string' && epoch.length > 0 ? epoch : undefined + }) + .catch(() => undefined) + const result = read ?? Promise.resolve(undefined) + relayMintEpochByProvider.set(provider, result) + return result +} + +export function rememberRetiredRelayEpochOwner(args: { + connectionId: string + paneKey: string | undefined + ownerPtyId: string +}): void { + if (!args.paneKey) { + return + } + const parsed = parseAppSshPtyId(args.ownerPtyId) + if (parsed?.connectionId !== args.connectionId || !parseRelayPtyMintEpoch(parsed.relayPtyId)) { + return + } + const key = retiredRelayOwnerKey(args.connectionId, args.paneKey) + // Delete-then-set so a re-retired pane refreshes recency instead of being evicted first. + retiredRelayOwnerByPane.delete(key) + if (retiredRelayOwnerByPane.size >= MAX_RETIRED_RELAY_OWNERS) { + const oldestKey = retiredRelayOwnerByPane.keys().next().value + if (oldestKey !== undefined) { + retiredRelayOwnerByPane.delete(oldestKey) + } + } + retiredRelayOwnerByPane.set(key, args.ownerPtyId) +} + +export function peekRetiredRelayEpochOwner( + connectionId: string | null | undefined, + paneKey: string | null | undefined +): string | undefined { + if (!connectionId || !paneKey) { + return undefined + } + const key = retiredRelayOwnerKey(connectionId, paneKey) + return retiredRelayOwnerByPane.get(key) +} + +/** Remove a retired owner only after the replacement PTY has been committed. */ +export function consumeRetiredRelayEpochOwner( + connectionId: string | null | undefined, + paneKey: string | null | undefined, + ownerPtyId: string | undefined +): void { + if (!connectionId || !paneKey || !ownerPtyId) { + return + } + const key = retiredRelayOwnerKey(connectionId, paneKey) + if (retiredRelayOwnerByPane.get(key) === ownerPtyId) { + retiredRelayOwnerByPane.delete(key) + } +} + +/** @deprecated Use peek + consume after a successful spawn. */ +export function takeRetiredRelayEpochOwner( + connectionId: string | null | undefined, + paneKey: string | null | undefined +): string | undefined { + const ownerPtyId = peekRetiredRelayEpochOwner(connectionId, paneKey) + consumeRetiredRelayEpochOwner(connectionId, paneKey, ownerPtyId) + return ownerPtyId +} + +export async function compareStablePaneRelayEpoch(args: { + provider: IPtyProvider + ownerPtyId: string + connectionId: string | null | undefined +}): Promise<'same' | 'different' | 'unknown'> { + if (!args.connectionId) { + return 'unknown' + } + const relayPtyId = parseAppSshPtyId(args.ownerPtyId)?.relayPtyId + const ownerEpoch = relayPtyId ? parseRelayPtyMintEpoch(relayPtyId) : undefined + if (!ownerEpoch || !args.provider.requestHostRpc) { + return 'unknown' + } + const currentEpoch = await readRelayMintEpoch(args.provider) + if (!currentEpoch) { + return 'unknown' + } + return currentEpoch === ownerEpoch ? 'same' : 'different' +} + +function stripAgentResumeOptions(options: PtySpawnOptions): PtySpawnOptions { + const stripped = { ...options } + delete stripped.launchAgent + delete stripped.command + delete stripped.commandDelivery + delete stripped.startupCommandDelivery + delete stripped.resumeProviderSession + delete stripped.startupIngress + delete stripped.agentSessionEnsure + delete stripped.agentSessionCreateOperationId + if (stripped.env) { + stripped.env = { ...stripped.env } + delete stripped.env.ORCA_AGENT_LAUNCH_TOKEN + } + stripped.envToDelete = [...new Set([...(stripped.envToDelete ?? []), 'ORCA_AGENT_LAUNCH_TOKEN'])] + return stripped +} + +export async function deriveStablePaneFreshSpawnOptions(args: { + provider: IPtyProvider + ownerPtyId: string | undefined + connectionId: string | null | undefined + spawnOptions: PtySpawnOptions +}): Promise<{ options: PtySpawnOptions; agentResumeDeclined: boolean }> { + const verdict = args.ownerPtyId + ? await compareStablePaneRelayEpoch({ + provider: args.provider, + ownerPtyId: args.ownerPtyId, + connectionId: args.connectionId + }) + : 'unknown' + const hasAgentResumeIntent = Boolean( + args.spawnOptions.launchAgent || + args.spawnOptions.resumeProviderSession || + args.spawnOptions.agentSessionEnsure + ) + // Compatibility: legacy pty-N ids, old relays, RPC failure/timeout, and non-SSH panes are no + // verdict and resume as today. We grandfather them because ordinary absence means the same + // relay lost its PTY; residual risk requires a legacy id, relay replacement, and surviving orphan. + const agentResumeDeclined = verdict === 'different' && hasAgentResumeIntent + return { + options: agentResumeDeclined ? stripAgentResumeOptions(args.spawnOptions) : args.spawnOptions, + agentResumeDeclined + } +} diff --git a/src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts b/src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts new file mode 100644 index 000000000000..608f65c719d9 --- /dev/null +++ b/src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts @@ -0,0 +1,358 @@ +import { describe, expect, it, vi } from 'vitest' +import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../../../providers/types' +import { toAppSshPtyId } from '../../../providers/ssh-pty-id' +import { rememberRetiredRelayEpochOwner, takeRetiredRelayEpochOwner } from './relay-pty-mint-epoch' +import { spawnForStablePane, type StablePaneOwner } from './stable-owner' + +type EpochAwareSpawnOptions = PtySpawnOptions & { resumeProviderSession?: unknown } +type EpochAwareSpawnResult = PtySpawnResult & { agentResumeUnavailable?: true } + +const owner = (relayPtyId: string): StablePaneOwner => ({ + tabId: 'tab-epoch-gate', + leafId: '11111111-1111-4111-8111-111111111111', + ptyId: toAppSshPtyId('remote', relayPtyId) +}) + +const agentSpawnOptions = (): EpochAwareSpawnOptions => ({ + cols: 100, + rows: 30, + cwd: '/workspace', + env: { KEEP: 'yes', ORCA_AGENT_LAUNCH_TOKEN: 'launch-token' }, + envToDelete: ['DELETE_ME'], + command: 'codex resume session', + commandDelivery: 'provider', + startupCommandDelivery: 'shell-ready', + launchAgent: 'codex', + resumeProviderSession: { key: 'session_id', id: 'session' }, + startupIngress: { colors: { foreground: '#ffffff' }, deadlineMs: 5_000 }, + agentSessionEnsure: {} as never, + agentSessionCreateOperationId: 'create-operation' +}) + +function createProvider(status: unknown) { + const spawns: EpochAwareSpawnOptions[] = [] + const requestHostRpc = vi.fn(async () => { + if (status instanceof Error) { + throw status + } + return status + }) + const provider = { + requestHostRpc, + spawn: vi.fn(async (options: EpochAwareSpawnOptions) => { + spawns.push(options) + if (options.attachOnly) { + throw new Error(`PTY "${options.sessionId}" not found`) + } + return { id: toAppSshPtyId('remote', 'pty2:current:2') } + }) + } as unknown as IPtyProvider + return { provider, requestHostRpc, spawns } +} + +async function runSpawn( + relayPtyId: string, + status: unknown, + spawnOptions: EpochAwareSpawnOptions = agentSpawnOptions() +) { + const harness = createProvider(status) + let freshResult: EpochAwareSpawnResult | undefined + const spawned = await spawnForStablePane({ + runtime: undefined, + provider: harness.provider, + spawnOptions, + owner: owner(relayPtyId), + connectionId: 'remote', + onFreshSpawn: (result) => { + freshResult = result as EpochAwareSpawnResult + } + }) + return { + ...harness, + freshOptions: harness.spawns[1], + result: spawned.result as EpochAwareSpawnResult, + freshResult + } +} + +describe('spawnForStablePane relay epoch gate', () => { + it('bounds retired owners when a pane never gets a fresh spawn', () => { + for (let index = 0; index < 300; index += 1) { + rememberRetiredRelayEpochOwner({ + connectionId: `connection-${index}`, + paneKey: `pane-${index}`, + ownerPtyId: `ssh:connection-${index}@@pty2:epoch-${index}:1` + }) + } + + expect(takeRetiredRelayEpochOwner('connection-0', 'pane-0')).toBeUndefined() + expect(takeRetiredRelayEpochOwner('connection-299', 'pane-299')).toBe( + 'ssh:connection-299@@pty2:epoch-299:1' + ) + }) + + it('refreshes eviction recency when the same pane retires again', () => { + for (let index = 0; index < 512; index += 1) { + rememberRetiredRelayEpochOwner({ + connectionId: `refresh-${index}`, + paneKey: `pane-${index}`, + ownerPtyId: `ssh:refresh-${index}@@pty2:epoch-${index}:1` + }) + } + // refresh-256 is now the oldest surviving entry; re-retiring it must move it to newest. + rememberRetiredRelayEpochOwner({ + connectionId: 'refresh-256', + paneKey: 'pane-256', + ownerPtyId: 'ssh:refresh-256@@pty2:epoch-updated:1' + }) + rememberRetiredRelayEpochOwner({ + connectionId: 'refresh-overflow', + paneKey: 'pane-overflow', + ownerPtyId: 'ssh:refresh-overflow@@pty2:epoch-overflow:1' + }) + + expect(takeRetiredRelayEpochOwner('refresh-257', 'pane-257')).toBeUndefined() + expect(takeRetiredRelayEpochOwner('refresh-256', 'pane-256')).toBe( + 'ssh:refresh-256@@pty2:epoch-updated:1' + ) + }) + + it('declines an agent resume owned by a different relay epoch', async () => { + const { freshOptions, result, freshResult, requestHostRpc } = await runSpawn( + 'pty2:previous:1', + { ptyIdMintEpoch: 'current' } + ) + + expect(requestHostRpc).toHaveBeenCalledWith( + 'relay.status', + {}, + expect.objectContaining({ timeoutMs: expect.any(Number) }) + ) + expect(freshOptions).toMatchObject({ + cols: 100, + rows: 30, + cwd: '/workspace', + env: { KEEP: 'yes' }, + envToDelete: expect.arrayContaining(['DELETE_ME', 'ORCA_AGENT_LAUNCH_TOKEN']) + }) + expect(freshOptions).not.toHaveProperty('launchAgent') + expect(freshOptions).not.toHaveProperty('command') + expect(freshOptions).not.toHaveProperty('commandDelivery') + expect(freshOptions).not.toHaveProperty('startupCommandDelivery') + expect(freshOptions).not.toHaveProperty('resumeProviderSession') + expect(freshOptions).not.toHaveProperty('startupIngress') + expect(freshOptions).not.toHaveProperty('agentSessionEnsure') + expect(freshOptions).not.toHaveProperty('agentSessionCreateOperationId') + expect(result.agentResumeUnavailable).toBe(true) + expect(freshResult?.agentResumeUnavailable).toBe(true) + }) + + it('preserves an agent resume owned by the current relay epoch', async () => { + const spawnOptions = agentSpawnOptions() + const { freshOptions, result } = await runSpawn('pty2:current:1', { + ptyIdMintEpoch: 'current' + }) + + expect(freshOptions).toEqual(spawnOptions) + expect(result.agentResumeUnavailable).toBeUndefined() + }) + + it.each([ + ['legacy owner id', 'pty-1', { ptyIdMintEpoch: 'current' }], + ['unknown relay epoch', 'pty2:previous:1', {}], + ['relay status failure', 'pty2:previous:1', new Error('relay unavailable')] + ])('preserves current behavior for %s', async (_label, relayPtyId, status) => { + const spawnOptions = agentSpawnOptions() + const { freshOptions, result } = await runSpawn(relayPtyId, status) + + expect(freshOptions).toEqual(spawnOptions) + expect(result.agentResumeUnavailable).toBeUndefined() + }) + + it('decodes the epoch embedded in an app-facing SSH PTY id', async () => { + const spawnOptions = agentSpawnOptions() + const { freshOptions } = await runSpawn('pty2:relay%3Aepoch:1', { + ptyIdMintEpoch: 'relay:epoch' + }) + + expect(freshOptions).toEqual(spawnOptions) + }) + + it('reads relay status only once per provider connection generation', async () => { + const harness = createProvider({ ptyIdMintEpoch: 'current' }) + const spawn = () => + spawnForStablePane({ + runtime: undefined, + provider: harness.provider, + spawnOptions: agentSpawnOptions(), + owner: owner('pty2:current:1'), + connectionId: 'remote' + }) + + await Promise.all([spawn(), spawn()]) + expect(harness.requestHostRpc).toHaveBeenCalledOnce() + }) + + it('gates a resume after relay recovery retired the stable pane owner', async () => { + const harness = createProvider({ ptyIdMintEpoch: 'current' }) + const paneKey = 'tab-retired-owner:22222222-2222-4222-8222-222222222222' + rememberRetiredRelayEpochOwner({ + connectionId: 'remote', + paneKey, + ownerPtyId: toAppSshPtyId('remote', 'pty2:previous:1') + }) + + const spawned = await spawnForStablePane({ + runtime: undefined, + provider: harness.provider, + spawnOptions: agentSpawnOptions(), + owner: null, + connectionId: 'remote', + paneKey + }) + + expect(harness.requestHostRpc).toHaveBeenCalledOnce() + expect(harness.spawns[0]).not.toHaveProperty('resumeProviderSession') + expect(spawned.result.agentResumeUnavailable).toBe(true) + }) + + it('preserves a resume after same-relay recovery retired the stable pane owner', async () => { + const harness = createProvider({ ptyIdMintEpoch: 'current' }) + const paneKey = 'tab-current-owner:33333333-3333-4333-8333-333333333333' + rememberRetiredRelayEpochOwner({ + connectionId: 'remote', + paneKey, + ownerPtyId: toAppSshPtyId('remote', 'pty2:current:1') + }) + const spawnOptions = agentSpawnOptions() + + await spawnForStablePane({ + runtime: undefined, + provider: harness.provider, + spawnOptions, + owner: null, + connectionId: 'remote', + paneKey + }) + + expect(harness.spawns[0]).toEqual(spawnOptions) + }) + + it('does not let a retired owner gate an unrelated later restore of the same pane', async () => { + const paneKey = 'tab-lifetime:55555555-5555-4555-8555-555555555555' + const retiredPtyId = toAppSshPtyId('remote', 'pty2:previous:1') + const provider = { + requestHostRpc: vi.fn(async () => ({ ptyIdMintEpoch: 'current' })), + spawn: vi.fn(async (options: EpochAwareSpawnOptions) => + options.attachOnly + ? { id: retiredPtyId, isReattach: true } + : { id: toAppSshPtyId('remote', 'pty2:current:2') } + ) + } as unknown as IPtyProvider + rememberRetiredRelayEpochOwner({ + connectionId: 'remote', + paneKey, + ownerPtyId: retiredPtyId + }) + + await spawnForStablePane({ + runtime: undefined, + provider, + spawnOptions: { cols: 80, rows: 24 }, + owner: owner('pty2:previous:1'), + connectionId: 'remote', + paneKey + }) + + const secondOptions = agentSpawnOptions() + await spawnForStablePane({ + runtime: undefined, + provider, + spawnOptions: secondOptions, + owner: null, + connectionId: 'remote', + paneKey + }) + expect(provider.spawn).toHaveBeenLastCalledWith(secondOptions) + }) + + it('retains the retired owner when the first replacement spawn fails', async () => { + const paneKey = 'tab-retry:66666666-6666-4666-8666-666666666666' + const requestHostRpc = vi.fn(async () => ({ ptyIdMintEpoch: 'current' })) + let attempts = 0 + const provider = { + requestHostRpc, + spawn: vi.fn(async (options: EpochAwareSpawnOptions) => { + if (options.attachOnly) { + throw new Error('not found') + } + attempts += 1 + if (attempts === 1) { + throw new Error('relay replacement in progress') + } + return { id: toAppSshPtyId('remote', 'pty2:current:2') } + }) + } as unknown as IPtyProvider + rememberRetiredRelayEpochOwner({ + connectionId: 'remote', + paneKey, + ownerPtyId: toAppSshPtyId('remote', 'pty2:previous:1') + }) + + await expect( + spawnForStablePane({ + runtime: undefined, + provider, + spawnOptions: agentSpawnOptions(), + owner: null, + connectionId: 'remote', + paneKey + }) + ).rejects.toThrow('relay replacement in progress') + + const retried = await spawnForStablePane({ + runtime: undefined, + provider, + spawnOptions: agentSpawnOptions(), + owner: null, + connectionId: 'remote', + paneKey + }) + expect(retried.result.agentResumeUnavailable).toBe(true) + expect(provider.spawn).toHaveBeenCalledTimes(2) + }) + + it('does not treat a new agent launch as a retired-owner resume', async () => { + const harness = createProvider({ ptyIdMintEpoch: 'current' }) + const paneKey = 'tab-new-agent:44444444-4444-4444-8444-444444444444' + rememberRetiredRelayEpochOwner({ + connectionId: 'remote', + paneKey, + ownerPtyId: toAppSshPtyId('remote', 'pty2:previous:1') + }) + const spawnOptions: PtySpawnOptions = { cols: 80, rows: 24, launchAgent: 'claude' } + + await spawnForStablePane({ + runtime: undefined, + provider: harness.provider, + spawnOptions, + owner: null, + connectionId: 'remote', + paneKey + }) + + expect(harness.requestHostRpc).not.toHaveBeenCalled() + expect(harness.spawns[0]).toEqual(spawnOptions) + }) + + it('does not label a plain replacement shell as an unavailable agent resume', async () => { + const { freshOptions, result } = await runSpawn( + 'pty2:previous:1', + { ptyIdMintEpoch: 'current' }, + { cols: 80, rows: 24 } + ) + + expect(freshOptions).toEqual({ cols: 80, rows: 24 }) + expect(result.agentResumeUnavailable).toBeUndefined() + }) +}) diff --git a/src/main/ipc/pty/pane/stable-owner.ts b/src/main/ipc/pty/pane/stable-owner.ts index 9442e914e1f3..0db78e116836 100644 --- a/src/main/ipc/pty/pane/stable-owner.ts +++ b/src/main/ipc/pty/pane/stable-owner.ts @@ -13,6 +13,7 @@ import { import { ptyIncarnationById, ptyOwnership } from '../provider/ownership-state' import { isPtyAlreadyGoneError } from '../provider/liveness' import { clearProviderPtyState } from '../provider/state-cleanup' +import * as relayEpoch from './relay-pty-mint-epoch' export type StablePaneOwner = { handle?: string @@ -164,6 +165,7 @@ export type StablePaneSpawnContext = { owner: StablePaneOwner | null worktreeId?: string connectionId?: string | null + paneKey?: string | null resolveOwner?: () => StablePaneOwner | null onFreshSpawn?: (result: PtySpawnResult) => void } @@ -287,7 +289,25 @@ export async function spawnForStablePane( return attached } } - const result = await args.provider.spawn(args.spawnOptions) + const retiredRelayOwnerPtyId = relayEpoch.peekRetiredRelayEpochOwner( + args.connectionId, + args.paneKey + ) + const freshSpawn = await relayEpoch.deriveStablePaneFreshSpawnOptions({ + provider: args.provider, + ownerPtyId: + args.owner?.ptyId ?? + (args.spawnOptions.resumeProviderSession || args.spawnOptions.agentSessionEnsure + ? retiredRelayOwnerPtyId + : undefined), + connectionId: args.connectionId, + spawnOptions: args.spawnOptions + }) + const providerResult = await args.provider.spawn(freshSpawn.options) + relayEpoch.consumeRetiredRelayEpochOwner(args.connectionId, args.paneKey, retiredRelayOwnerPtyId) + const result = freshSpawn.agentResumeDeclined + ? { ...providerResult, agentResumeUnavailable: true as const } + : providerResult args.onFreshSpawn?.(result) return { result, owner: null } } diff --git a/src/main/ipc/pty/runtime/spawn-commit.ts b/src/main/ipc/pty/runtime/spawn-commit.ts index 0b4e8804ac04..bf0986586f27 100644 --- a/src/main/ipc/pty/runtime/spawn-commit.ts +++ b/src/main/ipc/pty/runtime/spawn-commit.ts @@ -38,6 +38,7 @@ import type { RuntimePtySpawnState } from './spawn-state' export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { const args = ctx.args + const agentResumeDeclined = ctx.result.agentResumeUnavailable === true const providerReattachLaunchIdentity = admitProviderReattachLaunchIdentity(ctx.result) try { ctx.stablePaneBindingPersisted = persistAdmittedStablePaneBinding({ @@ -138,16 +139,18 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { if (ctx.effectiveSessionAppId !== undefined && ctx.effectiveSessionAppId !== ctx.result.id) { ptySizes.delete(ctx.effectiveSessionAppId) } - recordCodexPaneAccountForSpawn({ - ptyId: ctx.result.id, - isDaemonHostSpawn: ctx.isDaemonHostSpawn, - isReattach: ctx.result.isReattach === true, - pinnedByResume: ctx.codexResumeHomeSelected, - launchCodexHomePath: ctx.selectedCodexHomePath, - launchEnv: args.env, - target: ctx.codexSelectionTarget, - settings: ctx.deps.getSettings?.() - }) + if (!agentResumeDeclined) { + recordCodexPaneAccountForSpawn({ + ptyId: ctx.result.id, + isDaemonHostSpawn: ctx.isDaemonHostSpawn, + isReattach: ctx.result.isReattach === true, + pinnedByResume: ctx.codexResumeHomeSelected, + launchCodexHomePath: ctx.selectedCodexHomePath, + launchEnv: args.env, + target: ctx.codexSelectionTarget, + settings: ctx.deps.getSettings?.() + }) + } if (ctx.hostSessionBinding && !ctx.stablePaneBindingPersisted) { try { const binding = { @@ -223,13 +226,13 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { // Why: runtime-controller creates (headless serve, CLI, splits) adopt surviving daemon sessions too; without this seed their records stay blank. seedTerminalRestoreRecordsFromSpawnResult(ctx.deps.runtime, ctx.result) // Why: arms main's per-PTY Command Code output detector from the launch command (renderer startupCommand parity). - if (!ctx.stablePaneOwner) { + if (!ctx.stablePaneOwner && !agentResumeDeclined) { ctx.deps.runtime?.noteTerminalSpawnCommand?.(ctx.result.id, ctx.launchCommand ?? null) } - if (ctx.isClaudeLaunch && !ctx.stablePaneOwner) { + if (ctx.isClaudeLaunch && !ctx.stablePaneOwner && !agentResumeDeclined) { markClaudePtySpawned(ctx.result.id) } - if (args.telemetry && !ctx.stablePaneOwner) { + if (args.telemetry && !ctx.stablePaneOwner && !agentResumeDeclined) { const agentKindParse = agentKindSchema.safeParse(args.telemetry.agent_kind) const launchSourceParse = launchSourceSchema.safeParse(args.telemetry.launch_source) const requestKindParse = requestKindSchema.safeParse(args.telemetry.request_kind) @@ -267,7 +270,7 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { } // Why: runtime-owned/background spawns bypass mounted-pane state, so inventory consumers need an explicit signal. ctx.deps.sendPtySpawnedToRenderer(ctx.result.id) - if (!args.connectionId) { + if (!args.connectionId && !agentResumeDeclined) { ctx.deps.options?.onCodexHomePtySpawned?.({ id: ctx.result.id, codexHomePath: ctx.selectedCodexHomePath, @@ -286,8 +289,7 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { }) } const response = { - id: ctx.result.id, - ...(ctx.result.incarnationId ? { incarnationId: ctx.result.incarnationId } : {}), + ...ctx.result, ...(ctx.stablePaneOwner && (ctx.stablePaneOwner.handle || args.preAllocatedHandle) ? { stablePaneOwner: { @@ -296,8 +298,7 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) { leafId: ctx.stablePaneOwner.leafId } } - : {}), - ...(ctx.result.agentSessionEnsure ? { agentSessionEnsure: ctx.result.agentSessionEnsure } : {}) + : {}) } resolvePaneSpawnReservation(ctx.paneSpawnReservationKey, ctx.paneSpawnReservation, { ...ctx.result, diff --git a/src/main/ipc/pty/runtime/spawn-execute.ts b/src/main/ipc/pty/runtime/spawn-execute.ts index 99829f119bbc..b2d4fc1ab716 100644 --- a/src/main/ipc/pty/runtime/spawn-execute.ts +++ b/src/main/ipc/pty/runtime/spawn-execute.ts @@ -136,6 +136,7 @@ export async function executeRuntimePtySpawn(ctx: RuntimePtySpawnState): Promise owner: stablePaneOwnerCandidate, worktreeId: args.worktreeId, connectionId: args.connectionId, + paneKey: ctx.spawnIdentityPaneKey, resolveOwner: () => resolveStablePaneOwner( ctx.deps.runtime, diff --git a/src/main/ipc/pty/runtime/spawn-options.ts b/src/main/ipc/pty/runtime/spawn-options.ts index fcba7770a392..c30fdb7747fa 100644 --- a/src/main/ipc/pty/runtime/spawn-options.ts +++ b/src/main/ipc/pty/runtime/spawn-options.ts @@ -101,6 +101,9 @@ export async function buildRuntimePtySpawnOptions( if (isTuiAgent(args.launchAgent)) { ctx.spawnOptions.launchAgent = args.launchAgent } + if (args.resumeProviderSession !== undefined) { + ctx.spawnOptions.resumeProviderSession = args.resumeProviderSession + } if (args.worktreeId !== undefined) { ctx.spawnOptions.worktreeId = args.worktreeId } diff --git a/src/main/ipc/pty/runtime/spawn.ts b/src/main/ipc/pty/runtime/spawn.ts index 2af050cd7963..f93abf49fb00 100644 --- a/src/main/ipc/pty/runtime/spawn.ts +++ b/src/main/ipc/pty/runtime/spawn.ts @@ -23,13 +23,15 @@ function toRuntimeSpawnReply(result: { wslDistro?: string | null stablePaneOwner?: { handle: string; tabId: string; leafId: string } agentSessionEnsure?: AgentSessionClaimedSpawnResult + agentResumeUnavailable?: true }) { return { id: result.id, ...(result.incarnationId ? { incarnationId: result.incarnationId } : {}), ...(typeof result.wslDistro === 'string' ? { wslDistro: result.wslDistro } : {}), ...(result.stablePaneOwner ? { stablePaneOwner: result.stablePaneOwner } : {}), - ...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}) + ...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}), + ...(result.agentResumeUnavailable ? { agentResumeUnavailable: true as const } : {}) } } diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts index 35fca5b0b34a..96c58ee46fc9 100644 --- a/src/main/providers/pty-provider-contract.ts +++ b/src/main/providers/pty-provider-contract.ts @@ -12,6 +12,7 @@ import type { import type { PtyProcessInfo } from './pty-process-info' import type { TerminalExitCause } from '../../shared/terminal-exit-cause' import type { TerminalOwner } from '../../shared/terminal-owner' +import type { AgentProviderSessionMetadata } from '../../shared/agent-session-resume' export type { PtyBackgroundStreamEvent, @@ -57,6 +58,8 @@ export type PtySpawnOptions = { startupCommandDelivery?: StartupCommandDelivery /** Minimal allowlisted launch ownership preserved by daemon reattach. */ launchAgent?: TuiAgent + /** Main-only resume intent retained until stable-pane recovery chooses the answering relay. */ + resumeProviderSession?: AgentProviderSessionMetadata /** Orca worktree identity. When present, the local provider scopes shell * history to this worktree so ArrowUp only surfaces local commands. */ worktreeId?: string diff --git a/src/main/providers/pty-spawn-result.ts b/src/main/providers/pty-spawn-result.ts index 43e9665de459..6dbcddc19726 100644 --- a/src/main/providers/pty-spawn-result.ts +++ b/src/main/providers/pty-spawn-result.ts @@ -7,6 +7,8 @@ import type { TerminalOwner } from '../../shared/terminal-owner' export type PtySpawnResult = { agentSessionEnsure?: AgentSessionClaimedSpawnResult + /** Main declined an agent resume owned by a different relay incarnation. */ + agentResumeUnavailable?: true /** App-facing PTY id. Remote providers must return globally routable ids, * not relay-local handles, because renderer/runtime IPC routes by this key. */ id: string diff --git a/src/main/runtime/orca-runtime-create-terminal.ts b/src/main/runtime/orca-runtime-create-terminal.ts index ec8a3e789416..692aaa018559 100644 --- a/src/main/runtime/orca-runtime-create-terminal.ts +++ b/src/main/runtime/orca-runtime-create-terminal.ts @@ -203,6 +203,7 @@ export class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTerminalCreate if (result.wslDistro) { this.preparePtyExecutionContext(result.id, result.wslDistro) } + const agentResumeDeclined = result.agentResumeUnavailable === true this.registerPty(result.id, workspace.id, workspace.connectionId, { tabId, leafId, @@ -228,12 +229,10 @@ export class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTerminalCreate pty.title = null pty.titleUpdatedAt = null } - pty.launchConfig = effectiveLaunchConfig - ? dependencies.copySleepingAgentLaunchConfig(effectiveLaunchConfig) - : null - pty.launchToken = launchToken ?? null - pty.launchIncarnationId = launchToken ? pty.incarnationId : null - pty.launchAgent = launchOpts.launchAgent ?? null + pty.launchConfig = !agentResumeDeclined && effectiveLaunchConfig ? dependencies.copySleepingAgentLaunchConfig(effectiveLaunchConfig) : null + pty.launchToken = agentResumeDeclined ? null : (launchToken ?? null) + pty.launchIncarnationId = !agentResumeDeclined && launchToken ? pty.incarnationId : null + pty.launchAgent = agentResumeDeclined ? null : (launchOpts.launchAgent ?? null) } pty.tabId = tabId pty.paneKey = paneKey @@ -258,9 +257,9 @@ export class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTerminalCreate ptyId: result.id, title: launchOpts.title ?? null, ...(cwd !== workspace.path ? { cwd } : {}), - ...(effectiveLaunchConfig ? { launchConfig: effectiveLaunchConfig } : {}), - ...(launchToken ? { launchToken } : {}), - ...(launchOpts.launchAgent ? { launchAgent: launchOpts.launchAgent } : {}), + ...(!agentResumeDeclined && effectiveLaunchConfig ? { launchConfig: effectiveLaunchConfig } : {}), + ...(!agentResumeDeclined && launchToken ? { launchToken } : {}), + ...(!agentResumeDeclined && launchOpts.launchAgent ? { launchAgent: launchOpts.launchAgent } : {}), ...(launchOpts.viewMode ? { viewMode: launchOpts.viewMode } : {}), activate: presentation === 'focused', ...(presentation ? { presentation } : {}), @@ -289,6 +288,7 @@ export class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTerminalCreate ...(result.agentSessionEnsure ? { agentSessionDisposition: result.agentSessionEnsure.disposition } : {}), + ...(agentResumeDeclined ? { agentResumeUnavailable: true as const } : {}), ...(adoptedStablePane ? { isReattach: true as const } : {}), ...(warning ? { warning } : {}) } diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index 2b17787f67d1..35b92436d7c2 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -85,6 +85,7 @@ export type RuntimePtyController = { wslDistro?: string stablePaneOwner?: { handle: string; tabId: string; leafId: string } agentSessionEnsure?: AgentSessionClaimedSpawnResult + agentResumeUnavailable?: true }> write(ptyId: string, data: string): boolean writeAgentSessionProof?( diff --git a/src/main/ssh/ssh-relay-session.test.ts b/src/main/ssh/ssh-relay-session.test.ts index 570fca21fd4a..58c98486dca1 100644 --- a/src/main/ssh/ssh-relay-session.test.ts +++ b/src/main/ssh/ssh-relay-session.test.ts @@ -6,6 +6,7 @@ import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-relay' import { SSH_RELAY_CONFIGURE_GRACE_TIME_METHOD } from '../../shared/ssh-types' +import { takeRetiredRelayEpochOwner } from '../ipc/pty/pane/relay-pty-mint-epoch' import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures' const { acceptOutputDataMock, muxRequestMock, openConsumerSessionMock, pauseAdapterMock } = @@ -679,26 +680,45 @@ describe('SshRelaySession', () => { mockDeploySuccess() const { getSshPtyProvider } = await import('../ipc/pty') + const stalePtyId = 'pty2:previous-epoch:7' + const staleLeafId = '55555555-5555-4555-8555-555555555555' + const stalePaneKey = `tab-stale:${staleLeafId}` const mockAttach = vi .fn() - .mockRejectedValueOnce(new Error('PTY "pty-stale" not found')) - .mockResolvedValueOnce(undefined) + .mockImplementation((ptyId: string) => + ptyId === stalePtyId + ? Promise.reject(new Error(`PTY "${stalePtyId}" not found`)) + : Promise.resolve(undefined) + ) vi.mocked(getSshPtyProvider).mockReturnValue({ attachForReconnect: mockAttach, dispose: vi.fn() } as unknown as ReturnType) - vi.mocked(getPtyIdsForConnection).mockReturnValue(['pty-stale', 'pty-live']) + vi.mocked(getPtyIdsForConnection).mockReturnValue(['pty-live']) + vi.mocked(mockStore.getSshRemotePtyLeases).mockReturnValue([ + { + targetId: 'target-1', + ptyId: stalePtyId, + state: 'detached', + tabId: 'tab-stale', + leafId: staleLeafId + } + ] as ReturnType) await session.reconnect(mockConn) - expect(mockAttach).toHaveBeenCalledWith('pty-stale') + expect(mockAttach).toHaveBeenCalledWith(stalePtyId, { + paneKey: stalePaneKey, + tabId: 'tab-stale' + }) expect(mockAttach).toHaveBeenCalledWith('pty-live') - expect(clearProviderPtyState).toHaveBeenCalledWith('ssh:target-1@@pty-stale') - expect(deletePtyOwnership).toHaveBeenCalledWith('ssh:target-1@@pty-stale') + expect(clearProviderPtyState).toHaveBeenCalledWith(`ssh:target-1@@${stalePtyId}`) + expect(deletePtyOwnership).toHaveBeenCalledWith(`ssh:target-1@@${stalePtyId}`) expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:exit', { - id: 'ssh:target-1@@pty-stale', + id: `ssh:target-1@@${stalePtyId}`, code: -1 }) + expect(takeRetiredRelayEpochOwner('target-1', stalePaneKey)).toBe(`ssh:target-1@@${stalePtyId}`) }) it('retries transient reattach failure without tearing down provider registration', async () => { diff --git a/src/main/ssh/ssh-relay-session.ts b/src/main/ssh/ssh-relay-session.ts index bdc7c4370f20..126f8da706cb 100644 --- a/src/main/ssh/ssh-relay-session.ts +++ b/src/main/ssh/ssh-relay-session.ts @@ -56,6 +56,7 @@ import { installSshPtySourceAckPublisher, installSshPtySourceCancellationPublisher } from '../ipc/ssh-pty-output-intake-registry' +import { rememberRetiredRelayEpochOwner } from '../ipc/pty/pane/relay-pty-mint-epoch' import { registerSshFilesystemProvider, unregisterSshFilesystemProvider, @@ -184,6 +185,7 @@ type PendingPtyReattach = { recoveryWaiters: Set<() => void> livePassthrough: boolean activated: boolean + paneKey?: string } type RemoteCliBridgeEnv = { @@ -2359,6 +2361,7 @@ export class SshRelaySession { targetedDeliveryRecovery } = args const appPtyId = toAppSshPtyId(this.targetId, ptyId) + const expectedIdentity = expectedIdentityByPtyId.get(ptyId) const pendingReattach: PendingPtyReattach = { mux, providerGeneration, @@ -2369,7 +2372,8 @@ export class SshRelaySession { liveData: [], recoveryWaiters: new Set(), livePassthrough: false, - activated: false + activated: false, + ...(expectedIdentity?.paneKey ? { paneKey: expectedIdentity.paneKey } : {}) } this.pendingPtyReattaches.set(appPtyId, pendingReattach) let sourceActivationLease: SshPtyAttachResult['sourceActivationLease'] @@ -2382,7 +2386,7 @@ export class SshRelaySession { const attachResult = await this.attachPtyWithRetry( ptyProvider, ptyId, - expectedIdentityByPtyId.get(ptyId), + expectedIdentity, recoveryRequest, shouldContinue ) @@ -2828,6 +2832,11 @@ export class SshRelaySession { error instanceof Error ? error.message : String(error) }` ) + rememberRetiredRelayEpochOwner({ + connectionId: this.targetId, + paneKey: pending.paneKey, + ownerPtyId: appPtyId + }) clearProviderPtyState(appPtyId) deletePtyOwnership(appPtyId) this.store.markSshRemotePtyLease(this.targetId, ptyId, 'expired') diff --git a/src/relay/pty-handler.ts b/src/relay/pty-handler.ts index 82f0b19b9ff3..4587bfb529dc 100644 --- a/src/relay/pty-handler.ts +++ b/src/relay/pty-handler.ts @@ -501,6 +501,10 @@ export class PtyHandler { this.dispatcher.onLegacyPtyCapacity?.(() => this.handleLegacyCapacity()) ?? null } + get mintEpoch(): string { + return this.ptyIdMintEpoch + } + setConsumerDeliveryPaused(id: string, paused: boolean): void { if (paused) { this.consumerPausedOutputPtys.add(id) diff --git a/src/relay/relay-daemon.ts b/src/relay/relay-daemon.ts index 3200dbb0ddb5..bbf90826feac 100644 --- a/src/relay/relay-daemon.ts +++ b/src/relay/relay-daemon.ts @@ -138,6 +138,7 @@ function registerRelayStatus( ): void { primaryChannel.dispatcher.onRequest('relay.status', async () => ({ capabilities: SKILL_RELAY_CAPABILITIES, + ptyIdMintEpoch: runtime.ptyHandler.mintEpoch, pid: process.pid, uptimeMs: Date.now() - startedAt, detached: options.detached, diff --git a/src/relay/subprocess.test.ts b/src/relay/subprocess.test.ts index 0c7eea107656..6fbd96b57af4 100644 --- a/src/relay/subprocess.test.ts +++ b/src/relay/subprocess.test.ts @@ -770,11 +770,13 @@ describe('Subprocess: Relay entry point', () => { expect(resp.error).toBeUndefined() const status = resp.result as { pid: number + ptyIdMintEpoch?: string memory: { rss: number } ptys: { active: number } socket: { owned: boolean; listening: boolean; clients: number } } expect(status.pid).toBeGreaterThan(0) + expect(status.ptyIdMintEpoch).toEqual(expect.any(String)) expect(status.memory.rss).toBeGreaterThan(0) expect(status.ptys.active).toBe(0) expect(status.socket).toMatchObject({ owned: true, listening: true, clients: 0 }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts index 35b37855238b..b98816e0cea1 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-cold-restore-agent-resume.test.ts @@ -457,6 +457,9 @@ describe('connectPanePty', () => { expect(deps.onShowSessionRestoredBanner).toHaveBeenCalledTimes(1) expect(deps.onShowSessionRestoredBanner).toHaveBeenCalledWith(1, 'resume-unavailable') + expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(paneKey) + expect(mockStoreState.clearPaneForegroundAgent).toHaveBeenCalledWith(paneKey) + expect(transport.sendInput).not.toHaveBeenCalled() }) it('resumes from an unambiguous legacy sleeping record when cold-restoring a preserved pane', async () => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts b/src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts index cb0806900afe..15c3ecce5807 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts @@ -19,6 +19,7 @@ import { resolveSshReconnectModelPaint } from './resolve-ssh-reconnect-model-pai import type { ReattachPayloadContext } from './reattach-payload-context' import type { ReattachPayloadSession } from './reattach-payload-session' +import { cancelDeclinedAgentResume } from './declined-agent-resume' export function createReattachPayloadHandlers( session: ReattachPayloadSession, @@ -279,6 +280,7 @@ export function createReattachPayloadHandlers( const didPrepareResume = session.applyColdRestoreAgentResumeStartup(preparedStartup) if (didPrepareResume) { if (ctx.connectResult.agentResumeUnavailable) { + cancelDeclinedAgentResume(session) // Why: main dropped the resume argv, so this pane is a NEW session — // the plain restored banner would claim the old one came back. session.showSessionRestoredBanner('resume-unavailable') @@ -297,7 +299,11 @@ export function createReattachPayloadHandlers( if (!isRemoteRuntimePtyId(ctx.ptyId)) { window.api.pty.ackColdRestore(ctx.ptyId) } - if (didPrepareResume && !ctx.coldRestoreStartup) { + if ( + didPrepareResume && + !ctx.coldRestoreStartup && + !ctx.connectResult.agentResumeUnavailable + ) { session.schedulePendingStartupCommandDelivery() } } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts index c6a25e0d4618..9691ae4f241e 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty-session.ts @@ -7,6 +7,11 @@ export type ConnectPanePtySession = { pane: ManagedPane manager: PaneManager deps: PtyConnectionDeps + cacheKey: string + pendingStartupCommand: { command: string } | null + startupInjectTimer: ReturnType | null + cancelStartupDraftPasteDelivery: () => void + clearRegisteredStartupLaunchConfig: () => void // oxlint-disable-next-line typescript/no-explicit-any -- session bag for mechanical extract [key: string]: any } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts index 2b55854c6761..21537e39d737 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts @@ -114,6 +114,7 @@ export function connectPanePty( session.cleanupHiddenOutputRestoreFloodRepaint = (): void => {} session.resetRendererOrderedSeqForPtyExit = () => {} session.cleanupStartupDraftPasteTimers = (): void => {} + session.cancelStartupDraftPasteDelivery = (): void => {} session.unregisterE2ePtyDataInjection = (): void => {} session.startupInjectTimer = null session.agentTaskCompleteNotificationGraceTimer = null diff --git a/src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts b/src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts new file mode 100644 index 000000000000..817525023cc7 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/declined-agent-resume.ts @@ -0,0 +1,22 @@ +import { useAppStore } from '@/store' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +type DeclinedAgentResumeSession = Pick< + ConnectPanePtySession, + | 'cacheKey' + | 'cancelStartupDraftPasteDelivery' + | 'clearRegisteredStartupLaunchConfig' + | 'pendingStartupCommand' + | 'startupInjectTimer' +> + +export function cancelDeclinedAgentResume(session: DeclinedAgentResumeSession): void { + session.pendingStartupCommand = null + if (session.startupInjectTimer !== null) { + clearTimeout(session.startupInjectTimer) + session.startupInjectTimer = null + } + session.cancelStartupDraftPasteDelivery() + session.clearRegisteredStartupLaunchConfig() + useAppStore.getState().clearPaneForegroundAgent(session.cacheKey) +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts index 2e0ebc74cb9e..088635c14225 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts @@ -15,6 +15,7 @@ import type { import type { ConnectPanePtySession } from './connect-pane-pty-session' import { resolveTerminalTabId } from './terminal-tab-id' +import { cancelDeclinedAgentResume } from './declined-agent-resume' export function bindStartFreshSpawn(session: ConnectPanePtySession): void { session.startFreshSpawn = ( @@ -209,7 +210,15 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { } return accepted ? resolvedPtyId : null } - if (spawnedPtyId && typeof spawnedPtyId === 'object' && 'id' in spawnedPtyId) { + const agentResumeUnavailable = Boolean( + spawnedPtyId && + typeof spawnedPtyId === 'object' && + 'id' in spawnedPtyId && + spawnedPtyId.agentResumeUnavailable + ) + if (agentResumeUnavailable) { + cancelDeclinedAgentResume(session) + } else if (spawnedPtyId && typeof spawnedPtyId === 'object' && 'id' in spawnedPtyId) { session.registerEffectiveLaunchConfig(spawnedPtyId.launchConfig, { ...(coldRestoreOverride ? { launchToken: coldRestoreOverride.launchToken } : {}), ...(coldRestoreOverride ? { launchAgent: coldRestoreOverride.agent } : {}) @@ -225,11 +234,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { foreground: shouldWritePtyOutputForeground(session.deps.isVisibleRef.current) }) } - if ( - spawnedPtyId && - typeof spawnedPtyId === 'object' && - spawnedPtyId.agentResumeUnavailable - ) { + if (spawnedPtyId && typeof spawnedPtyId === 'object' && agentResumeUnavailable) { // Why: main dropped the resume argv, so this pane is a NEW session — // the plain restored banner would claim the old one came back. session.showSessionRestoredBanner('resume-unavailable') @@ -281,7 +286,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { void window.api.pty.settlePaneSerializer(session.cacheKey, gen).catch(() => {}) } } - if (resolvedPtyId && session.connectionId) { + if (resolvedPtyId && session.connectionId && !agentResumeUnavailable) { if ( session.shouldUseProviderSshStartupDelivery && (startupOverride?.command || session.paneStartup?.command) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts b/src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts index 9ca1202e9b1b..4142d244907c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pane-serializer-settle.ts @@ -88,6 +88,11 @@ export function bindSettlePaneSerializer(session: ConnectPanePtySession): void { } } session.cleanupStartupDraftPasteTimers = clearStartupDraftPasteTimers + session.cancelStartupDraftPasteDelivery = (): void => { + startupDraftPasteSettled = true + clearStartupDraftPasteTimers() + session.releaseUnattemptedStartupDraftPasteDelivery() + } const getStartupDraftPtyId = (): string | null => { const ptyId = session.transport.getPtyId() if ( diff --git a/src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts b/src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts index 6bd4d78886d9..bbec4e8d30cb 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-session.ts @@ -5,12 +5,16 @@ export type ReattachPayloadSession = Pick< | 'applyColdRestoreAgentResumeStartup' | 'applySnapshotKittyKeyboardModes' | 'buildColdRestoreAgentResumeStartup' + | 'cacheKey' + | 'cancelStartupDraftPasteDelivery' + | 'clearRegisteredStartupLaunchConfig' | 'clearSleepingRecordAfterColdRestoreSpawn' | 'consumeRestoredViewportBlankingMarker' | 'createReattachGridPush' | 'isPaneOnAlternateScreen' | 'kittyKeyboardModes' | 'pane' + | 'pendingStartupCommand' | 'pendingReattachFit' | 'reattachReplayResetSequence' | 'recordRendererOrderedSeq' @@ -21,6 +25,7 @@ export type ReattachPayloadSession = Pick< | 'shouldPreserveAgentReattachModes' | 'showSessionRestoredBanner' | 'suppressStructuralReplayPtyResize' + | 'startupInjectTimer' | 'transport' | 'writeFreshShellViewportBlanking' | 'writeReplayData' diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index 62c3ebee134a..bd59ba4ee92e 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -2289,7 +2289,10 @@ export function createRemoteRuntimePtyTransport( return { id: remotePtyId, replay: '', - ...(createdTerminal.isReattach === true ? { isReattach: true } : {}) + ...(createdTerminal.isReattach === true ? { isReattach: true } : {}), + ...(createdTerminal.agentResumeUnavailable + ? { agentResumeUnavailable: true as const } + : {}) } satisfies PtyConnectResult } catch (error) { if (!destroyed && lifecycleEpoch === connectLifecycleEpoch) { diff --git a/src/shared/runtime-terminal-contracts.ts b/src/shared/runtime-terminal-contracts.ts index 16a16acf6139..099a9c36ab9a 100644 --- a/src/shared/runtime-terminal-contracts.ts +++ b/src/shared/runtime-terminal-contracts.ts @@ -260,6 +260,7 @@ export type RuntimeTerminalCreate = { surface?: 'background' | 'visible' warning?: string agentSessionDisposition?: 'created' | 'adopted' + agentResumeUnavailable?: true isReattach?: true /** Spawn process identity for host-internal ownership proof. */ processId?: number diff --git a/sta5698-epoch-gate-plan.md b/sta5698-epoch-gate-plan.md new file mode 100644 index 000000000000..ac4c476a0a41 --- /dev/null +++ b/sta5698-epoch-gate-plan.md @@ -0,0 +1,47 @@ +# STA-5698 relay epoch gate lifetime fix + +## Diagnosis to verify + +The runtime failures share the retired-owner side table's identity/lifetime bug. A +`(connectionId, paneKey)` tombstone is consumed by whichever later spawn happens to +use that pane, so a later same-relay restore can compare against an unrelated old +epoch. Conversely, a failed fresh spawn consumes the only tombstone before a relay +replacement retries the same absence, making that retry `unknown` and allowing the +resume. + +## Design + +The first proposal to key by `effectiveSessionAppId` is rejected: fresh resume paths +intentionally omit `sessionId`, so that value cannot identify the absence. The fix is +scoped to direct IPC/SSH paths that reproduce STA-5698; paired-runtime methods and +stream opcodes remain unchanged. Relay retirement (including the synthetic +`webContents.send('pty:exit', {id, code:-1})` in +`ssh-relay-session.handlePtyReattachFailure`) records `{connectionId,paneKey,ownerPtyId}` +in the bounded main-process map. No renderer wire shape changes: this map is consulted +only by the main process when a fresh IPC/SSH spawn already carries the pane key. + +Presentation is transactional: lookup peeks the retired owner, and the entry is removed +only after provider spawn succeeds (including a successful rebind or shell replacement). +A provider rejection leaves the entry for the next relay incarnation retry; a later +restore after successful rebind cannot see it. A restore with no entry remains `unknown`; +known-different still declines agent resume and known-same still resumes. Concurrent +lookups are serialized by the spawn path, and the map remains bounded at 256 with +recency refresh. + +## Tests and verification + +Add red-before-fix tests in stable-owner and SSH relay suites: synthetic relay exit records +the exact owner; first provider rejection leaves that owner for a successful retry; success +removes it and blocks replay; an attach/rebind followed by an unrelated restore of the same +pane is unknown; same-epoch, legacy/no-entry, and concurrent presentation controls remain +unchanged. Run focused tests, typecheck, oxlint/format, relay build, then both runtime +scenarios in separate and back-to-back app sessions against `openclaw`. + +## OSS precedent + +The synced desktop terminal manager keeps killed-session tombstones separate from +live-resource maps, bounds them, refreshes recency on re-record, and consumes them on +matching reuse. It clears the tombstone before create and does not roll it back on +create failure; rollback-on-provider-failure is an Orca requirement demonstrated by +STA-5698, not OSS precedent. This change borrows only separation, bounding, recency, +and explicit reuse. diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/report.md b/validation-artifacts/sta5698-task01-final-20260829T010120Z/report.md new file mode 100644 index 000000000000..752be209fad4 --- /dev/null +++ b/validation-artifacts/sta5698-task01-final-20260829T010120Z/report.md @@ -0,0 +1,132 @@ +# STA-5698 relay epoch gate diagnosis, fix, and revalidation + +## Verdict + +Both required openclaw end-to-end scenarios pass after the fix. + +- **Relay replaced / known-different epoch:** PASS. Orca declined the persisted agent resume, launched the stub exactly once without `--resume`, displayed `--- previous session unavailable, started fresh ---`, and left a working shell. +- **Relay alive / same epoch:** PASS. Orca relaunched the agent with `--resume sta5698-session-diag-task01` and displayed `--- session restored ---`. + +## Proven root cause + +The epoch read did not time out and was not cached as `undefined`. The relay recovery path positively determined that the old PTY was absent, then removed the stable owner from ownership state before the renderer requested its cold agent resume. `spawnForStablePane` did execute, but its `owner` argument was `null`; the previous implementation only called `deriveStablePaneFreshSpawnOptions` when an owner remained, so the epoch gate never requested `relay.status` and the resume passed through unchanged. + +Temporary instrumentation captured the following sequence before any production change: + +1. The old relay PTY was reported absent during reconnect and its stable owner was cleared. +2. The renderer initiated `startFreshColdRestoreAgentResume`. +3. The request reached `spawnForStablePane` with no owner PTY ID. +4. The fresh spawn retained the resume identity and launched Claude with `--resume`. + +The instrumentation also called the deployed relay's raw `relay.status` method. Its reply contained: + +```json +{ "ptyIdMintEpoch": "e865b114-0e7c-4ff1-93a9-3a13952800b4" } +``` + +This establishes that the deployed relay published the field and that the gate was skipped before any timeout/cache behavior could matter. + +## Ranked hypotheses + +- **H1 eliminated:** `requestHostRpc('relay.status')` was called zero times in the failing path. The read did not fail or time out, so the existing positive/negative promise cache was not causal. +- **H2 eliminated:** the raw deployed `relay.status` reply included `ptyIdMintEpoch` as shown above. +- **H3 refined, not causal:** the renderer did initiate `startFreshColdRestoreAgentResume`, but that request still passed through `spawnForStablePane`; this was not a bypass spawn site. +- **H4 eliminated:** the owner did not carry the replacement relay's epoch. It had already been removed, so the comparison was skipped rather than comparing new against new. + +## Fix + +Relay recovery now records the old, epoch-bearing owner by SSH connection and pane key immediately before clearing an absent PTY. The IPC and runtime spawn paths pass the pane key into `spawnForStablePane`, which consumes the retired owner when the live owner is gone and the fresh spawn has explicit persisted resume identity (`resumeProviderSession` or `agentSessionEnsure`). + +The existing comparison semantics remain intact: + +- known-different epochs strip resume options and mark `agentResumeUnavailable`; +- same epochs preserve the resume; +- unknown status, timeout, malformed IDs, non-SSH owners, and ordinary new agent launches behave as before. + +The retired owner is one-shot and connection-scoped, so it cannot cross the SSH execution boundary or affect a later unrelated spawn. + +## Regression proof + +The new regression test was run against the pre-fix implementation and failed as expected: + +```text +expected requestHostRpc to be called once, received zero calls +1 failed, 8 passed +``` + +That failure directly reproduced the missing gate after relay recovery had retired the owner. Coverage now includes: + +- different epoch after a retired owner: resume declined; +- same epoch after a retired owner: resume preserved; +- ordinary new agent launch: retired owner does not convert it into a resume decision; +- SSH reconnect retirement: the absent remote PTY records the correct connection/pane-scoped owner before cleanup. + +Final targeted result: 2 files passed, 46 tests passed. + +## Electron environment + +- App identity: `Orca: brennanb2025/sta5698-integration-e2e` +- `devRepoRoot`: `/Users/brennanbenson/orca/workspaces/orca/sta5698-electron-e2e` +- Named Playwright session: `sta5698-diag-task01-final` +- Isolated CDP endpoint: `127.0.0.1:9334` +- Isolated renderer: `127.0.0.1:5176` +- Isolated user-data path: `/tmp/orca-sta5698-diag-task01.klaEPi` +- SSH target: config-backed `openclaw`, displayed as `openclaw-sta5698-diag-task01` +- Remote namespace: `/home/brennan/sta5698-diag-task01-20260829T0018Z` +- Provider session identity explicitly seeded through the real store: `sta5698-session-diag-task01` + +`window.api.app.getIdentity()` was checked before validation and matched the worktree above. + +## Test 1 — relay replaced, resume must be declined + +**PASS** + +- Exact old relay PID sent `SIGKILL`: `3031516`. +- PTY mint epoch changed from `17abb0ae-969d-47c7-b59e-2a00ac800b0c` to `c31268f9-6763-4b06-8b35-976f924440ce`. +- Stub launch count: exactly 1. +- The only stub launch had `--dangerously-skip-permissions` and no `--resume`. +- Visible banner: `--- previous session unavailable, started fresh ---`. +- Working-shell sentinel: `STA5698_TEST1_SHELL_OK`. + +Evidence: + +- [Fresh-session banner](./test1-relay-replaced-pass.png) +- [Working shell sentinel](./test1-working-shell-pass.png) +- [Stub launch log](./test1-stub-launches.log) + +## Test 2 — relay alive, same epoch must resume + +**PASS** + +- Relay PID remained `3035314` throughout the scenario. +- Mint epoch remained `c31268f9-6763-4b06-8b35-976f924440ce`. +- Exact pane shell PID sent `SIGKILL`: `3046028`, after verifying `/bin/bash --rcfile /home/brennan/.orca-relay/shell-ready/bash/rcfile`. +- The dedicated pane-recovery remount seam was invoked after the automatic health remount did not trigger. +- The replacement PTY kept the same epoch and advanced to suffix `:4`. +- Stub launch count increased from 1 to 2. +- The second launch was `--dangerously-skip-permissions --resume sta5698-session-diag-task01`. +- Visible banner: `--- session restored ---`. + +Evidence: + +- [Restored-session UI and exact resume invocation](./test2-same-relay-resume-pass.png) +- [Stub launch log](./test2-stub-launches.log) + +## Required checks + +All final checks passed after formatting the final implementation: + +```text +pnpm tc +pnpm test src/main/ipc/pty/ # 3 files, 23 tests passed +pnpm test src/main/ssh/ssh-relay-session.test.ts \ + src/main/ipc/pty/pane/stable-owner-relay-epoch.test.ts # 2 files, 46 tests passed +npx oxlint +pnpm oxfmt +git diff --check +rg 'STA5698_DIAG' src/main src/renderer # no matches +``` + +## Cleanup + +The test agent tab was stopped and closed through the isolated Electron UI using Playwright CDP. The named Playwright session was closed, the recorded Electron session was interrupted, ports 9334 and 5176 were verified free, exact relay PID `3035314` was verified and terminated, the exact remote namespace was removed, and the isolated local profile was moved to Trash. No broad process kill or desktop-control automation was used. diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-relay-replaced-pass.png b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-relay-replaced-pass.png new file mode 100644 index 000000000000..7fba11109bdd Binary files /dev/null and b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-relay-replaced-pass.png differ diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-stub-launches.log b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-stub-launches.log new file mode 100644 index 000000000000..7223f4bec557 --- /dev/null +++ b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-stub-launches.log @@ -0,0 +1 @@ +timestamp=2026-08-29T00:47:07Z marker=sta5698-agent-diag-task01 pid=3034183 ppid=3034166 argv= --dangerously-skip-permissions diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-working-shell-pass.png b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-working-shell-pass.png new file mode 100644 index 000000000000..f5ca0fb31dfb Binary files /dev/null and b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test1-working-shell-pass.png differ diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-same-relay-resume-pass.png b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-same-relay-resume-pass.png new file mode 100644 index 000000000000..26575251b664 Binary files /dev/null and b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-same-relay-resume-pass.png differ diff --git a/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-stub-launches.log b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-stub-launches.log new file mode 100644 index 000000000000..b602232afbad --- /dev/null +++ b/validation-artifacts/sta5698-task01-final-20260829T010120Z/test2-stub-launches.log @@ -0,0 +1,2 @@ +timestamp=2026-08-29T00:54:28Z marker=sta5698-agent-diag-task01 pid=3046047 ppid=3046028 argv= --dangerously-skip-permissions +timestamp=2026-08-29T00:58:55Z marker=sta5698-agent-diag-task01 pid=3050884 ppid=3050868 argv= --dangerously-skip-permissions --resume sta5698-session-diag-task01