Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(mobile): hide handles for unavailable terminals (#36135)

Kelvin Amoaba12f9f8175cc1
diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts
index 0529bdf45cd..b5566659998 100644
--- a/src/main/daemon/daemon-pty-adapter.ts
+++ b/src/main/daemon/daemon-pty-adapter.ts
@@ -194,7 +194,7 @@ export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyPro
// Kept per incarnation: the report can land before its own spawn reply.
this.inputClosedIncarnations.record(event.sessionId, event.payload.incarnationId)
} else if (event.event === 'exit') {
- const currentIncarnationId = this.sessionIncarnations.get(event.sessionId)
+ const currentIncarnationId = this.ptyInventory.currentIncarnation(event.sessionId)
const pendingOperations = new Set([
...(this.pendingSpawnOperationsBySessionId.get(event.sessionId) ?? []),
...this.pendingClaimSpawnOperations
diff --git a/src/main/daemon/daemon-pty-availability-inventory.test.ts b/src/main/daemon/daemon-pty-availability-inventory.test.ts
new file mode 100644
index 00000000000..68dc5ef82d8
--- /dev/null
+++ b/src/main/daemon/daemon-pty-availability-inventory.test.ts
@@ -0,0 +1,280 @@
+import { rmSync } from 'node:fs'
+import { expect, it, vi } from 'vitest'
+import { DaemonPtyAdapter } from './daemon-pty-adapter'
+import {
+ createMockSubprocess,
+ startDaemonAdapterHarness,
+ waitFor
+} from './daemon-pty-adapter-test-harness'
+import type { DaemonServer } from './daemon-server'
+
+function omitIncarnation(result: unknown): unknown {
+ if (!result || typeof result !== 'object') {
+ return result
+ }
+ if ('incarnationId' in result) {
+ const { incarnationId: _incarnation, ...legacy } = result
+ return legacy
+ }
+ if ('sessions' in result && Array.isArray(result.sessions)) {
+ return { ...result, sessions: result.sessions.map(omitIncarnation) }
+ }
+ return result
+}
+
+function createInputClosableSubprocess() {
+ let inputClosed = false
+ let onInputClosed: ((reason: string) => void) | undefined
+ return {
+ ...createMockSubprocess(),
+ isInputClosed: () => inputClosed,
+ onInputClosed: (callback: (reason: string) => void) => {
+ onInputClosed = callback
+ },
+ closeInput: () => {
+ inputClosed = true
+ onInputClosed?.('master_closed')
+ }
+ }
+}
+
+function holdInventoryResponses(server: DaemonServer, beforeSnapshot = false, legacy = false) {
+ const router = server['requestRouter']
+ const route = router.route.bind(router)
+ const pending: ReturnType<typeof Promise.withResolvers<void>>[] = []
+ const spy = vi.spyOn(router, 'route').mockImplementation(async (clientId, request) => {
+ const read = async () => {
+ const result = await route(clientId, request)
+ return legacy ? omitIncarnation(result) : result
+ }
+ if (request.type !== 'listSessions') {
+ return read()
+ }
+ const response = Promise.withResolvers<void>()
+ const result = beforeSnapshot ? undefined : await read()
+ pending.push(response)
+ await response.promise
+ if (beforeSnapshot) {
+ return read()
+ }
+ return result
+ })
+ return {
+ pending,
+ dispose: () => {
+ pending.forEach((response) => response.resolve())
+ spy.mockRestore()
+ }
+ }
+}
+
+async function withRetainedPty(
+ run: (context: {
+ owner: DaemonPtyAdapter
+ subprocess: ReturnType<typeof createInputClosableSubprocess>
+ subprocesses: ReturnType<typeof createInputClosableSubprocess>[]
+ peer: DaemonPtyAdapter
+ responses: ReturnType<typeof holdInventoryResponses>
+ }) => Promise<void>,
+ beforeSnapshot = false,
+ legacy = false
+) {
+ const subprocesses: ReturnType<typeof createInputClosableSubprocess>[] = []
+ const harness = await startDaemonAdapterHarness(() => {
+ const subprocess = createInputClosableSubprocess()
+ subprocesses.push(subprocess)
+ return subprocess
+ })
+ const owner = new DaemonPtyAdapter(harness)
+ const peer = new DaemonPtyAdapter(harness)
+ let responses: ReturnType<typeof holdInventoryResponses> | undefined
+ try {
+ await harness.adapter.spawn({ sessionId: 'retained', cwd: '/tmp', cols: 80, rows: 24 })
+ const subprocess = subprocesses[0]
+ if (!subprocess) {
+ throw new Error('Expected the retained subprocess')
+ }
+ harness.adapter.dispose()
+ await owner.listProcesses()
+ expect(owner.hasPty('retained')).toBe(false)
+ expect(owner.getPtyAvailability('retained')).toBe(true)
+ responses = holdInventoryResponses(harness.server, beforeSnapshot, legacy)
+ await run({ owner, subprocess, subprocesses, peer, responses })
+ } finally {
+ responses?.dispose()
+ owner.dispose()
+ peer.dispose()
+ harness.adapter.dispose()
+ await harness.server.shutdown()
+ rmSync(harness.dir, { recursive: true, force: true })
+ }
+}
+
+it('commits confirmed absence while a newer inventory times out without disconnecting', async () => {
+ await withRetainedPty(async ({ owner, subprocess, responses }) => {
+ subprocess._simulateExit(0)
+ const first = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ // ast-grep-ignore: test-no-wall-clock -- Exercise the real RPC timeout while its socket stays connected.
+ const deadlineMs = Date.now() + 200
+ const second = owner.listProcesses({ deadlineMs }).then(
+ () => null,
+ (error: unknown) => error
+ )
+ await waitFor(() => responses.pending.length === 2)
+ responses.pending[0]?.resolve()
+ await expect(first).resolves.toEqual([])
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ expect(await second).toBeInstanceOf(Error)
+ expect(owner.getDaemonIdentity()).not.toBeNull()
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ })
+})
+
+it.each(['exit', 'close'] as const)(
+ 'commits retained absence while an unrelated attached PTY has a concurrent %s',
+ async (retirement) => {
+ await withRetainedPty(async ({ owner, subprocess, subprocesses, responses }) => {
+ await owner.spawn({ sessionId: 'attached', cwd: '/tmp', cols: 80, rows: 24 })
+ subprocess._simulateExit(0)
+ const inventory = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ if (retirement === 'exit') {
+ subprocesses[1]?._simulateExit(0)
+ } else {
+ await owner.shutdown('attached', { immediate: true })
+ }
+ await waitFor(() => !owner.hasPty('attached'))
+ responses.pending[0]?.resolve()
+ await expect(inventory).resolves.toHaveLength(1)
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ expect(owner.getPtyAvailability('attached')).toBe(false)
+ // ast-grep-ignore: test-no-wall-clock -- An ordinary RPC timeout must preserve the completed absence.
+ const deadlineMs = Date.now() + 200
+ const timedOut = owner.listProcesses({ deadlineMs }).catch((error: unknown) => error)
+ await waitFor(() => responses.pending.length === 2)
+ expect(await timedOut).toBeInstanceOf(Error)
+ expect(owner.getDaemonIdentity()).not.toBeNull()
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ })
+ }
+)
+
+it('admits a replacement incarnation captured after its predecessor retires during acquisition', async () => {
+ await withRetainedPty(async ({ owner, peer, subprocess, responses }) => {
+ await owner.attach('retained')
+ const inventory = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ subprocess._simulateExit(0)
+ await waitFor(() => !owner.hasPty('retained'))
+ const replacement = await peer.spawn({ sessionId: 'retained', cwd: '/tmp', cols: 80, rows: 24 })
+ responses.pending[0]?.resolve()
+ await expect(inventory).resolves.toMatchObject([{ incarnationId: replacement.incarnationId }])
+ expect(owner.hasPty('retained')).toBe(false)
+ expect(owner.getPtyAvailability('retained')).toBe(true)
+ }, true)
+})
+
+it('does not let an older absent census prune a replacement after a newer census commits', async () => {
+ await withRetainedPty(async ({ owner, subprocess, responses }) => {
+ await owner.attach('retained')
+ subprocess._simulateExit(0)
+ expect(owner.hasPty('retained')).toBe(true)
+ const first = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1 && !owner.hasPty('retained'))
+ await owner.spawn({ sessionId: 'retained', cwd: '/tmp', cols: 80, rows: 24 })
+ const second = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 2)
+ responses.pending[1]?.resolve()
+ await expect(second).resolves.toHaveLength(1)
+ responses.pending[0]?.resolve()
+ await expect(first).resolves.toEqual([])
+ expect(owner.hasPty('retained')).toBe(true)
+ expect(owner.getPtyAvailability('retained')).toBe(true)
+ })
+})
+
+it('preserves a newly acknowledged legacy owner against an older absent census', async () => {
+ await withRetainedPty(
+ async ({ owner, subprocess, responses }) => {
+ await owner.attach('retained')
+ const stream = owner['client']['streamSocket']
+ if (!stream) {
+ throw new Error('Expected the event stream')
+ }
+ stream.pause()
+ subprocess._simulateExit(0)
+ const inventory = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ const replacement = await owner.spawn({
+ sessionId: 'retained',
+ cwd: '/tmp',
+ cols: 80,
+ rows: 24
+ })
+ expect(replacement.incarnationId).toBeUndefined()
+ responses.pending[0]?.resolve()
+ await expect(inventory).resolves.toEqual([])
+ expect(owner.hasPty('retained')).toBe(true)
+ expect(owner.getPtyAvailability('retained')).toBe(true)
+ },
+ false,
+ true
+ )
+})
+
+it('uses confirmed replacement identity after an old owner closes input and is explicitly closed', async () => {
+ await withRetainedPty(async ({ owner, peer, subprocess, subprocesses, responses }) => {
+ await owner.attach('retained')
+ subprocess.closeInput()
+ await waitFor(() => owner.getPtyAvailability('retained') === false)
+ const stream = owner['client']['streamSocket']
+ if (!stream) {
+ throw new Error('Expected the event stream')
+ }
+ stream.pause()
+ await owner.shutdown('retained', { immediate: true })
+ const replacement = await peer.spawn({ sessionId: 'retained', cwd: '/tmp', cols: 80, rows: 24 })
+ expect(replacement.isReattach).not.toBe(true)
+ const inventory = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ responses.pending[0]?.resolve()
+ await expect(inventory).resolves.toMatchObject([{ incarnationId: replacement.incarnationId }])
+ expect(owner.hasPty('retained')).toBe(false)
+ expect(owner.getPtyAvailability('retained')).toBe(true)
+ await expect(owner.writeWithSettlement('retained', 'live')).resolves.toMatchObject({
+ outcome: 'accepted'
+ })
+ await waitFor(() => subprocesses[1]?.write.mock.calls.length === 1)
+ expect(subprocesses[1]?.write).toHaveBeenCalledWith('live')
+ })
+})
+
+it('does not let an older positive reply overwrite a newer confirmed absence', async () => {
+ await withRetainedPty(async ({ owner, subprocess, responses }) => {
+ const first = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ subprocess._simulateExit(0)
+ const second = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 2)
+ responses.pending[1]?.resolve()
+ await expect(second).resolves.toEqual([])
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ responses.pending[0]?.resolve()
+ await expect(first).resolves.toHaveLength(1)
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ })
+})
+
+it('does not revive an attached PTY from inventory captured before its exit', async () => {
+ await withRetainedPty(async ({ owner, subprocess, responses }) => {
+ await owner.attach('retained')
+ const inventory = owner.listProcesses()
+ await waitFor(() => responses.pending.length === 1)
+ subprocess._simulateExit(0)
+ await waitFor(() => !owner.hasPty('retained'))
+ responses.pending[0]?.resolve()
+ await expect(inventory).resolves.toHaveLength(1)
+ expect(owner.getPtyAvailability('retained')).toBe(false)
+ })
+})
diff --git a/src/main/daemon/daemon-pty-inventory-observation.ts b/src/main/daemon/daemon-pty-inventory-observation.ts
new file mode 100644
index 00000000000..f6c7ea84db2
--- /dev/null
+++ b/src/main/daemon/daemon-pty-inventory-observation.ts
@@ -0,0 +1,111 @@
+type InventoryRequest = {
+ sequence: number
+ transportEpoch: number
+ owners: Map<string, string | undefined>
+ replacements: Map<string, string | undefined>
+ retirements: Map<string, Set<string | undefined>>
+}
+
+export class DaemonPtyInventoryObservation {
+ private sessions: Map<string, string | undefined> | null = null
+ private sequence = 0
+ private committedSequence = 0
+ private transportEpoch = 0
+ private pending = new Set<InventoryRequest>()
+
+ constructor(
+ private readonly activeIds: Set<string>,
+ private readonly incarnations: ReadonlyMap<string, string>
+ ) {}
+
+ has(id: string): boolean {
+ return this.sessions?.has(id) ?? false
+ }
+
+ currentIncarnation(id: string): string | undefined {
+ return this.activeIds.has(id)
+ ? this.incarnations.get(id)
+ : (this.sessions?.get(id) ?? this.incarnations.get(id))
+ }
+
+ begin(): InventoryRequest {
+ const request: InventoryRequest = {
+ sequence: ++this.sequence,
+ transportEpoch: this.transportEpoch,
+ owners: new Map([...this.activeIds].map((id) => [id, this.incarnations.get(id)])),
+ replacements: new Map(),
+ retirements: new Map()
+ }
+ this.pending.add(request)
+ return request
+ }
+
+ end(request: InventoryRequest): void {
+ this.pending.delete(request)
+ }
+
+ reset(): void {
+ this.sessions = null
+ this.transportEpoch += 1
+ }
+
+ spawned(id: string, incarnation: string | undefined): void {
+ this.sessions?.delete(id)
+ for (const request of this.pending) {
+ request.replacements.set(id, incarnation)
+ }
+ }
+
+ retire(id: string, incarnation: string | undefined): boolean {
+ const current = this.currentIncarnation(id)
+ if (current !== undefined && current !== incarnation) {
+ return false
+ }
+ const listed = this.sessions?.get(id)
+ if (incarnation === undefined || listed === undefined || listed === incarnation) {
+ this.sessions?.delete(id)
+ }
+ for (const request of this.pending) {
+ const retired = request.retirements.get(id) ?? new Set()
+ retired.add(incarnation)
+ request.retirements.set(id, retired)
+ if (incarnation === undefined || request.replacements.get(id) === incarnation) {
+ request.replacements.delete(id)
+ }
+ }
+ return true
+ }
+
+ commit(request: InventoryRequest, alive: ReadonlyMap<string, string | undefined>): void {
+ if (
+ request.transportEpoch !== this.transportEpoch ||
+ request.sequence <= this.committedSequence
+ ) {
+ return
+ }
+ const sessions = new Map(alive)
+ for (const [id, incarnation] of sessions) {
+ const retired = request.retirements.get(id)
+ if (
+ (retired &&
+ (incarnation === undefined || retired.has(undefined) || retired.has(incarnation))) ||
+ (request.replacements.has(id) &&
+ (incarnation === undefined || request.replacements.get(id) !== incarnation))
+ ) {
+ sessions.delete(id)
+ }
+ }
+ for (const [id, incarnation] of request.owners) {
+ if (
+ !alive.has(id) &&
+ !request.retirements.has(id) &&
+ !request.replacements.has(id) &&
+ this.incarnations.get(id) === incarnation
+ ) {
+ this.activeIds.delete(id)
+ }
+ }
+ this.sessions = sessions
+ this.committedSequence = request.sequence
+ }
+}
diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts
index abc4ac5e0f7..75d63a28394 100644
--- a/src/main/daemon/daemon-pty-router.ts
+++ b/src/main/daemon/daemon-pty-router.ts
@@ -138,6 +138,10 @@ export class DaemonPtyRouter implements IPtyProvider {
return this.current.hasPty(id) || this.legacy.some((adapter) => adapter.hasPty(id))
}
+ getPtyAvailability(id: string): boolean | null {
+ return this.adapterFor(id).getPtyAvailability(id)
+ }
+
async probePtyLiveness(id: string): Promise<boolean | null> {
return await this.ownerResolver.probe(id)
}
diff --git a/src/main/daemon/daemon-pty-runtime-state.ts b/src/main/daemon/daemon-pty-runtime-state.ts
index 03f8d99f391..1f2082f6f01 100644
--- a/src/main/daemon/daemon-pty-runtime-state.ts
+++ b/src/main/daemon/daemon-pty-runtime-state.ts
@@ -1,5 +1,6 @@
import { DaemonClient } from './client'
import { DaemonPtyInputClosedIncarnations } from './daemon-pty-input-closed-incarnations'
+import { DaemonPtyInventoryObservation } from './daemon-pty-inventory-observation'
import { createDaemonAuditEligibilityTracker } from './daemon-audit-eligibility-event'
import type {
DaemonAuditContext,
@@ -138,6 +139,10 @@ export abstract class DaemonPtyRuntimeState {
protected getSizeUnsupported = false
protected sessionsAwaitingDaemonRecovery = new Set<string>()
protected sessionIncarnations = new Map<string, string>()
+ protected readonly ptyInventory = new DaemonPtyInventoryObservation(
+ this.activeSessionIds,
+ this.sessionIncarnations
+ )
protected inputClosedIncarnations = new DaemonPtyInputClosedIncarnations()
protected pendingSpawnOperationsBySessionId = new Map<string, Set<PendingDaemonSpawnOperation>>()
protected pendingClaimSpawnOperations = new Set<PendingDaemonSpawnOperation>()
@@ -186,8 +191,7 @@ export abstract class DaemonPtyRuntimeState {
// Host loss leaves history unended, so the pane can still cold-restore (as after a crash).
{ closeHistory = true }: { closeHistory?: boolean } = {}
): void {
- const currentIncarnationId = this.sessionIncarnations.get(sessionId)
- if (currentIncarnationId !== undefined && expectedIncarnationId !== currentIncarnationId) {
+ if (!this.ptyInventory.retire(sessionId, expectedIncarnationId)) {
return
}
this.activeSessionIds.delete(sessionId)
@@ -256,6 +260,7 @@ export abstract class DaemonPtyRuntimeState {
this.protocolVersion >= SNAPSHOT_SERIALIZER_FIDELITY_DAEMON_PROTOCOL_VERSION
this.supportsStartupIngress = supportsPtyStartupIngress(this.protocolVersion)
this.client.onDisconnected(() => {
+ this.ptyInventory.reset()
if (!this.respawnAdoptionClosed) {
this.writeRecoveryAttempted = false
for (const id of this.activeSessionIds) {
diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts
index 7ffc85b46fc..c83ce19f04a 100644
--- a/src/main/daemon/daemon-pty-session-control.ts
+++ b/src/main/daemon/daemon-pty-session-control.ts
@@ -240,6 +240,7 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput {
id: string,
opts: { keepHistory?: boolean }
): Promise<void> {
+ this.ptyInventory.retire(id, this.ptyInventory.currentIncarnation(id))
this.activeSessionIds.delete(id)
this.hostLossSessionIds.delete(id)
this.clearSessionAwaitingDaemonRecovery(id)
diff --git a/src/main/daemon/daemon-pty-session-input.ts b/src/main/daemon/daemon-pty-session-input.ts
index 5aede584428..44123e92f27 100644
--- a/src/main/daemon/daemon-pty-session-input.ts
+++ b/src/main/daemon/daemon-pty-session-input.ts
@@ -3,9 +3,21 @@ import { PtyWriteUnavailableError } from '../providers/pty-write-unavailable-err
import { writeRefused, type WriteSettlement } from '../../shared/pty-write-settlement'
export abstract class DaemonPtySessionInput extends DaemonPtySessionSpawn {
+ getPtyAvailability(id: string): boolean | null {
+ if (
+ !this.client.isConnected() ||
+ this.sessionsAwaitingDaemonRecovery.has(id) ||
+ this.inputClosedIncarnations.isClosed(id, this.ptyInventory.currentIncarnation(id))
+ ) {
+ return false
+ }
+ // Inventory includes retained sessions this host has not attached yet.
+ return this.activeSessionIds.has(id) || this.ptyInventory.has(id)
+ }
+
write(id: string, data: string): boolean {
// Remount recovery cannot reopen a live child's retired PTY master; refuse instead of dropping.
- if (this.inputClosedIncarnations.isClosed(id, this.sessionIncarnations.get(id))) {
+ if (this.inputClosedIncarnations.isClosed(id, this.ptyInventory.currentIncarnation(id))) {
return false
}
const recoverable = this.prepareWrite(id)
@@ -14,7 +26,7 @@ export abstract class DaemonPtySessionInput extends DaemonPtySessionSpawn {
/** Preserve ambiguous delivery as a settlement: throwing would look like proven refusal and permit replay. */
async writeWithSettlement(id: string, data: string): Promise<WriteSettlement> {
- if (this.inputClosedIncarnations.isClosed(id, this.sessionIncarnations.get(id))) {
+ if (this.inputClosedIncarnations.isClosed(id, this.ptyInventory.currentIncarnation(id))) {
return writeRefused('provider_refused_write')
}
let recoverable: boolean
diff --git a/src/main/daemon/daemon-pty-session-inventory.ts b/src/main/daemon/daemon-pty-session-inventory.ts
index 82916f3fd2b..809c31762d4 100644
--- a/src/main/daemon/daemon-pty-session-inventory.ts
+++ b/src/main/daemon/daemon-pty-session-inventory.ts
@@ -18,56 +18,56 @@ import type { PtyProcessInfo } from '../providers/pty-provider-contract'
export abstract class DaemonPtySessionInventory extends DaemonPtyProcessInspection {
async listProcesses(opts?: { deadlineMs?: number }): Promise<PtyProcessInfo[]> {
- // Snapshot before awaiting inventory so newly spawned IDs cannot be reconciled away.
- const preRequestActiveIds = new Set(this.activeSessionIds)
try {
// Retry connect and inventory together; reconcile only once after both succeed.
// Share the teardown deadline so handshake cannot consume a fresh budget before inventory.
- const result = await this.withDaemonRetry(async () => {
+ return await this.withDaemonRetry(async () => {
await this.ensureConnected(opts?.deadlineMs)
- return this.client.request<ListSessionsResult>(
- 'listSessions',
- undefined,
- remainingDaemonRequestTimeoutMs(opts?.deadlineMs)
- )
- })
- const admission = new PtyProcessListAdmission()
- const processes: PtyProcessInfo[] = []
- const aliveSessionIds = new Set<string>()
- for (const session of result.sessions) {
- if (!session.isAlive) {
- continue
+ const inventory = this.ptyInventory.begin()
+ try {
+ const result = await this.client.request<ListSessionsResult>(
+ 'listSessions',
+ undefined,
+ remainingDaemonRequestTimeoutMs(opts?.deadlineMs)
+ )
+ const admission = new PtyProcessListAdmission()
+ const processes: PtyProcessInfo[] = []
+ const aliveSessionIds = new Map<string, string | undefined>()
+ for (const session of result.sessions) {
+ if (!session.isAlive) {
+ continue
+ }
+ aliveSessionIds.set(session.sessionId, session.incarnationId)
+ const { worktreeId } = parsePtySessionId(session.sessionId)
+ processes.push(
+ admission.admit({
+ id: session.sessionId,
+ ...(session.incarnationId ? { incarnationId: session.incarnationId } : {}),
+ ...(session.pid ? { rootProcessId: session.pid } : {}),
+ // Spawn cwd remains authoritative until the daemon reports live cwd.
+ cwd: session.cwd ?? this.initialCwds.get(session.sessionId) ?? '',
+ title: 'shell',
+ ...(session.foregroundProcess
+ ? { foregroundProcess: session.foregroundProcess }
+ : {}),
+ ...(worktreeId ? { worktreeId } : {}),
+ ...(session.terminalHandle ? { terminalHandle: session.terminalHandle } : {}),
+ ...(session.paneKey ? { paneKey: session.paneKey } : {}),
+ ...(session.wslDistro !== undefined ? { wslDistro: session.wslDistro } : {}),
+ ...(session.state === 'exiting' ? { exiting: true as const } : {}),
+ ...this.validatedAgentSessionOwners(session.agentSessionOwners)
+ })
+ )
+ }
+ this.ptyInventory.commit(inventory, aliveSessionIds)
+ this.publishAuditObservation(
+ recordAuthenticatedInventory(this.auditContext, this.exactDaemonIncarnation)
+ )
+ return processes
+ } finally {
+ this.ptyInventory.end(inventory)
}
- aliveSessionIds.add(session.sessionId)
- const { worktreeId } = parsePtySessionId(session.sessionId)
- processes.push(
- admission.admit({
- id: session.sessionId,
- ...(session.incarnationId ? { incarnationId: session.incarnationId } : {}),
- ...(session.pid ? { rootProcessId: session.pid } : {}),
- // Spawn cwd remains authoritative until the daemon reports live cwd.
- cwd: session.cwd ?? this.initialCwds.get(session.sessionId) ?? '',
- title: 'shell',
- ...(session.foregroundProcess ? { foregroundProcess: session.foregroundProcess } : {}),
- ...(worktreeId ? { worktreeId } : {}),
- ...(session.terminalHandle ? { terminalHandle: session.terminalHandle } : {}),
- ...(session.paneKey ? { paneKey: session.paneKey } : {}),
- ...(session.wslDistro !== undefined ? { wslDistro: session.wslDistro } : {}),
- ...(session.state === 'exiting' ? { exiting: true as const } : {}),
- ...this.validatedAgentSessionOwners(session.agentSessionOwners)
- })
- )
- }
- // Reconcile missed disconnect-time exits so hasPty cannot retain disproven owners forever.
- for (const id of preRequestActiveIds) {
- if (!aliveSessionIds.has(id)) {
- this.activeSessionIds.delete(id)
- }
- }
- this.publishAuditObservation(
- recordAuthenticatedInventory(this.auditContext, this.exactDaemonIncarnation)
- )
- return processes
+ })
} catch (error) {
const missingAuthenticatedToken = this.isRetiredEndpointTokenMissing()
const missingNamedPipe = isMissingWindowsNamedPipeError(error)
@@ -124,6 +124,7 @@ export abstract class DaemonPtySessionInventory extends DaemonPtyProcessInspecti
fanoutSyntheticExits(code: number, exit: { replacedByRestart?: true } = {}): void {
const ids = [...this.activeSessionIds]
this.activeSessionIds.clear()
+ this.ptyInventory.reset()
this.sessionsAwaitingDaemonRecovery.clear()
this.writeRecoveryAttempted = false
this.dirtySessionVersions.clear()
diff --git a/src/main/daemon/daemon-pty-spawn-result.ts b/src/main/daemon/daemon-pty-spawn-result.ts
index b390f94c749..1f02667c8a0 100644
--- a/src/main/daemon/daemon-pty-spawn-result.ts
+++ b/src/main/daemon/daemon-pty-spawn-result.ts
@@ -75,6 +75,7 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest {
// Both ids: adoptSpawnResultSession may have rewritten sessionId to the claim owner.
this.clearSessionAwaitingDaemonRecovery(requestedSessionId)
this.clearSessionAwaitingDaemonRecovery(sessionId)
+ this.ptyInventory.spawned(sessionId, result.incarnationId)
const exitedResult = this.resultForExitBeforeSpawnReply(sessionId, result, operation)
if (exitedResult) {
return exitedResult
@@ -149,6 +150,7 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest {
effectiveRows = restoreInfo.rows
result = await createOrAttach(historySeedSegments)
await adoptSpawnResultSession(result)
+ this.ptyInventory.spawned(sessionId, result.incarnationId)
const exitedRetryResult = this.resultForExitBeforeSpawnReply(sessionId, result, operation)
if (exitedRetryResult) {
return exitedRetryResult
@@ -269,15 +271,14 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest {
}
}
- const isReattach = !result.isNew
- if (!isReattach || !result.snapshot) {
+ if (result.isNew || !result.snapshot) {
return finalizeSpawnResult({
id: sessionId,
...daemonSpawnResultIdentity(result),
pid,
...(providerWslDistro !== undefined ? { wslDistro: providerWslDistro } : {}),
...(providerSequence ? { providerSequence } : {}),
- ...(isReattach ? { isReattach: true } : {})
+ ...(!result.isNew ? { isReattach: true } : {})
})
}
@@ -289,7 +290,6 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest {
const isAltScreen = reattachSnapshot.modes.alternateScreen
const snapshotPrefix = reattachSnapshot.scrollbackAnsi + reattachSnapshot.rehydrateSequences
const snapshotFrame = reattachSnapshot.snapshotAnsi
- const snapshotPayload = snapshotPrefix + snapshotFrame
// Reassert kitty flags after payload screen switches; carry known zero separately from unknown.
const kittyKeyboardFlags = parseTerminalKittyKeyboardFlags(
reattachSnapshot.modes.kittyKeyboardFlags
@@ -299,7 +299,7 @@ export abstract class DaemonPtySpawnResult extends DaemonPtySpawnRequest {
...daemonSpawnResultIdentity(result),
pid,
...(providerWslDistro !== undefined ? { wslDistro: providerWslDistro } : {}),
- snapshot: snapshotPayload,
+ snapshot: snapshotPrefix + snapshotFrame,
snapshotCols: reattachSnapshot.cols,
snapshotRows: reattachSnapshot.rows,
// Only alt frames need a separate restore; normal history can replay at its captured grid.
diff --git a/src/main/daemon/degraded-daemon-pty-provider.ts b/src/main/daemon/degraded-daemon-pty-provider.ts
index c7552d110ec..a78047eb5e3 100644
--- a/src/main/daemon/degraded-daemon-pty-provider.ts
+++ b/src/main/daemon/degraded-daemon-pty-provider.ts
@@ -98,6 +98,9 @@ export class DegradedDaemonPtyProvider implements IPtyProvider {
return mapped ? (mapped.hasPty?.(id) ?? true) : this.findProviderForExistingSession(id) !== null
}
+ getPtyAvailability = (id: string): boolean | null =>
+ this.providerFor(id).getPtyAvailability?.(id) ?? null
+
async probePtyLiveness(id: string): Promise<boolean | null> {
const mapped = this.sessionProviders.get(id)
if (mapped && (mapped.hasPty?.(id) ?? true)) {
diff --git a/src/main/ipc/pty/pty-startup-swap-window-presence.test.ts b/src/main/ipc/pty/pty-startup-swap-window-presence.test.ts
index 5fd940ba63c..ffce1593b46 100644
--- a/src/main/ipc/pty/pty-startup-swap-window-presence.test.ts
+++ b/src/main/ipc/pty/pty-startup-swap-window-presence.test.ts
@@ -47,6 +47,11 @@ vi.mock('../../codex/codex-state-db-backfill-recovery', () =>
import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock())
)
+type PresenceController = {
+ hasPty: (ptyId: string) => boolean | null
+ getPtyAvailability: (ptyId: string) => boolean | null
+}
+
// During daemon startup, local-provider absence cannot prove restored PTYs dead; await the owning provider or report unknown.
describe('registerPtyHandlers daemon-swap-window presence', () => {
const { handlers, mainWindow, installDaemonTestProvider } = setupPtyIpcSuite()
@@ -66,10 +71,8 @@ describe('registerPtyHandlers daemon-swap-window presence', () => {
)
}
- const installRuntimeControllerWithBarrier = (
- barrier: Promise<void>
- ): { hasPty: (ptyId: string) => boolean | null } => {
- let controller: { hasPty: (ptyId: string) => boolean | null } | undefined
+ const installRuntimeControllerWithBarrier = (barrier: Promise<void>): PresenceController => {
+ let controller: PresenceController | undefined
registerWithStartupBarrier(barrier, {
setPtyController: vi.fn((next) => {
controller = next
@@ -114,18 +117,23 @@ describe('registerPtyHandlers daemon-swap-window presence', () => {
// The pre-swap local provider cannot authoritatively answer for a daemon-owned PTY.
expect(controller.hasPty('daemon-restored-pty')).toBe(null)
+ expect(controller.getPtyAvailability('daemon-restored-pty')).toBe(null)
- installDaemonTestProvider({ hasPty: (id: string) => id === 'daemon-restored-pty' })
+ installDaemonTestProvider({
+ hasPty: (id: string) => id === 'daemon-restored-pty',
+ getPtyAvailability: () => false
+ })
barrier.resolve()
await vi.waitFor(() => {
expect(controller.hasPty('daemon-restored-pty')).toBe(true)
+ expect(controller.getPtyAvailability('daemon-restored-pty')).toBe(false)
})
})
it('runtime controller hasPty never answers a paired-runtime handle from the local registry', () => {
// Exercise remote ownership without a startup barrier; local-provider silence must still remain unknown.
- let controller: { hasPty: (ptyId: string) => boolean | null } | undefined
+ let controller: PresenceController | undefined
registerPtyHandlers(
mainWindow as never,
{
@@ -140,6 +148,7 @@ describe('registerPtyHandlers daemon-swap-window presence', () => {
)
expect(controller?.hasPty('remote:environment@@pty-1')).toBe(null)
+ expect(controller?.getPtyAvailability('remote:environment@@pty-1')).toBe(null)
})
it('pty:inspectProcess defers a restored daemon id until the provider swap lands instead of answering from the non-owning provider', async () => {
@@ -177,7 +186,7 @@ describe('registerPtyHandlers daemon-swap-window presence', () => {
it('keeps the in-process provider authoritative when no startup barrier is configured', async () => {
// Headless hosts install their sole provider before registration; its absence is authoritative (#12393).
- let controller: { hasPty: (ptyId: string) => boolean | null } | undefined
+ let controller: PresenceController | undefined
registerPtyHandlers(
mainWindow as never,
{
diff --git a/src/main/ipc/pty/runtime/controller.ts b/src/main/ipc/pty/runtime/controller.ts
index db8de341cf3..9fd9e877531 100644
--- a/src/main/ipc/pty/runtime/controller.ts
+++ b/src/main/ipc/pty/runtime/controller.ts
@@ -27,6 +27,7 @@ import {
getSizeFromRuntimeController,
hasChildProcessesFromRuntimeController,
hasPtyFromRuntimeController,
+ getPtyAvailabilityFromRuntimeController,
hasRendererSerializerFromRuntimeController,
inspectProcessFromRuntimeController,
probePtyLivenessFromRuntimeController,
@@ -83,6 +84,7 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi
clearBuffer: (ptyId) => clearBufferFromRuntimeController(deps, ptyId),
resetInputModes: (ptyId) => resetInputModesFromRuntimeController(deps, ptyId),
hasPty: (ptyId) => hasPtyFromRuntimeController(deps, ptyId),
+ getPtyAvailability: (ptyId) => getPtyAvailabilityFromRuntimeController(deps, ptyId),
listProcesses: (hostId, opts) => listProcessesFromRuntimeController(deps, hostId, opts),
listProcessesWithHostScope: (opts) =>
listProcessesWithHostScopeFromRuntimeController(deps, opts),
diff --git a/src/main/ipc/pty/runtime/operations.ts b/src/main/ipc/pty/runtime/operations.ts
index 16fa7490017..daf94951e47 100644
--- a/src/main/ipc/pty/runtime/operations.ts
+++ b/src/main/ipc/pty/runtime/operations.ts
@@ -227,9 +227,10 @@ export async function resetInputModesFromRuntimeController(
const settledLocalPtyProviderStartups = new WeakSet<Promise<void>>()
const watchedLocalPtyProviderStartups = new WeakSet<Promise<void>>()
-export function hasPtyFromRuntimeController(
+function readReadyPtyProvider(
deps: PtyRuntimeControllerDeps,
- ptyId: string
+ ptyId: string,
+ read: (provider: IPtyProvider) => boolean | null
): boolean | null {
try {
// A local provider cannot prove remote-host absence.
@@ -248,12 +249,27 @@ export function hasPtyFromRuntimeController(
}
return null
}
- return getProviderForPty(ptyId).hasPty?.(ptyId) ?? null
+ return read(getProviderForPty(ptyId))
} catch {
return null
}
}
+export function hasPtyFromRuntimeController(deps: PtyRuntimeControllerDeps, ptyId: string) {
+ return readReadyPtyProvider(deps, ptyId, (provider) => provider.hasPty?.(ptyId) ?? null)
+}
+
+export function getPtyAvailabilityFromRuntimeController(
+ deps: PtyRuntimeControllerDeps,
+ ptyId: string
+): boolean | null {
+ return readReadyPtyProvider(
+ deps,
+ ptyId,
+ (provider) => provider.getPtyAvailability?.(ptyId) ?? null
+ )
+}
+
export function resizePtyFromRuntimeController(ptyId: string, cols: number, rows: number): boolean {
try {
getProviderForPty(ptyId).resize(ptyId, cols, rows)
diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts
index e8b6c27ec88..c85a14336c3 100644
--- a/src/main/providers/local-pty-provider.ts
+++ b/src/main/providers/local-pty-provider.ts
@@ -83,6 +83,8 @@ export class LocalPtyProvider implements IPtyProvider {
hasPty(id: string): boolean {
return ptyProcesses.has(id)
}
+ getPtyAvailability = (id: string): boolean => this.hasPty(id)
+
write(id: string, data: string): boolean {
return writeLocalPty(id, data)
}
diff --git a/src/main/providers/pty-provider-contract.ts b/src/main/providers/pty-provider-contract.ts
index d0a16c91098..6b15dbbd9c7 100644
--- a/src/main/providers/pty-provider-contract.ts
+++ b/src/main/providers/pty-provider-contract.ts
@@ -144,6 +144,8 @@ export type IPtyProvider = {
supportsAgentSessionCreateOperations?: (options?: PtyProbeOptions) => boolean | Promise<boolean>
attach(id: string): Promise<Pick<PtySpawnResult, 'providerSequence' | 'lastTitle'> | void>
hasPty?: (id: string) => boolean
+ /** Read-only input availability, including retained unattached PTYs; null means unobserved. */
+ getPtyAvailability?: (id: string) => boolean | null
/** Exact provider readback: false only when the provider answered that the PTY is absent. */
probePtyLiveness?: (id: string) => Promise<boolean | null>
write(id: string, data: string): boolean | void
diff --git a/src/main/runtime/mobile-session-dead-pty.test.ts b/src/main/runtime/mobile-session-dead-pty.test.ts
new file mode 100644
index 00000000000..06de4c6da5f
--- /dev/null
+++ b/src/main/runtime/mobile-session-dead-pty.test.ts
@@ -0,0 +1,231 @@
+import { expect, it, vi } from 'vitest'
+import { rmSync } from 'node:fs'
+import { DaemonPtyAdapter } from '../daemon/daemon-pty-adapter'
+import { DaemonPtyRouter } from '../daemon/daemon-pty-router'
+import { DegradedDaemonPtyProvider } from '../daemon/degraded-daemon-pty-provider'
+import { LocalPtyProvider } from '../providers/local-pty-provider'
+import {
+ createMockSubprocess,
+ startDaemonAdapterHarness,
+ waitFor
+} from '../daemon/daemon-pty-adapter-test-harness'
+import type { IPtyProvider } from '../providers/pty-provider-contract'
+import { PtyWriteUnavailableError } from '../providers/pty-write-unavailable-error'
+
+await import('./orca-runtime-test-mocks.spec')
+await import('./orca-runtime-test-lifecycle.spec')
+const { OrcaRuntimeService } = await import('./orca-runtime-test-mocks.spec')
+const {
+ HEADLESS_LEAF_ID,
+ TEST_WORKTREE_ID,
+ TEST_WORKTREE_PATH,
+ makeRuntimeStoreWithWorkspaceSession,
+ makeWorkspaceSessionWithHeadlessTerminal
+} = await import('./orca-runtime-test-fixtures.spec')
+
+const providerSession = { key: 'session_id' as const, id: 'codex-conversation' }
+
+function mobileChat(provider: IPtyProvider) {
+ const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(
+ makeWorkspaceSessionWithHeadlessTerminal()
+ )
+ const runtime = new OrcaRuntimeService(runtimeStore)
+ const spawn = vi.fn()
+ const write = vi.fn(() => true)
+ runtime.setPtyController({
+ spawn,
+ write,
+ kill: () => true,
+ getForegroundProcess: async () => null,
+ hasPty: (id) => provider.hasPty?.(id) ?? null,
+ getPtyAvailability: (id) => provider.getPtyAvailability?.(id) ?? null,
+ listProcesses: () => provider.listProcesses()
+ })
+ runtime.attachWindow(1)
+ let snapshotVersion = 0
+ const publish = (ptyId: string) =>
+ runtime.syncWindowGraph(1, {
+ tabs: [
+ {
+ tabId: 'host-tab',
+ worktreeId: TEST_WORKTREE_ID,
+ title: 'Codex',
+ activeLeafId: HEADLESS_LEAF_ID,
+ layout: null
+ }
+ ],
+ leaves: [
+ {
+ tabId: 'host-tab',
+ worktreeId: TEST_WORKTREE_ID,
+ leafId: HEADLESS_LEAF_ID,
+ paneRuntimeId: 1,
+ ptyId,
+ paneTitle: 'Codex'
+ }
+ ],
+ mobileSessionTabs: [
+ {
+ worktree: TEST_WORKTREE_ID,
+ publicationEpoch: 'renderer',
+ snapshotVersion: ++snapshotVersion,
+ activeGroupId: null,
+ activeTabId: 'host-tab',
+ activeTabType: 'terminal',
+ tabs: [
+ {
+ type: 'terminal',
+ id: `host-tab::${HEADLESS_LEAF_ID}`,
+ parentTabId: 'host-tab',
+ leafId: HEADLESS_LEAF_ID,
+ ptyId,
+ title: 'Codex',
+ isActive: true,
+ agentStatus: {
+ agentType: 'codex',
+ state: 'waiting',
+ prompt: '',
+ updatedAt: 1,
+ stateStartedAt: 1,
+ stateHistory: [],
+ paneKey: `host-tab:${HEADLESS_LEAF_ID}`,
+ providerSession
+ }
+ }
+ ]
+ }
+ ]
+ })
+ const read = () => runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)
+ const published = () => runtime['getMobileSessionTabsForWorktree'](TEST_WORKTREE_ID)
+ return { runtime, publish, read, published, spawn, write }
+}
+
+it.each(['direct', 'router', 'degraded'] as const)(
+ 'keeps an unattached retained conversation ready, then withholds a gone PTY through %s',
+ async (route) => {
+ const subprocesses: ReturnType<typeof createMockSubprocess>[] = []
+ const harness = await startDaemonAdapterHarness(() => {
+ const subprocess = createMockSubprocess()
+ subprocesses.push(subprocess)
+ return subprocess
+ })
+ const owner = new DaemonPtyAdapter(harness)
+ try {
+ await harness.adapter.spawn({
+ sessionId: 'persisted-pty',
+ cwd: TEST_WORKTREE_PATH,
+ cols: 80,
+ rows: 24
+ })
+ harness.adapter.dispose()
+ const provider =
+ route === 'direct'
+ ? owner
+ : route === 'router'
+ ? new DaemonPtyRouter({ current: owner, legacy: [] })
+ : new DegradedDaemonPtyProvider({
+ current: owner,
+ legacy: [],
+ fallback: new LocalPtyProvider()
+ })
+ const chat = mobileChat(provider)
+ chat.publish('persisted-pty')
+ const before = await chat.read()
+ expect(owner.hasPty('persisted-pty')).toBe(false)
+ expect(before.tabs[0]).toMatchObject({ status: 'ready', terminal: expect.any(String) })
+ const original = before.tabs[0]
+ if (original?.type !== 'terminal') {
+ throw new Error('Expected the retained terminal')
+ }
+
+ await owner.attach('persisted-pty')
+ expect((await chat.read()).tabs[0]).toHaveProperty('terminal', original.terminal)
+ expect(subprocesses).toHaveLength(1)
+ subprocesses[0]?._simulateExit(0)
+ await waitFor(() => !owner.hasPty('persisted-pty'))
+ expect((await chat.read()).tabs[0]).toMatchObject({
+ status: 'pending-handle',
+ terminal: null
+ })
+ chat.publish('persisted-pty')
+ expect(chat.published().tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null })
+
+ await owner.spawn({
+ sessionId: 'replacement-pty',
+ cwd: TEST_WORKTREE_PATH,
+ cols: 80,
+ rows: 24
+ })
+ chat.publish('replacement-pty')
+ const restored = (await chat.read()).tabs[0]
+ expect(restored).toMatchObject({
+ id: original.id,
+ status: 'ready',
+ terminal: expect.any(String),
+ agentStatus: expect.objectContaining({ providerSession })
+ })
+ expect(restored).not.toHaveProperty('terminal', original.terminal)
+ expect(chat.spawn).not.toHaveBeenCalled()
+ expect(chat.write).not.toHaveBeenCalled()
+ expect(subprocesses.every((subprocess) => subprocess.write.mock.calls.length === 0)).toBe(
+ true
+ )
+ } finally {
+ owner.dispose()
+ harness.adapter.dispose()
+ await harness.server.shutdown()
+ rmSync(harness.dir, { recursive: true, force: true })
+ }
+ }
+)
+
+it('withholds an attached PTY during endpoint recovery and restores its same conversation without replay', async () => {
+ const subprocess = createMockSubprocess()
+ const harness = await startDaemonAdapterHarness(() => subprocess)
+ const respawn = vi.fn(async () => {})
+ const owner = new DaemonPtyAdapter({ ...harness, respawn })
+ try {
+ await owner.spawn({ sessionId: 'persisted-pty', cwd: TEST_WORKTREE_PATH, cols: 80, rows: 24 })
+ const chat = mobileChat(owner)
+ chat.publish('persisted-pty')
+ const original = (await chat.read()).tabs[0]
+ if (original?.type !== 'terminal') {
+ throw new Error('Expected the attached terminal')
+ }
+ expect(original.status).toBe('ready')
+ const unavailable = new Promise<void>((resolve) => owner.onWriteUnavailable(() => resolve()))
+ owner['client'].disconnect()
+ expect(() => owner.write('persisted-pty', 'refused')).toThrow(PtyWriteUnavailableError)
+ await unavailable
+ expect(owner.hasPty('persisted-pty')).toBe(true)
+ expect(chat.published().tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null })
+
+ // Successful inventory reconnects transport but does not clear the remount fence.
+ expect((await chat.read()).tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null })
+ await owner.attach('persisted-pty')
+ expect((await chat.read()).tabs[0]).toMatchObject({
+ id: original.id,
+ status: 'ready',
+ terminal: original.terminal,
+ agentStatus: expect.objectContaining({ providerSession })
+ })
+ expect(subprocess.write).not.toHaveBeenCalled()
+ expect(chat.spawn).not.toHaveBeenCalled()
+ expect(chat.write).not.toHaveBeenCalled()
+ expect(respawn).not.toHaveBeenCalled()
+
+ respawn.mockRejectedValue(new Error('daemon remains unavailable'))
+ await harness.server.shutdown()
+ await waitFor(() => owner.getDaemonIdentity() === null)
+ expect((await chat.read()).tabs[0]).toMatchObject({ status: 'pending-handle', terminal: null })
+ expect(owner.hasPty('persisted-pty')).toBe(true)
+ expect(subprocess.write).not.toHaveBeenCalled()
+ expect(chat.spawn).not.toHaveBeenCalled()
+ } finally {
+ owner.dispose()
+ harness.adapter.dispose()
+ await harness.server.shutdown()
+ rmSync(harness.dir, { recursive: true, force: true })
+ }
+})
diff --git a/src/main/runtime/runtime-mobile-last-assistant-message.test.ts b/src/main/runtime/runtime-mobile-last-assistant-message.test.ts
index bf945e6f304..ffc25911a67 100644
--- a/src/main/runtime/runtime-mobile-last-assistant-message.test.ts
+++ b/src/main/runtime/runtime-mobile-last-assistant-message.test.ts
@@ -145,6 +145,7 @@ describe('mobile completion status projection', () => {
]
]),
ptysById: new Map([[pty.ptyId, pty]]),
+ getPtyAvailability: () => null,
getLiveBrowserTabs: () => new Map(),
getProviderSessionRows: () => [],
getProviderSessionSnapshot: () => [],
diff --git a/src/main/runtime/runtime-mobile-session-incarnation-projection.test.ts b/src/main/runtime/runtime-mobile-session-incarnation-projection.test.ts
index 1abf698debe..613e87031c8 100644
--- a/src/main/runtime/runtime-mobile-session-incarnation-projection.test.ts
+++ b/src/main/runtime/runtime-mobile-session-incarnation-projection.test.ts
@@ -18,6 +18,7 @@ it.each(['pty', 'leaf', 'unknown', 'disconnected'] as const)(
tabs: new Map(),
leaves: new Map(kind === 'leaf' ? [['leaf', { ptyId: pty.ptyId, connected: true }]] : []),
ptysById: new Map([[pty.ptyId, pty]]),
+ getPtyAvailability: () => null,
getLiveBrowserTabs: () => new Map(),
getProviderSessionRows: () => [],
getProviderSessionSnapshot: () => [],
diff --git a/src/main/runtime/runtime-mobile-session-projection-contract.ts b/src/main/runtime/runtime-mobile-session-projection-contract.ts
index a9d04f1bdf0..dc6012bbd63 100644
--- a/src/main/runtime/runtime-mobile-session-projection-contract.ts
+++ b/src/main/runtime/runtime-mobile-session-projection-contract.ts
@@ -17,6 +17,7 @@ export type RuntimeMobileSessionProjectionHost = {
tabs: ReadonlyMap<string, RuntimeSyncedTab>
leaves: ReadonlyMap<string, RuntimeLeafRecord>
ptysById: ReadonlyMap<string, RuntimePtyWorktreeRecord>
+ getPtyAvailability(ptyId: string): boolean | null
getLiveBrowserTabs(worktreeId: string): Map<string, BrowserTabInfo>
isRendererOwnedMobileBrowserTab(
snapshot: RuntimeMobileSessionTabsSnapshot,
diff --git a/src/main/runtime/runtime-mobile-session-projection.ts b/src/main/runtime/runtime-mobile-session-projection.ts
index 7d75109ec3f..3d6cf075c2f 100644
--- a/src/main/runtime/runtime-mobile-session-projection.ts
+++ b/src/main/runtime/runtime-mobile-session-projection.ts
@@ -92,6 +92,8 @@ export function projectRuntimeMobileSessionTabs(
}
// Claim each live PTY once or duplicate leaf keys crash client React.
const claimedLivePtyIds = new Set<string>()
+ const isPtyLive = (ptyId: string): boolean =>
+ host.getPtyAvailability(ptyId) ?? host.ptysById.get(ptyId)?.connected ?? false
for (const tab of snapshot.tabs) {
if (tab.type === 'browser') {
const liveTab = tab.browserPageId ? liveBrowserTabsByPageId.get(tab.browserPageId) : undefined
@@ -118,7 +120,7 @@ export function projectRuntimeMobileSessionTabs(
}
const syncedTab = host.tabs.get(tab.parentTabId)
const leaf = host.leaves.get(host.getLeafKey(tab.parentTabId, tab.leafId)) ?? null
- const liveLeaf = leaf?.ptyId && leaf.connected ? leaf : null
+ const liveLeaf = leaf?.ptyId && isPtyLive(leaf.ptyId) ? leaf : null
const liveLeafPtyId = liveLeaf?.ptyId ?? null
const liveLeafPty = liveLeafPtyId ? (host.ptysById.get(liveLeafPtyId) ?? null) : null
const pty = liveLeaf
@@ -126,7 +128,7 @@ export function projectRuntimeMobileSessionTabs(
: host.findPty(snapshot.worktree, tab, {
allowWorktreeOnlyMatch: !snapshot.publicationEpoch.startsWith('headless')
})
- const livePty = pty?.connected ? pty : null
+ const livePty = pty?.connected && isPtyLive(pty.ptyId) ? pty : null
// Drop later tabs sharing an already-claimed PTY so handles stay unique.
const resolvedLivePtyId = liveLeafPtyId ?? livePty?.ptyId ?? null
if (resolvedLivePtyId !== null) {
diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts
index 901f61dcf31..9017a10c7df 100644
--- a/src/main/runtime/runtime-pty-controller-contract.ts
+++ b/src/main/runtime/runtime-pty-controller-contract.ts
@@ -169,6 +169,7 @@ export type RuntimePtyController = {
resize?(ptyId: string, cols: number, rows: number): boolean
// Exact-id mobile polls must not enumerate every local/SSH PTY.
hasPty?(ptyId: string): boolean | null
+ getPtyAvailability?(ptyId: string): boolean | null
/** Omitting the host lists every registered host. */
listProcesses?(
hostId?: ExecutionHostId,
diff --git a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts
index de11fa0804e..43f1e844394 100644
--- a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts
+++ b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts
@@ -131,6 +131,7 @@ export abstract class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends Or
tabs: this.tabs,
leaves: this.leaves,
ptysById: this.ptysById,
+ getPtyAvailability: (ptyId) => this.ptyController?.getPtyAvailability?.(ptyId) ?? null,
getLiveBrowserTabs: (worktreeId) => this.getListedBrowserTabsByPageId(worktreeId),
isRendererOwnedMobileBrowserTab: (...args) => this.isRendererOwnedMobileBrowserTab(...args),
getProviderSessionRows: (paneKey) => this.getAgentProviderSessionRowsForPaneFn?.(paneKey),
@@ -298,10 +299,9 @@ export abstract class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends Or
paneKey: string
): AgentStatusOrchestrationContext | undefined {
const handle = this.getTerminalHandleForPaneKey(paneKey)
- if (!handle) {
- return undefined
- }
- return this.agentOrchestrationProjection.getForHandle(handle, undefined, { paneKey })
+ return handle
+ ? this.agentOrchestrationProjection.getForHandle(handle, undefined, { paneKey })
+ : undefined
}
getAgentStatusTerminalHandleForPaneKey(paneKey: string): string | undefined {
diff --git a/src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts b/src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts
index afd4646590c..26b69f20b1b 100644
--- a/src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts
+++ b/src/main/runtime/terminal/lifecycle/main-pane-liveness.test.ts
@@ -39,6 +39,7 @@ function hostController(host: Host, cwd: string, worktreeId: string) {
kill: () => true,
getForegroundProcess: async () => null,
hasPty: (ptyId: string) => host.live.has(ptyId),
+ getPtyAvailability: (ptyId: string) => host.live.has(ptyId),
listProcesses: async (providerKey?: string) =>
[...host.live]
.filter((id) => (id === SSH_PTY) === (providerKey === 'ssh:ssh-target'))
@@ -380,14 +381,14 @@ describe('a terminal registered while a listing is in flight (switch on)', () =>
})
describe('switch off: a window leaf still vouches for its terminal', () => {
- it('keeps a windowed pane connected when the inventory stops listing it', async () => {
+ it('keeps the window record but withholds a ready mobile handle when the host loses its PTY', async () => {
layoutOwner.isMain = false
const { runtime, host } = savedPaneHost('saved-pty', { windowed: true })
expect(await rowStatus(runtime, TEST_WORKTREE_ID)).toBe('ready')
host.live.clear()
- expect(await rowStatus(runtime, TEST_WORKTREE_ID)).toBe('ready')
+ expect(await rowStatus(runtime, TEST_WORKTREE_ID)).toBe('pending-handle')
expect(record(runtime, 'saved-pty')?.connected).toBe(true)
})
})