Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
26 changes: 26 additions & 0 deletions src/main/codex/codex-legacy-session-resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,32 @@ export async function prepareLegacySharedCodexSessionResume(
return { useRealCodexHome: true }
}

/** Explicit account restarts must move the verified rollout before changing credentials. */
export async function prepareCodexAccountRestartResume(args: {
sourceHome: string
transcriptPath: string
targetHome: string
systemCodexHomePath: string
}): Promise<string> {
if (sameRuntimePath(args.sourceHome, args.targetHome)) {
return args.targetHome
}
const relativePath = relative(
resolve(join(args.sourceHome, 'sessions')),
resolve(args.transcriptPath)
)
if (!isDatedRolloutRelativePath(relativePath)) {
throw new Error(RETRYABLE_RESUME_ERROR)
}
const paths = resolveCodexSessionBackfillPaths(args.systemCodexHomePath)
await materializeLegacyRollout(
args.transcriptPath,
join(args.targetHome, 'sessions', relativePath),
paths.auditLogPath
)
return args.targetHome
}

/**
* Repins a per-account resume to the selected account's home, or null to keep
* the session's own home.
Expand Down
394 changes: 374 additions & 20 deletions src/main/ipc/pty-pane-restart-replace.test.ts

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src/main/ipc/pty/host-env/codex-resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export type PrepareCodexResumeHomeArgs = {
providerSession?: AgentProviderSessionMetadata
target: CodexAccountSelectionTarget
launchEnv?: NodeJS.ProcessEnv
useSelectedAccount?: boolean
}

export function prepareCodexResumeHome(
Expand All @@ -48,7 +49,8 @@ export function prepareCodexResumeHome(
preparation: prepareCodexSessionResume({
providerSession,
target: args.target,
launchEnv: args.launchEnv
launchEnv: args.launchEnv,
...(args.useSelectedAccount ? { useSelectedAccount: true } : {})
})
}
}
Expand Down
1 change: 1 addition & 0 deletions src/main/ipc/pty/host-env/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export type PrepareCodexSessionResume = (args: {
providerSession: AgentProviderSessionMetadata
target: CodexAccountSelectionTarget
launchEnv?: NodeJS.ProcessEnv
useSelectedAccount?: boolean
}) => Promise<CodexSessionResumePreparation | null>

export type CodexHomePtySpawnedLifecycleArgs = {
Expand Down
33 changes: 20 additions & 13 deletions src/main/ipc/pty/ipc/spawn-begin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import {
pendingRuntimePaneCreatesByOwnerKey
} from '../pane/spawn-reservation'
import { resolveStablePaneOwner } from '../pane/stable-owner'
import { excludeReplacedPaneOwner } from '../pane/pane-owner-replacement'
import type { PtyIpcSpawnState } from './spawn-state'
import type { PtySpawnIpcArgs } from './spawn-types'

/** The pane key a spawn names before preflight; null when it names no stable pane. */
function resolveEarlyPaneKey(args: PtySpawnIpcArgs): string | null {
export function resolveEarlyPaneKey(args: PtySpawnIpcArgs): string | null {
const leafId =
typeof args.leafId === 'string' && isTerminalLeafId(args.leafId) ? args.leafId : null
return typeof args.worktreeId === 'string' &&
Expand Down Expand Up @@ -45,12 +46,15 @@ export async function beginPtyIpcSpawn(
const initialStablePanePtyId = (() => {
try {
return !args.connectionId && initialPaneKey
? resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
initialPaneKey,
args.worktreeId,
args.connectionId
? excludeReplacedPaneOwner(
resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
initialPaneKey,
args.worktreeId,
args.connectionId
),
ctx.replacedPaneOwner
)?.ptyId
: undefined
} catch {
Expand Down Expand Up @@ -87,12 +91,15 @@ export async function beginPtyIpcSpawn(
}
ctx.earlyStablePaneOwner =
initialPaneKey && args.worktreeId
? resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
initialPaneKey,
args.worktreeId,
args.connectionId
? excludeReplacedPaneOwner(
resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
initialPaneKey,
args.worktreeId,
args.connectionId
),
ctx.replacedPaneOwner
)
: null
ctx.earlyWorktreeId = args.worktreeId
Expand Down
11 changes: 8 additions & 3 deletions src/main/ipc/pty/ipc/spawn-commit-persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { closeStartupQueryAuthorityForPty, getRelayPtyId } from '../provider/reg
import { createTerminalSessionStateSaveFailureMessage } from '../../../../shared/terminal-session-state-save-failure'
import { recordCodexPaneAccountForSpawn } from '../host-env/codex-home'
import { persistAdmittedStablePaneBinding } from '../pane/stable-owner'
import { swapReplacedPaneBinding } from '../pane/pane-owner-replacement'
import { claimSshPaneLease } from '../pane/ssh-pane-lease-claim'
import {
pendingByPaneKey,
Expand Down Expand Up @@ -60,9 +61,13 @@ export async function persistPtyIpcSpawnCommit(ctx: PtyIpcSpawnState): Promise<P
...(ctx.cwd ? { startupCwd: ctx.cwd } : {}),
origin: spawnCommitBindingOrigin(ctx.result)
}
const persisted = args.connectionId
? await ctx.deps.store.persistPtyBinding(binding, toSshExecutionHostId(args.connectionId))
: await ctx.deps.store.persistPtyBinding(binding)
const hostId = args.connectionId ? toSshExecutionHostId(args.connectionId) : undefined
const input = ctx.replacedPaneOwner
? swapReplacedPaneBinding(ctx.deps.store, binding, ctx.replacedPaneOwner, hostId)
: binding
const persisted = hostId
? await ctx.deps.store.persistPtyBinding(input, hostId)
: await ctx.deps.store.persistPtyBinding(input)
if (persisted === false) {
throw new Error('terminal_pane_owner_changed')
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/ipc/pty/ipc/spawn-env-codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export async function assemblePtyIpcSpawnCodexEnv(ctx: PtyIpcSpawnState): Promis
launchAgent: args.launchAgent,
providerSession: args.resumeProviderSession,
target: ctx.codexSelectionTarget,
launchEnv: ctx.baseEnv
launchEnv: ctx.baseEnv,
...(args.replacesPtyId ? { useSelectedAccount: true } : {})
})
ctx.codexResumeLaunch = codexResumePreparation
? await ctx.deps.resolveCodexResumeLaunch(args.command, codexResumePreparation)
Expand Down
30 changes: 15 additions & 15 deletions src/main/ipc/pty/ipc/spawn-execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getCohortAtEmit } from '../../../telemetry/cohort-classifier'
import { agentKindSchema } from '../../../../shared/telemetry-events'
import { normalizeNodePtySpawnError } from '../provider/liveness'
import { resolveStablePaneOwner, spawnForStablePane } from '../pane/stable-owner'
import { excludeReplacedPaneOwner } from '../pane/pane-owner-replacement'
import { assertSpawnReplyWasLive } from '../pane/agent-session-owners'
import { deletePtyOwnership } from '../provider/ownership-state'
import { ptySizes } from '../delivery/visibility-state'
Expand All @@ -23,13 +24,19 @@ export async function executePtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<void> {
ctx.deps.trustedTerminalHandleEnv.add(ctx.preAllocatedHandle)
}
ctx.spawnTiming.mark('options')
const stablePaneOwnerCandidate = resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
ctx.reservationPaneKey,
args.worktreeId,
args.connectionId
)
// Why exclude: the restart's own stop leaves its binding for the bind to swap, not to reattach.
const resolveOwner = () =>
excludeReplacedPaneOwner(
resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
ctx.reservationPaneKey,
args.worktreeId,
args.connectionId
),
ctx.replacedPaneOwner
)
const stablePaneOwnerCandidate = resolveOwner()
const expectedPtyId =
stablePaneOwnerCandidate?.ptyId ?? ctx.effectiveSessionAppId ?? ctx.effectiveSessionId
if (expectedPtyId) {
Expand All @@ -56,14 +63,7 @@ export async function executePtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<void> {
owner: stablePaneOwnerCandidate,
worktreeId: args.worktreeId,
connectionId: args.connectionId,
resolveOwner: () =>
resolveStablePaneOwner(
ctx.deps.runtime,
ctx.deps.store,
ctx.reservationPaneKey,
args.worktreeId,
args.connectionId
)
resolveOwner
})
ctx.result = stablePaneSpawn.result
ctx.stablePaneOwner = stablePaneSpawn.owner
Expand Down
19 changes: 15 additions & 4 deletions src/main/ipc/pty/ipc/spawn-run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { rejectPaneSpawnReservation, reserveIdlePaneSpawn } from '../pane/spawn-reservation'
import { ptySizes } from '../delivery/visibility-state'
import { beginPtyIpcSpawn, resolveEarlyPaneSpawnReservationKey } from './spawn-begin'
import {
beginPtyIpcSpawn,
resolveEarlyPaneKey,
resolveEarlyPaneSpawnReservationKey
} from './spawn-begin'
import { releaseStoppedPaneBinding, stopReplacedPaneOwner } from '../pane/pane-owner-replacement'
import { preparePtyIpcSpawnPreflight } from './spawn-preflight'
import { assemblePtyIpcSpawnEnv } from './spawn-env'
import { preparePtyIpcQoderCommand } from './spawn-qoder-command'
Expand Down Expand Up @@ -43,9 +48,12 @@ export async function runPtyIpcSpawn(deps: PtySpawnIpcDeps, args: PtySpawnIpcArg
}
try {
if (args.replacesPtyId !== undefined) {
// Why: stop before resolving the pane owner, so the spawn below finds a dead owner and
// launches fresh instead of reattaching the process this restart exists to replace.
await deps.stopReplacedPty(args.replacesPtyId)
ctx.replacedPaneOwner = await stopReplacedPaneOwner(deps, {
replacesPtyId: args.replacesPtyId,
paneKey: resolveEarlyPaneKey(args),
worktreeId: args.worktreeId,
connectionId: args.connectionId
})
}
triggerPtySpawnPushTargetMaterialization(deps, args)
const early = await beginPtyIpcSpawn(ctx)
Expand Down Expand Up @@ -81,6 +89,9 @@ export async function runPtyIpcSpawn(deps: PtySpawnIpcDeps, args: PtySpawnIpcArg
)
ctx.pendingRegistrationPtyId = null
}
if (ctx.replacedPaneOwner) {
await releaseStoppedPaneBinding(deps.store, ctx.replacedPaneOwner)
}
// Why: once the reservation is created, any later throw —
// spawn failure, persist failure, or a post-spawn helper such as
// seedHeadlessTerminal/registerPty/track — must settle it. Otherwise
Expand Down
3 changes: 3 additions & 0 deletions src/main/ipc/pty/ipc/spawn-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createPtySpawnTiming } from '../../pty-spawn-timing'
import { noCodexResumeLaunch, type CodexResumeLaunch } from '../host-env/codex-resume'
import type { StablePaneOwner } from '../pane/stable-owner'
import type { PaneSpawnReservation } from '../pane/spawn-reservation'
import type { ReplacedPaneOwner } from '../pane/pane-owner-replacement'
import { localProvider } from '../provider/registry'
import type { AdoptStablePaneResult, PtySpawnIpcArgs, PtySpawnIpcDeps } from './spawn-types'

Expand All @@ -25,6 +26,7 @@ export type PtyIpcSpawnState = {
earlyWorktreeId: string | undefined
paneSpawnReservationKey: string | null
paneSpawnReservation: PaneSpawnReservation | null
replacedPaneOwner: ReplacedPaneOwner | null
finishTerminalInstall: () => void
result: PtySpawnResult
stablePaneOwner: StablePaneOwner | null
Expand Down Expand Up @@ -103,6 +105,7 @@ export function createPtyIpcSpawnState(
earlyWorktreeId: undefined,
paneSpawnReservationKey: null,
paneSpawnReservation: null,
replacedPaneOwner: null,
finishTerminalInstall: () => {},
result: { id: '' },
stablePaneOwner: null,
Expand Down
1 change: 1 addition & 0 deletions src/main/ipc/pty/ipc/spawn-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export type PtySpawnIpcDeps = {
providerSession?: AgentProviderSessionMetadata
target: CodexAccountSelectionTarget
launchEnv?: NodeJS.ProcessEnv
useSelectedAccount?: boolean
}) => PreparedCodexResumeHome | null
noCodexResumeLaunch: (command: string | undefined) => CodexResumeLaunch
resolveCodexResumeLaunch: (
Expand Down
108 changes: 108 additions & 0 deletions src/main/ipc/pty/pane/pane-owner-replacement.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { expect, it, vi } from 'vitest'
import { fixture } from '../../../persistence/loading-store/profile-state-delayed-authority-fixture'
import { TEST_LEAF_1, TEST_LEAF_2 } from '../../../persistence-session-fixtures'
import { swapReplacedPaneBinding, type ReplacedPaneOwner } from './pane-owner-replacement'

vi.mock('../../../telemetry/client', () => ({ track: vi.fn() }))
vi.mock('../../../telemetry/cohort-classifier', () => ({
getCohortAtEmit: () => ({ nth_repo_added: 2 })
}))
vi.mock('../../../ssh/ssh-config-parser', () => ({
loadUserSshConfig: () => ({ hosts: [] }),
sshConfigHostsToTargets: () => []
}))

const worktreeId = 'repo-local::/fixture/local'
const tabId = 'restart-tab'

function replaced(ptyId: string, hostId?: string): ReplacedPaneOwner {
return { ptyId, pane: { worktreeId, tabId, leafId: TEST_LEAF_1, hostId } }
}

type FixtureStore = Awaited<ReturnType<typeof fixture>>['store']

/** The binding swap must survive the renderer's own pre-connect clear, which strict fences refuse. */
async function expectSwapAfterRendererClear(
store: FixtureStore,
oldId: string,
newId: string,
hostId?: string
): Promise<void> {
expect(
store.getWorkspaceSession(hostId).terminalLayoutsByTabId[tabId].ptyIdsByLeafId?.[TEST_LEAF_1]
).toBeUndefined()
const binding = { worktreeId, tabId, leafId: TEST_LEAF_1, ptyId: newId, incarnationId: 'inc-new' }
expect(
await store.persistPtyBinding(
{ ...binding, expectedBinding: { ptyId: oldId, incarnationId: 'inc-old' } },
hostId
)
).toBe(false)
expect(
await store.persistPtyBinding(
swapReplacedPaneBinding(store, binding, replaced(oldId, hostId), hostId),
hostId
)
).toBe(true)
expect(
store.getWorkspaceSession(hostId).terminalLayoutsByTabId[tabId].ptyIdsByLeafId?.[TEST_LEAF_1]
).toBe(newId)
}

it('swaps a local split pane whose renderer layout patch already dropped the stopped binding', async () => {
const { store } = await fixture()
const pane = { worktreeId, tabId }
await store.persistPtyBinding({
...pane,
leafId: TEST_LEAF_1,
ptyId: 'old',
incarnationId: 'inc-old'
})
await store.persistPtyBinding({ ...pane, leafId: TEST_LEAF_2, ptyId: 'sibling' })
const layouts = structuredClone(store.getWorkspaceSession().terminalLayoutsByTabId)
// The mounted restart clears only its own leaf before connecting; a partial map is honored.
delete layouts[tabId].ptyIdsByLeafId![TEST_LEAF_1]
store.patchWorkspaceSession({ terminalLayoutsByTabId: layouts })
await expectSwapAfterRendererClear(store, 'old', 'new')
expect(
store.getWorkspaceSession().terminalLayoutsByTabId[tabId].ptyIdsByLeafId?.[TEST_LEAF_2]
).toBe('sibling')
})

it('swaps an SSH pane whose terminated lease let the renderer clear withdraw the binding', async () => {
const { store } = await fixture()
const hostId = 'ssh:restart'
const oldId = 'ssh:restart@@remote-old'
await store.persistPtyBinding(
{ worktreeId, tabId, leafId: TEST_LEAF_1, ptyId: oldId, incarnationId: 'inc-old' },
hostId
)
store.upsertSshRemotePtyLease({
targetId: 'restart',
ptyId: 'remote-old',
worktreeId,
tabId,
leafId: TEST_LEAF_1,
state: 'attached'
})
// What the replacement stop records (finishPtyShutdown).
store.markSshRemotePtyLease('restart', 'remote-old', 'terminated')
const layouts = structuredClone(store.getWorkspaceSession(hostId).terminalLayoutsByTabId)
layouts[tabId].ptyIdsByLeafId = {}
store.patchWorkspaceSession({ terminalLayoutsByTabId: layouts }, hostId)
await expectSwapAfterRendererClear(store, oldId, 'ssh:restart@@remote-new', hostId)
})

it('refuses the swap when another owner holds the leaf', async () => {
const { store } = await fixture()
await store.persistPtyBinding({ worktreeId, tabId, leafId: TEST_LEAF_1, ptyId: 'successor' })
const binding = { worktreeId, tabId, leafId: TEST_LEAF_1, ptyId: 'new' }
expect(
await store.persistPtyBinding(
swapReplacedPaneBinding(store, binding, replaced('old'), undefined)
)
).toBe(false)
expect(
store.getWorkspaceSession().terminalLayoutsByTabId[tabId].ptyIdsByLeafId?.[TEST_LEAF_1]
).toBe('successor')
})
Loading
Loading