Skip to content
Closed
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
22 changes: 12 additions & 10 deletions src/main/ipc/pty/ipc/spawn-commit-persist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 19 additions & 16 deletions src/main/ipc/pty/ipc/spawn-commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { persistPtyIpcSpawnCommit } from './spawn-commit-persist'

export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawnResult> {
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).
Expand Down Expand Up @@ -76,15 +77,17 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
args.worktreeId.length > 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,
Expand Down Expand Up @@ -125,21 +128,21 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
// seed but the list/read records still live main-side.
seedTerminalRestoreRecordsFromSpawnResult(ctx.deps.runtime, ctx.result)
// Why: arm main's per-PTY Command Code output detector from the launch command (startupCommand parity); banner detection covers PTYs without one.
if (!ctx.stablePaneOwner) {
if (!ctx.stablePaneOwner && !agentResumeDeclined) {
ctx.deps.runtime?.noteTerminalSpawnCommand?.(
ctx.result.id,
typeof ctx.launchCommand === 'string' ? ctx.launchCommand : null
)
}
if (ctx.isClaudeLaunch && !ctx.stablePaneOwner) {
if (ctx.isClaudeLaunch && !ctx.stablePaneOwner && !agentResumeDeclined) {
markClaudePtySpawned(ctx.result.id)
}
// Why: record the paneKey mapping so clearProviderPtyState can clear the agent-hooks server's per-paneKey caches on exit.
// Why: args.env is untrusted IPC JSON (type unenforced); bound the paneKey so malformed/oversized values can't pollute ptyPaneKey or clearPaneState.
const rememberedPaneKey = ctx.validatedPaneKey
? rememberPaneKeyForPty(ctx.result.id, ctx.validatedPaneKey)
: null
if (ctx.legacySpawnPaneKey && ctx.migrationUnsupportedPaneKey) {
if (!agentResumeDeclined && ctx.legacySpawnPaneKey && ctx.migrationUnsupportedPaneKey) {
agentHookServer.registerPaneKeyAlias(
ctx.legacySpawnPaneKey.paneKey,
ctx.migrationUnsupportedPaneKey,
Expand All @@ -157,7 +160,7 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
Date.now(),
{ authorityVerified: true }
)
} else if (ctx.validatedPaneKey) {
} else if (!agentResumeDeclined && ctx.validatedPaneKey) {
if (!ctx.result.isReattach) {
clearMigrationUnsupportedPtysForPaneKey(ctx.validatedPaneKey)
}
Expand Down Expand Up @@ -189,7 +192,7 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
})
}
// Why: telemetry-plan.md§Agent launch semantics — fire agent_started only after spawn resolved; safeParse each field so a spoofed IPC payload can't poison the event (missing required field skips it).
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)
Expand All @@ -211,7 +214,7 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
ctx.snapshotKittyFlagsCoverReconciledSeq
? { snapshotSeq: ctx.reconciledSnapshotSeq }
: { snapshotKittyKeyboardFlags: undefined }),
...(!ctx.result.isReattach && ctx.effectiveLaunchConfig
...(!ctx.result.isReattach && !agentResumeDeclined && ctx.effectiveLaunchConfig
? { launchConfig: ctx.effectiveLaunchConfig }
: {}),
// Why: a daemon-retry race can surface isReattach even for a minted session id, and a reattach must never claim its cwd was remapped.
Expand All @@ -226,7 +229,7 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
}
// Why: renderer tab state cannot reliably infer background and reattached PTYs in the daemon inventory.
ctx.deps.sendPtySpawnedToRenderer(ctx.result.id)
if (!args.connectionId) {
if (!args.connectionId && !agentResumeDeclined) {
ctx.deps.options?.onCodexHomePtySpawned?.({
id: ctx.result.id,
codexHomePath: ctx.selectedCodexHomePath,
Expand Down
1 change: 1 addition & 0 deletions src/main/ipc/pty/ipc/spawn-execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export async function executePtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<void> {
owner: stablePaneOwnerCandidate,
worktreeId: args.worktreeId,
connectionId: args.connectionId,
paneKey: ctx.reservationPaneKey,
resolveOwner: () =>
resolveStablePaneOwner(
ctx.deps.runtime,
Expand Down
3 changes: 3 additions & 0 deletions src/main/ipc/pty/ipc/spawn-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
171 changes: 171 additions & 0 deletions src/main/ipc/pty/pane/relay-pty-mint-epoch.ts
Original file line number Diff line number Diff line change
@@ -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<IPtyProvider, Promise<string | undefined>>()
const retiredRelayOwnerByPane = new Map<string, string>()

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<string | undefined> {
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
}
}
Loading
Loading