fix(remote-runtime): materialize the host surface when reconnecting a terminal pane (#11542)

Reconnect could never recover a terminal pane whose host-side process was gone (host restarted, or the workspace was never opened there): recovery only polled the tab inventory, which can never create the surface it is waiting for, so Reconnect spun for ~60s and gave up permanently.

Verified with a deterministic reproduction: on main the recovery path issues 51 inventory polls and zero activations across both an automatic online trigger and a manual Reconnect click; with this change the pane re-materializes, rebinds and accepts input.

Review found and fixed three further defects beyond the original change:
- an activation answered with a stale ready handle left the loop polling forever instead of re-activating;
- a non-missing activation failure (e.g. an older host without the method) never fell back to inventory;
- host-side, activating a parked surface permanently deleted the host tab, because an already-absent persisted binding was read as a competing owner *after* the destructive retirement had already run.

Independent review confirmed by mutation testing that every production change is covered by a test that fails when it is reverted, that only an authoritative inventory can retire a pane, that the loop is bounded under every failure mode, and that the unknown-liveness guard (proven death required before retirement) is intact.

Fixes STA-3002.
This commit is contained in:
PLANDER DEV 7
2026-08-04 22:59:06 -07:00
committed by GitHub
parent eebaf47df0
commit cbc005c8aa
7 changed files with 1028 additions and 40 deletions
+137
View File
@@ -9513,6 +9513,143 @@ describe('registerPtyHandlers', () => {
expect(store.flushOrThrow).toHaveBeenCalledOnce()
})
// Why: a parked pane (stopped with keepHistory) leaves the runtime holding the binding while
// persistence has already dropped it. Reading "nothing left to retire" as a competing owner
// aborted materialization *after* signalling the exit, which destroyed the pane instead of
// rebuilding it — the reconnect path then had no surface to attach to (#11541).
it('respawns a proven-dead owner whose persisted binding was already retired', async () => {
const worktreeId = 'repo-1::/tmp/already-retired-owner'
const cwd = '/tmp/already-retired-owner'
const tabId = 'tab-already-retired-owner'
const leafId = '89898989-8989-4989-8989-898989898989'
const paneKey = makePaneKey(tabId, leafId)
const providerSpawn = vi.fn(
async (options: { attachOnly?: boolean; command?: string; sessionId?: string }) => {
if (options.attachOnly) {
throw new Error('Session not found: pty-already-retired-owner')
}
return { id: 'pty-fresh-already-retired', incarnationId: 'inc-fresh-already-retired' }
}
)
const probePtyLiveness = vi.fn(async () => false)
setLocalPtyProvider({
spawn: providerSpawn,
probePtyLiveness,
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
shutdown: vi.fn(),
sendSignal: vi.fn(),
getCwd: vi.fn(),
getInitialCwd: vi.fn(),
clearBuffer: vi.fn(),
acknowledgeDataEvent: vi.fn(),
hasChildProcesses: vi.fn(),
getForegroundProcess: vi.fn(),
serialize: vi.fn(),
revive: vi.fn(),
onData: vi.fn(() => () => {}),
onReplay: vi.fn(() => () => {}),
onExit: vi.fn(() => () => {}),
listProcesses: vi.fn(async () => []),
attach: vi.fn(),
getDefaultShell: vi.fn(),
getProfiles: vi.fn()
} as never)
// Persistence kept the tab but already dropped this leaf's PTY binding, exactly as an
// earlier keep-history stop leaves it.
let session = {
tabsByWorktree: {
[worktreeId]: [{ id: tabId, worktreeId, ptyId: null }]
},
terminalLayoutsByTabId: {
[tabId]: {
root: { type: 'leaf' as const, leafId },
activeLeafId: leafId,
expandedLeafId: null,
ptyIdsByLeafId: {}
}
},
terminalPtyIncarnationsByPaneKey: {}
}
const store = {
getWorkspaceSession: vi.fn(() => session),
setWorkspaceSession: vi.fn((next) => {
session = next
}),
flushOrThrow: vi.fn(),
persistPtyBinding: vi.fn(),
getFolderWorkspace: vi.fn(() => undefined),
getFolderWorkspaces: vi.fn(() => []),
getProjectGroups: vi.fn(() => []),
getRepos: vi.fn(() => [])
}
let runtimeOwnsPane = true
const runtime = {
setPtyController: vi.fn(),
resolveTerminalPane: vi.fn(() => {
if (!runtimeOwnsPane) {
throw new Error('terminal_not_found')
}
return {
ptyId: 'pty-already-retired-owner',
tabId,
leafId,
handle: 'term-already-retired',
connected: true
}
}),
createPreAllocatedTerminalHandle: vi.fn(() => 'term-already-retired-fresh'),
preAllocateHandleForPty: vi.fn(() => 'term-already-retired-fresh'),
registerPreAllocatedHandleForPty: vi.fn(),
beginPtyRegistration: vi.fn(),
cancelPendingPtyRegistration: vi.fn(),
assertPtyRegistrationAllowed: vi.fn(),
registerPty: vi.fn(),
noteTerminalSpawnCommand: vi.fn(),
seedHeadlessTerminal: vi.fn(),
onPtySpawned: vi.fn(),
// Why: the real runtime drops its pane binding on exit; the guard after retirement must
// see that release rather than a resurrected owner.
onPtyExit: vi.fn(() => {
runtimeOwnsPane = false
}),
onPtyData: vi.fn()
}
registerPtyHandlers(
mainWindow as never,
runtime as never,
undefined,
undefined,
undefined,
store as never
)
const mounted = await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd,
command: 'codex resume already-retired-session',
worktreeId,
tabId,
leafId,
env: {
ORCA_PANE_KEY: paneKey,
ORCA_TAB_ID: tabId,
ORCA_WORKTREE_ID: worktreeId
}
})
expect(probePtyLiveness).toHaveBeenCalledWith('pty-already-retired-owner')
expect(mounted).toMatchObject({ id: 'pty-fresh-already-retired' })
expect(providerSpawn).toHaveBeenCalledTimes(2)
expect(providerSpawn.mock.calls[1]?.[0]).toMatchObject({
command: 'codex resume already-retired-session'
})
expect(runtime.onPtyExit).toHaveBeenCalledWith('pty-already-retired-owner', 0, undefined)
})
it('retires a dead owner from the exact SSH host session before fresh recovery', async () => {
const connectionId = 'ssh-dead-stable-pane'
const hostId = `ssh:${connectionId}`
+7 -1
View File
@@ -712,7 +712,13 @@ function retirePersistedStablePaneOwner(
const paneKey = makePaneKey(owner.tabId, owner.leafId)
const hostId = connectionId ? toSshExecutionHostId(connectionId) : undefined
const current = resolvePersistedStablePaneOwner(store, paneKey, worktreeId, connectionId)
if (current?.ptyId !== owner.ptyId || current.incarnationId !== owner.incarnationId) {
if (!current) {
// Why: persistence already dropped this pane binding (an earlier stop retired it while the
// runtime kept history), so there is nothing left to clear — that is a completed retirement,
// not a competing owner. Reporting failure here strands the pane after its PTY is proven dead.
return true
}
if (current.ptyId !== owner.ptyId || current.incarnationId !== owner.incarnationId) {
return false
}
const session = store.getWorkspaceSession(hostId)
@@ -1646,6 +1646,10 @@ describe('createRemoteRuntimePtyTransport', () => {
let hostListCalls = 0
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'session.tabs.activate') {
// Why: this host publishes the replacement only through its own inventory, so activation answers with nothing.
return { ok: true, result: { tabs: [] } }
}
if (args.method === 'session.tabs.list') {
hostListCalls += 1
if (hostListCalls === 1) {
@@ -1694,7 +1698,7 @@ describe('createRemoteRuntimePtyTransport', () => {
expect(onPtyExit).not.toHaveBeenCalled()
await vi.waitFor(
() => expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-reconnected' }),
{ timeout: 2_000 }
{ timeout: 6_000 }
)
const replacementStreamId = latestSubscribePayload().streamId
emitSnapshot(replacementStreamId, draft)
@@ -1723,6 +1727,7 @@ describe('createRemoteRuntimePtyTransport', () => {
return payload ? [payload.terminal] : []
})
expect(subscribedTerminals).toEqual(['terminal-stale', 'terminal-reconnected'])
transport.destroy?.()
})
it('reattaches from a later host snapshot after bounded replacement polling stops', async () => {
@@ -1798,11 +1803,14 @@ describe('createRemoteRuntimePtyTransport', () => {
expect(hostListCalls).toBeGreaterThan(1)
expect(hostListCalls).toBeLessThan(25)
// The reconnect opens with a materialize (session.tabs.activate) and then
// polls the inventory, so the first list runs one backoff into the budget.
const listTimeouts = runtimeCall.mock.calls
.map(([args]) => args)
.filter((args) => args.method === 'session.tabs.list')
.map((args) => args.timeoutMs as number)
expect(listTimeouts[0]).toBe(15_000)
expect(listTimeouts[0]).toBeGreaterThan(14_000)
expect(listTimeouts[0]).toBeLessThanOrEqual(15_000)
expect(listTimeouts.every((timeoutMs) => timeoutMs > 0 && timeoutMs <= 15_000)).toBe(true)
expect(listTimeouts.at(-1)).toBeLessThanOrEqual(1_000)
expect(onError).not.toHaveBeenCalled()
@@ -1875,6 +1883,379 @@ describe('createRemoteRuntimePtyTransport', () => {
}
})
it('materializes a host surface whose PTY died instead of polling a dead inventory', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const onPtyExit = vi.fn()
const onPtyRebind = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-tab-1',
leafId: 'pane:1',
onPtyExit,
onPtyRebind
})
resolvedPaneHandle = 'terminal-before-restart'
transport.attach({
existingPtyId: 'remote:env-1@@terminal-before-restart',
cols: 80,
rows: 24,
callbacks: { onError }
})
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
const activateCalls = (): {
method: string
params?: { tabId?: string; leafId?: string }
}[] =>
runtimeCall.mock.calls
.map(([args]) => args)
.filter((args) => args.method === 'session.tabs.activate')
const activateCallsBeforeStale = activateCalls().length
// The host still publishes the surface, but only activation can mint its replacement handle.
let materialized = false
const hostSnapshot = (): unknown => ({
worktree: 'wt-1',
publicationEpoch: 'epoch-2',
snapshotVersion: materialized ? 3 : 2,
activeGroupId: null,
activeTabId: 'tab-1::pane:1',
activeTabType: 'terminal',
tabs: [
{
type: 'terminal',
id: 'tab-1::pane:1',
parentTabId: 'tab-1',
leafId: 'pane:1',
title: 'Claude Code',
isActive: true,
...(materialized
? { status: 'ready', terminal: 'terminal-after-restart' }
: { status: 'pending-handle', terminal: null })
}
]
})
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'session.tabs.activate') {
materialized = true
return { ok: true, result: hostSnapshot() }
}
if (args.method === 'session.tabs.list') {
return { ok: true, result: hostSnapshot() }
}
return { ok: true, result: {} }
})
subscriptionCallbacks?.onResponse({
ok: true,
result: {
type: 'error',
streamId: latestSubscribePayload().streamId,
message: 'terminal_handle_stale'
}
})
await vi.advanceTimersByTimeAsync(1_000)
expect(activateCalls().length).toBeGreaterThan(activateCallsBeforeStale)
expect(activateCalls().at(-1)?.params).toMatchObject({
tabId: 'tab-1',
leafId: 'pane:1',
notifyClients: false,
navigation: 'caller'
})
await vi.waitFor(() =>
expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-after-restart' })
)
expect(onPtyRebind).toHaveBeenCalledWith(
'remote:env-1@@terminal-after-restart',
'remote:env-1@@terminal-before-restart'
)
expect(onPtyExit).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('re-activates when a stale ready activation response precedes the pending surface', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const onPtyExit = vi.fn()
const onPtyRebind = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-tab-1',
leafId: 'pane:1',
onPtyExit,
onPtyRebind
})
resolvedPaneHandle = 'terminal-before-restart'
transport.attach({
existingPtyId: 'remote:env-1@@terminal-before-restart',
callbacks: { onError }
})
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
runtimeCall.mockClear()
let activateCalls = 0
const snapshot = (terminal: string | null): unknown => ({
worktree: 'wt-1',
publicationEpoch: 'epoch-2',
snapshotVersion: activateCalls + 2,
activeGroupId: null,
activeTabId: 'tab-1::pane:1',
activeTabType: 'terminal',
tabs: [
{
type: 'terminal',
id: 'tab-1::pane:1',
parentTabId: 'tab-1',
leafId: 'pane:1',
title: 'Terminal',
isActive: true,
...(terminal
? { status: 'ready', terminal }
: { status: 'pending-handle', terminal: null })
}
]
})
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'session.tabs.activate') {
activateCalls += 1
// Why: the first activation races host publication and answers with the pre-restart handle.
return {
ok: true,
result: snapshot(
activateCalls === 1 ? 'terminal-before-restart' : 'terminal-after-restart'
)
}
}
if (args.method === 'session.tabs.list') {
return { ok: true, result: snapshot(null) }
}
return { ok: true, result: {} }
})
subscriptionCallbacks?.onResponse({
ok: true,
result: {
type: 'error',
streamId: latestSubscribePayload().streamId,
message: 'terminal_handle_stale'
}
})
await vi.advanceTimersByTimeAsync(2_000)
expect(
runtimeCall.mock.calls
.map(([args]) => args.method)
.filter((method) => method === 'session.tabs.activate' || method === 'session.tabs.list')
).toEqual(['session.tabs.activate', 'session.tabs.list', 'session.tabs.activate'])
await vi.waitFor(() =>
expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-after-restart' })
)
expect(onPtyRebind).toHaveBeenCalledWith(
'remote:env-1@@terminal-after-restart',
'remote:env-1@@terminal-before-restart'
)
expect(onPtyExit).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
transport.destroy?.()
} finally {
vi.useRealTimers()
}
})
it('falls back to inventory when activation fails for a non-missing reason', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const onPtyExit = vi.fn()
const onPtyRebind = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-tab-1',
leafId: 'pane:1',
onPtyExit,
onPtyRebind
})
resolvedPaneHandle = 'terminal-before-restart'
transport.attach({
existingPtyId: 'remote:env-1@@terminal-before-restart',
callbacks: { onError }
})
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
runtimeCall.mockClear()
const replacementSnapshot = {
worktree: 'wt-1',
publicationEpoch: 'epoch-2',
snapshotVersion: 2,
activeGroupId: null,
activeTabId: 'tab-1::pane:1',
activeTabType: 'terminal',
tabs: [
{
type: 'terminal',
id: 'tab-1::pane:1',
parentTabId: 'tab-1',
leafId: 'pane:1',
title: 'Terminal',
isActive: true,
status: 'ready',
terminal: 'terminal-after-restart'
}
]
}
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'session.tabs.activate') {
// Why: an older host has no activation method at all, which is not evidence the surface is gone.
return { ok: false, error: { code: 'method_not_found', message: 'Unknown method' } }
}
if (args.method === 'session.tabs.list') {
return { ok: true, result: replacementSnapshot }
}
return { ok: true, result: {} }
})
subscriptionCallbacks?.onResponse({
ok: true,
result: {
type: 'error',
streamId: latestSubscribePayload().streamId,
message: 'terminal_handle_stale'
}
})
await vi.advanceTimersByTimeAsync(1_000)
expect(
runtimeCall.mock.calls
.map(([args]) => args.method)
.filter((method) => method === 'session.tabs.activate' || method === 'session.tabs.list')
).toEqual(['session.tabs.activate', 'session.tabs.list'])
await vi.waitFor(() =>
expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-after-restart' })
)
expect(onPtyRebind).toHaveBeenCalledWith(
'remote:env-1@@terminal-after-restart',
'remote:env-1@@terminal-before-restart'
)
expect(onPtyExit).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
transport.destroy?.()
} finally {
vi.useRealTimers()
}
})
it('retries activation when inventory disproves a transient missing-surface response', async () => {
vi.useFakeTimers()
try {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onError = vi.fn()
const onPtyExit = vi.fn()
const onPtyRebind = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-tab-1',
leafId: 'pane:1',
onPtyExit,
onPtyRebind
})
resolvedPaneHandle = 'terminal-before-restart'
transport.attach({
existingPtyId: 'remote:env-1@@terminal-before-restart',
callbacks: { onError }
})
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
runtimeCall.mockClear()
let activateCalls = 0
const pendingSnapshot = {
worktree: 'wt-1',
publicationEpoch: 'epoch-2',
snapshotVersion: 2,
activeGroupId: null,
activeTabId: 'tab-1::pane:1',
activeTabType: 'terminal',
tabs: [
{
type: 'terminal',
id: 'tab-1::pane:1',
parentTabId: 'tab-1',
leafId: 'pane:1',
title: 'Terminal',
isActive: true,
status: 'pending-handle',
terminal: null
}
]
}
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method === 'session.tabs.activate') {
activateCalls += 1
if (activateCalls === 1) {
return { ok: false, error: { code: 'runtime_error', message: 'tab_not_found' } }
}
return {
ok: true,
result: {
...pendingSnapshot,
snapshotVersion: 3,
tabs: [
{
...pendingSnapshot.tabs[0],
status: 'ready',
terminal: 'terminal-after-restart'
}
]
}
}
}
if (args.method === 'session.tabs.list') {
return { ok: true, result: pendingSnapshot }
}
return { ok: true, result: {} }
})
subscriptionCallbacks?.onResponse({
ok: true,
result: {
type: 'error',
streamId: latestSubscribePayload().streamId,
message: 'terminal_handle_stale'
}
})
await vi.advanceTimersByTimeAsync(2_000)
expect(
runtimeCall.mock.calls
.map(([args]) => args.method)
.filter((method) => method === 'session.tabs.activate' || method === 'session.tabs.list')
).toEqual(['session.tabs.activate', 'session.tabs.list', 'session.tabs.activate'])
await vi.waitFor(() =>
expect(latestSubscribePayload()).toMatchObject({ terminal: 'terminal-after-restart' })
)
expect(onPtyRebind).toHaveBeenCalledWith(
'remote:env-1@@terminal-after-restart',
'remote:env-1@@terminal-before-restart'
)
expect(onPtyExit).not.toHaveBeenCalled()
expect(onError).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot', async () => {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const handleEvents = await import('../../runtime/web-session-terminal-handle-events')
@@ -2691,7 +3072,7 @@ describe('createRemoteRuntimePtyTransport', () => {
emitSnapshot(staleStreamId, 'before stale handle')
runtimeCall.mockImplementation(async (args: { method: string }) => {
if (args.method !== 'session.tabs.list') {
if (args.method !== 'session.tabs.activate' && args.method !== 'session.tabs.list') {
return { ok: true, result: {} }
}
return {
@@ -498,6 +498,30 @@ export function createRemoteRuntimePtyTransport(
)
}
// Why: pending host surfaces materialize only through activation.
function activateHostSessionSurface(
hostTabId: string,
worktree: string,
timeoutMs?: number
): Promise<RuntimeMobileSessionTabsResult> {
return callRuntime<RuntimeMobileSessionTabsResult>(
'session.tabs.activate',
{
worktree,
tabId: hostTabId,
...(leafId ? { leafId } : {}),
notifyClients: false,
navigation: 'caller'
},
timeoutMs
)
}
function isMissingHostSessionSurfaceError(error: unknown): boolean {
const message = runtimeTerminalErrorMessage(error)
return message.includes('tab_not_found') || message.includes('terminal_not_found')
}
async function waitForHostSessionHandle(
hostTabId: string,
isCurrent: () => boolean
@@ -508,16 +532,9 @@ export function createRemoteRuntimePtyTransport(
const worktree = toRuntimeWorktreeSelector(worktreeId)
let activated: RuntimeMobileSessionTabsResult
try {
activated = await callRuntime<RuntimeMobileSessionTabsResult>('session.tabs.activate', {
worktree,
tabId: hostTabId,
...(leafId ? { leafId } : {}),
notifyClients: false,
navigation: 'caller'
})
activated = await activateHostSessionSurface(hostTabId, worktree)
} catch (error) {
const message = runtimeTerminalErrorMessage(error)
if (message.includes('tab_not_found') || message.includes('terminal_not_found')) {
if (isMissingHostSessionSurfaceError(error)) {
return null
}
throw error
@@ -634,9 +651,10 @@ export function createRemoteRuntimePtyTransport(
const worktree = toRuntimeWorktreeSelector(worktreeId)
const startedAt = Date.now()
let pollMs = HOST_SESSION_ATTACH_POLL_MS
let lastListError: unknown = null
// Why: list-only polling cannot recreate a host PTY lost across desktop generations.
let nextRequest: 'activate' | 'list' = 'activate'
let lastRequestError: unknown = null
let lastReadyHandle: string | null = null
let sawSuccessfulInventory = false
const finishBoundedWait = (): HostSessionHandleWaitResult => {
const effectivePolicy = stricterReplacementPolicy(
replacementPolicy,
@@ -645,16 +663,14 @@ export function createRemoteRuntimePtyTransport(
if (effectivePolicy === 'prefer-replacement' && lastReadyHandle) {
return { handle: lastReadyHandle, inventoryFailed: false }
}
if (lastListError) {
if (lastRequestError) {
console.warn(
sawSuccessfulInventory
? '[remote-runtime-pty] final host session inventory poll failed during reconnect:'
: '[remote-runtime-pty] host session inventory unavailable during reconnect:',
runtimeTerminalErrorMessage(lastListError)
'[remote-runtime-pty] host session recovery request failed during reconnect:',
runtimeTerminalErrorMessage(lastRequestError)
)
}
// Why: a bounded wait without removal evidence is unknown liveness; keep the pane for a later snapshot to reattach.
return { handle: undefined, inventoryFailed: lastListError !== null }
return { handle: undefined, inventoryFailed: lastRequestError !== null }
}
while (
!destroyed &&
@@ -666,21 +682,24 @@ export function createRemoteRuntimePtyTransport(
if (requestRemainingMs <= 0) {
return finishBoundedWait()
}
const request = nextRequest
try {
const listed = await listRemoteRuntimeSessionTabsDeduped({
environmentId: currentRuntimeEnvironmentId,
worktreeId,
load: () =>
callRuntime<RuntimeMobileSessionTabsResult>(
'session.tabs.list',
{
worktree
},
requestRemainingMs
)
})
lastListError = null
sawSuccessfulInventory = true
const listed =
request === 'list'
? await listRemoteRuntimeSessionTabsDeduped({
environmentId: currentRuntimeEnvironmentId,
worktreeId,
load: () =>
callRuntime<RuntimeMobileSessionTabsResult>(
'session.tabs.list',
{
worktree
},
requestRemainingMs
)
})
: await activateHostSessionSurface(hostTabId, worktree, requestRemainingMs)
lastRequestError = null
const nextHandle = findReadyHostSessionHandle(listed, hostTabId)
if (nextHandle) {
lastReadyHandle = nextHandle
@@ -692,12 +711,25 @@ export function createRemoteRuntimePtyTransport(
if (nextHandle && (effectivePolicy === 'reuse' || nextHandle !== previousHandle)) {
return { handle: nextHandle, inventoryFailed: false }
}
if (!hasHostSessionTerminalSurface(listed, hostTabId)) {
return { handle: null, inventoryFailed: false }
if (request === 'list') {
if (!hasHostSessionTerminalSurface(listed, hostTabId)) {
return { handle: null, inventoryFailed: false }
}
if (!nextHandle) {
// Why: the surface is published but unmaterialized, and only activation can mint its PTY.
nextRequest = 'activate'
}
} else {
// Why: an activation response can race host publication, so inventory — not this snapshot — decides what exists.
nextRequest = 'list'
}
} catch (error) {
// Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane.
lastListError = error
lastRequestError = error
if (request === 'activate') {
// Why: no activation failure is absence proof, whether the surface is missing or the host predates the method.
nextRequest = 'list'
}
}
const remainingMs = HOST_SESSION_ATTACH_TIMEOUT_MS - (Date.now() - startedAt)
if (remainingMs <= 0) {
@@ -178,7 +178,9 @@ type E2eRemoteTerminalMultiplexAckGateSnapshot = {
type E2eRemoteTerminalMultiplexAckGateApi = {
dropOutputUntilResubscribe: (terminals: string[]) => number
forceError: (terminals: string[], message: string) => number
hold: (terminals: string[]) => void
holdEnd: (terminals: string[]) => void
release: () => void
sendInput: (terminal: string, text: string) => number
snapshot: () => E2eRemoteTerminalMultiplexAckGateSnapshot
@@ -189,6 +191,7 @@ type E2eRemoteTerminalMultiplexAckGateWindow = Window & {
}
const e2eHeldRemoteAckTerminals = new Set<string>()
const e2eHeldRemoteEndTerminals = new Set<string>()
const e2eDroppedOutputStreams = new Set<RemoteRuntimeMultiplexedTerminalState>()
let e2eDroppedOutputBytes = 0
let e2eDroppedOutputFrames = 0
@@ -262,15 +265,30 @@ function exposeE2eRemoteTerminalMultiplexAckGate(): void {
}
return e2eDroppedOutputStreams.size
},
forceError: (terminals, message) => {
let dispatched = 0
const targets = new Set(terminals)
for (const multiplexer of multiplexers.values()) {
dispatched += multiplexer.forceErrorForE2e(targets, message)
}
return dispatched
},
hold: (terminals) => {
releaseE2eRemoteTerminalAcks()
for (const terminal of terminals) {
e2eHeldRemoteAckTerminals.add(terminal)
}
},
holdEnd: (terminals) => {
e2eHeldRemoteEndTerminals.clear()
for (const terminal of terminals) {
e2eHeldRemoteEndTerminals.add(terminal)
}
},
release: () => {
releaseE2eRemoteTerminalAcks()
resetE2eDroppedRemoteOutput()
e2eHeldRemoteEndTerminals.clear()
},
sendInput: (terminal, value) => {
let sent = 0
@@ -544,6 +562,13 @@ class RemoteRuntimeTerminalMultiplexer {
return
}
stream.watchdog.recordInbound()
if (
event.type === 'end' &&
e2eConfig.exposeStore &&
e2eHeldRemoteEndTerminals.has(stream.terminal)
) {
return
}
if (event.type === 'subscribed') {
const capabilities =
typeof event.capabilities === 'object' && event.capabilities !== null
@@ -1185,6 +1210,17 @@ class RemoteRuntimeTerminalMultiplexer {
return this.streams.values()
}
forceErrorForE2e(terminals: ReadonlySet<string>, message: string): number {
let dispatched = 0
for (const stream of this.streams.values()) {
if (terminals.has(stream.terminal)) {
stream.callbacks.onError?.(message)
dispatched += 1
}
}
return dispatched
}
releaseHeldAcksForE2e(): number {
let released = 0
for (const stream of this.streams.values()) {