diff --git a/src/main/ipc/pty/runtime/controller.ts b/src/main/ipc/pty/runtime/controller.ts index 4013e06e37fa..8dd45a76541f 100644 --- a/src/main/ipc/pty/runtime/controller.ts +++ b/src/main/ipc/pty/runtime/controller.ts @@ -28,6 +28,7 @@ import { writePtyFromRuntimeController } from './operations' import { recordUnconfirmedExplicitSshStop } from './undelivered-ssh-kill' +import { requestPtyRedrawFromRuntimeController } from './pty-redraw' import { supportsForegroundProcessEvidenceFromRuntimeController } from './foreground-process-evidence-capability' import { listProcessesFromRuntimeController, @@ -91,6 +92,7 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi waitForRendererSerializer: (ptyId, afterGeneration, timeoutMs, signal) => waitForRendererSerializerFromRuntimeController(ptyId, afterGeneration, timeoutMs, signal), getSize: (ptyId) => getSizeFromRuntimeController(ptyId), - resize: (ptyId, cols, rows) => resizePtyFromRuntimeController(ptyId, cols, rows) + resize: (ptyId, cols, rows) => resizePtyFromRuntimeController(ptyId, cols, rows), + requestRedraw: requestPtyRedrawFromRuntimeController }) } diff --git a/src/main/ipc/pty/runtime/pty-redraw.test.ts b/src/main/ipc/pty/runtime/pty-redraw.test.ts new file mode 100644 index 000000000000..98f5b2ebcaaf --- /dev/null +++ b/src/main/ipc/pty/runtime/pty-redraw.test.ts @@ -0,0 +1,38 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { requestPtyRedrawFromRuntimeController } from './pty-redraw' + +const { getProviderForPty, sendSignal } = vi.hoisted(() => ({ + getProviderForPty: vi.fn(), + sendSignal: vi.fn() +})) +vi.mock('../provider/registry', () => ({ getProviderForPty })) + +describe('execution-host PTY redraw', () => { + beforeEach(() => { + vi.resetAllMocks() + getProviderForPty.mockReturnValue({ sendSignal }) + sendSignal.mockResolvedValue(undefined) + }) + + it.each(['daemon-pane', 'ssh:connection-1:pty-1'])( + 'routes %s through its provider', + async (id) => { + expect(await requestPtyRedrawFromRuntimeController(id)).toBe(true) + expect(getProviderForPty).toHaveBeenCalledExactlyOnceWith(id) + expect(sendSignal).toHaveBeenCalledExactlyOnceWith(id, 'SIGWINCH') + } + ) + + it('does not substitute a local provider when the execution host is unavailable', async () => { + getProviderForPty.mockImplementation(() => { + throw new Error('provider unavailable') + }) + expect(await requestPtyRedrawFromRuntimeController('ssh:connection-1:pty-1')).toBe(false) + expect(sendSignal).not.toHaveBeenCalled() + }) + + it('treats an unsupported or failed signal as best-effort', async () => { + sendSignal.mockRejectedValue(new Error('signal unsupported')) + expect(await requestPtyRedrawFromRuntimeController('daemon-pane')).toBe(false) + }) +}) diff --git a/src/main/ipc/pty/runtime/pty-redraw.ts b/src/main/ipc/pty/runtime/pty-redraw.ts new file mode 100644 index 000000000000..b28b8f08f4be --- /dev/null +++ b/src/main/ipc/pty/runtime/pty-redraw.ts @@ -0,0 +1,11 @@ +import { getProviderForPty } from '../provider/registry' + +export async function requestPtyRedrawFromRuntimeController(ptyId: string): Promise { + try { + // The provider routes SIGWINCH to the foreground group on the execution host. + await getProviderForPty(ptyId).sendSignal(ptyId, 'SIGWINCH') + return true + } catch { + return false + } +} diff --git a/src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts b/src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts index 53a9b4ffc59c..368e5c80a9b0 100644 --- a/src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts +++ b/src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts @@ -90,6 +90,22 @@ export class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRuntimeWithA return { handle, reset: true } } + async requestTerminalRedraw( + handle: string, + viewport: { cols: number; rows: number } + ): Promise { + // Re-resolve after the viewport await: a replacement or mobile takeover invalidates the kick. + const leaf = this.resolveLiveLeafForHandle(handle) + if (!leaf?.ptyId || this.getDriver(leaf.ptyId).kind === 'mobile') { + return false + } + const size = this.getTerminalSize(leaf.ptyId) + if (size?.cols !== viewport.cols || size.rows !== viewport.rows) { + return false + } + return (await this.ptyController?.requestRedraw?.(leaf.ptyId)) ?? false + } + getTerminalSize(ptyId: string): { cols: number; rows: number } | null { return this.ptyController?.getSize?.(ptyId) ?? null } diff --git a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts index b977c1136681..d2adafd79797 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts @@ -62,6 +62,7 @@ export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [ if (!leaf?.ptyId) { throw new Error('no_connected_pty') } + const previousSize = params.redraw ? runtime.getTerminalSize(leaf.ptyId) : null const viewportUpdate = await updateViewportForClient( runtime, leaf.ptyId, @@ -73,6 +74,15 @@ export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [ 'refresh', params.claim === true ) + if ( + params.redraw === true && + params.client.type === 'desktop' && + viewportUpdate.applied && + previousSize?.cols === params.viewport.cols && + previousSize.rows === params.viewport.rows + ) { + await runtime.requestTerminalRedraw(params.terminal, params.viewport) + } return { ...viewportUpdate, seq: runtime.getLayout(leaf.ptyId)?.seq } } }) diff --git a/src/main/runtime/rpc/terminal-reattach-redraw.test.ts b/src/main/runtime/rpc/terminal-reattach-redraw.test.ts new file mode 100644 index 000000000000..9e3c45224394 --- /dev/null +++ b/src/main/runtime/rpc/terminal-reattach-redraw.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../orca-runtime' +import { RpcDispatcher } from './dispatcher' +import { TERMINAL_METHODS } from './methods/terminal' + +function createRedrawRuntime(initialSize = { cols: 80, rows: 24 }) { + const runtime = new OrcaRuntimeService() + const requestRedraw = vi.fn(async () => true) + let size = initialSize + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => size, + requestRedraw + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These handlers read only ptyId from the resolved leaf. + const leaf = { ptyId: 'pty-1' } as NonNullable< + ReturnType + > + const resolve = vi.spyOn(runtime, 'resolveLiveLeafForHandle').mockReturnValue(leaf) + const refresh = vi.spyOn(runtime, 'refreshRemoteDesktopViewer').mockResolvedValue(true) + vi.spyOn(runtime, 'getLayout').mockReturnValue(null) + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const update = (extra: { redraw?: boolean; claim?: boolean } = { redraw: true }) => + dispatcher.dispatch({ + id: 'req-1', + authToken: 'token', + method: 'terminal.updateViewport', + params: { + terminal: 'terminal-1', + client: { id: 'client-1', type: 'desktop' }, + viewport: initialSize, + ...extra + } + }) + return { + runtime, + requestRedraw, + resolve, + refresh, + update, + setSize: (next: typeof size) => { + size = next + } + } +} + +describe('remote reattach redraw through the existing viewport RPC', () => { + it('kicks an unchanged grid once without claiming control', async () => { + const { update, requestRedraw, refresh } = createRedrawRuntime() + expect((await update()).ok).toBe(true) + expect(requestRedraw).toHaveBeenCalledExactlyOnceWith('pty-1') + expect(refresh).toHaveBeenCalledWith('pty-1', 'client-1', 80, 24, false) + }) + + it.each([ + { cols: 20, rows: 8 }, + { cols: 240, rows: 120 } + ])('kicks an unchanged host-clamped $cols×$rows grid', async (viewport) => { + const { update, requestRedraw } = createRedrawRuntime(viewport) + expect((await update()).ok).toBe(true) + expect(requestRedraw).toHaveBeenCalledExactlyOnceWith('pty-1') + }) + + it('leaves ordinary viewport updates unchanged', async () => { + const { update, requestRedraw } = createRedrawRuntime() + expect((await update({})).ok).toBe(true) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('does not double-signal a real geometry change', async () => { + const { update, requestRedraw, setSize, refresh } = createRedrawRuntime() + setSize({ cols: 100, rows: 30 }) + refresh.mockImplementation(async () => { + setSize({ cols: 80, rows: 24 }) + return true + }) + expect((await update()).ok).toBe(true) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('does not kick a viewer whose stream has gone away', async () => { + const { update, requestRedraw, refresh } = createRedrawRuntime() + refresh.mockResolvedValue(false) + expect((await update()).ok).toBe(true) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('rechecks mobile ownership after the viewport await', async () => { + const { runtime, update, requestRedraw, refresh } = createRedrawRuntime() + refresh.mockImplementation(async () => { + runtime.markMobileActor('pty-1', 'phone-1') + return true + }) + expect((await update()).ok).toBe(true) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('rechecks the applied grid after the viewport await', async () => { + const { update, requestRedraw, refresh, setSize } = createRedrawRuntime() + refresh.mockImplementation(async () => { + setSize({ cols: 100, rows: 30 }) + return true + }) + expect((await update()).ok).toBe(true) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('refuses a replaced handle after the viewport await', async () => { + const { update, requestRedraw, resolve, refresh } = createRedrawRuntime() + refresh.mockImplementation(async () => { + resolve.mockImplementation(() => { + throw new Error('terminal_handle_stale') + }) + return true + }) + expect((await update()).ok).toBe(false) + expect(requestRedraw).not.toHaveBeenCalled() + }) + + it('degrades safely when the controller cannot request redraw', async () => { + const { runtime, update } = createRedrawRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => ({ cols: 80, rows: 24 }) + }) + expect((await update()).ok).toBe(true) + }) +}) diff --git a/src/main/runtime/runtime-pty-controller-contract.ts b/src/main/runtime/runtime-pty-controller-contract.ts index 60c1e18cf10a..013447607751 100644 --- a/src/main/runtime/runtime-pty-controller-contract.ts +++ b/src/main/runtime/runtime-pty-controller-contract.ts @@ -126,6 +126,7 @@ export type RuntimePtyController = { clearBuffer?(ptyId: string): Promise resetInputModes?(ptyId: string): Promise resize?(ptyId: string, cols: number, rows: number): boolean + requestRedraw?(ptyId: string): Promise // Why: exact-id mobile polls should not enumerate every local and SSH PTY. hasPty?(ptyId: string): boolean | null listProcesses?( diff --git a/src/main/runtime/terminal-viewport.ts b/src/main/runtime/terminal-viewport.ts index 3130f9a1a06a..efffe04a9d85 100644 --- a/src/main/runtime/terminal-viewport.ts +++ b/src/main/runtime/terminal-viewport.ts @@ -1,7 +1 @@ -// Clamp terminal dimensions to the PTY's supported range (cols 20–240, rows 8–120). -export function clampTerminalViewport(cols: number, rows: number): { cols: number; rows: number } { - return { - cols: Math.max(20, Math.min(240, Math.round(cols))), - rows: Math.max(8, Math.min(120, Math.round(rows))) - } -} +export { clampTerminalViewport } from '../../shared/terminal-viewport' diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker-contract.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker-contract.ts new file mode 100644 index 000000000000..7ba92dae96db --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker-contract.ts @@ -0,0 +1,47 @@ +import type { RecognizedAgentProcess } from '../../../../shared/agent-process-recognition' +import type { TuiAgent } from '../../../../shared/tui-agent' +import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' +import type { RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection' + +export type PaneForegroundAgentTrackerDeps = { + getPtyId: () => string | null + /** Local panes only — remote/SSH foreground reads are expensive RPCs and + * their replayed OSC streams must not produce process evidence. */ + isTrackablePtyId: (ptyId: string) => boolean + readForegroundProcess: ( + ptyId: string, + options?: { expectedIncarnationId?: string } + ) => Promise + /** Fresh, provider-owned evidence used only when input routing may change. */ + confirmForegroundProcess?: ( + ptyId: string, + options?: { expectedIncarnationId?: string } + ) => Promise + /** Remote authorities must provide fenced evidence; local panes retain the string path. */ + isRemotePtyId?: (ptyId: string) => boolean + getExpectedIncarnationId?: () => string | null + publish: (entry: PaneForegroundAgentEntry) => void + /** The entry currently published for this pane, whoever wrote it. */ + getPublishedEntry?: () => PaneForegroundAgentEntry | undefined + /** A local read recognized an agent; lets the pane's process monitor watch for its exit. */ + onAgentProcessRead?: (process: RecognizedAgentProcess) => void + /** Launch/hook evidence retained until a foreground read confirms ownership. */ + hasKnownAgentIdentity?: () => boolean + /** Clears an agent title only after a confirmed foreground shell or process exit. */ + onConfirmedShellForeground?: (reason: 'visible-pty' | 'command-finished' | 'process-exit') => void + onCommandFinishedUnavailable?: () => void + onVisibleForegroundSettled?: (outcome: 'agent' | 'shell' | 'inconclusive') => void +} + +export type PaneForegroundAgentTracker = { + /** True while any read is scheduled or running, whatever its authority. */ + hasReadInFlight: () => boolean + onVisiblePtyBound: (expectsAgent?: boolean) => boolean + onCommandStarted: (expectedAgent?: TuiAgent | null) => void + /** True when pane identity must remain visible until an async shell confirmation. */ + onCommandFinished: () => boolean + resetForPtyReplacement: () => void + /** The process monitor confirmed this agent exited (no agent, no children, settled). */ + onProcessExitConfirmed: (process: RecognizedAgentProcess) => void + dispose: () => void +} diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts index 3021132c3157..49fd197ead62 100644 --- a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts @@ -56,6 +56,36 @@ describe('createPaneForegroundAgentTracker', () => { vi.useRealTimers() }) + it('retires a pending predecessor read when an incarnation reuses its PTY ID', async () => { + let resolveRead!: (value: string | null) => void + readForegroundProcess.mockImplementation( + () => + new Promise((resolve) => { + resolveRead = resolve + }) + ) + const tracker = makeTracker() + tracker.onVisiblePtyBound(true) + await flushSettleRead(VISIBLE_PTY_SETTLE_MS) + tracker.resetForPtyReplacement() + expect(tracker.hasReadInFlight()).toBe(false) + resolveRead('pi') + await flushSettleRead(SECOND_WRAPPER_RETRY_MS) + expect(publish).not.toHaveBeenCalled() + expect(onConfirmedShellForeground).not.toHaveBeenCalled() + expect(onVisibleForegroundSettled).not.toHaveBeenCalled() + expect(readForegroundProcess).toHaveBeenCalledOnce() + readForegroundProcess.mockResolvedValue('codex') + tracker.onCommandStarted() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).toHaveBeenCalledWith({ + agent: 'codex', + shellForeground: false, + agentEvidence: 'process-read' + }) + tracker.dispose() + }) + // Why: detach/remount emits no PTY exit, so the store entry outlives this tracker. // A capability retained pending the disposed read would latch there forever. it('releases a retained capability when disposed mid-read', async () => { diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts index 308ca14919a2..aaf664839c21 100644 --- a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts @@ -1,53 +1,19 @@ import { isAgentForegroundWrapperProcess, - recognizeAgentProcess, - type RecognizedAgentProcess + recognizeAgentProcess } from '../../../../shared/agent-process-recognition' import { resolveCompatibleAgentTypeForOwner } from '../../../../shared/agent-title-owner' import { isShellProcess } from '../../../../shared/shell-process-detection' -import type { TuiAgent } from '../../../../shared/tui-agent' -import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' -import type { RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection' +import type { + PaneForegroundAgentTracker, + PaneForegroundAgentTrackerDeps +} from './pane-foreground-agent-tracker-contract' import { createPaneForegroundProcessReader } from './pane-foreground-process-reader' import { FOREGROUND_COMMAND_READS } from '../../../../shared/foreground-command-settle' const VISIBLE_PTY_SETTLE_MS = 350 type ForegroundReadReason = 'command' | 'visible-pty' | 'command-finished' -type PaneForegroundAgentTrackerDeps = { - getPtyId: () => string | null - /** Local panes only — remote/SSH foreground reads are expensive RPCs and - * their replayed OSC streams must not produce process evidence. */ - isTrackablePtyId: (ptyId: string) => boolean - readForegroundProcess: ( - ptyId: string, - options?: { expectedIncarnationId?: string } - ) => Promise - /** Fresh, provider-owned evidence used only when input routing may change. */ - confirmForegroundProcess?: ( - ptyId: string, - options?: { expectedIncarnationId?: string } - ) => Promise - /** Remote authorities must provide fenced evidence; local panes retain the string path. */ - isRemotePtyId?: (ptyId: string) => boolean - getExpectedIncarnationId?: () => string | null - publish: (entry: PaneForegroundAgentEntry) => void - /** The entry currently published for this pane, whoever wrote it. */ - getPublishedEntry?: () => PaneForegroundAgentEntry | undefined - /** A local read recognized an agent; lets the pane's process monitor watch for its exit. */ - onAgentProcessRead?: (process: RecognizedAgentProcess) => void - /** True when the pane is otherwise known to run an agent (launchAgent, live - * hook status). Lets a restored agent pane confirm — rather than trust — a - * 133;D before any command-start read has recorded its own evidence. */ - hasKnownAgentIdentity?: () => boolean - /** Fired when a confirming read proves the foreground genuinely returned to a - * shell (agent exited). Lets callers clear a stale agent-named tab title that - * the shell never repaints. */ - onConfirmedShellForeground?: (reason: 'visible-pty' | 'command-finished' | 'process-exit') => void - onCommandFinishedUnavailable?: () => void - onVisibleForegroundSettled?: (outcome: 'agent' | 'shell' | 'inconclusive') => void -} - /** * Publishes process-table identity for a pane at OSC 133 command boundaries: * one foreground read when a command starts (that is when the foreground @@ -56,17 +22,9 @@ type PaneForegroundAgentTrackerDeps = { * foreground read first, because a full-screen agent's nested command shells * leak their own 133;D onto the main PTY. */ -export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTrackerDeps): { - /** True while any read is scheduled or running, whatever its authority. */ - hasReadInFlight: () => boolean - onVisiblePtyBound: (expectsAgent?: boolean) => boolean - onCommandStarted: (expectedAgent?: TuiAgent | null) => void - /** True when pane identity must remain visible until an async shell confirmation. */ - onCommandFinished: () => boolean - /** The process monitor confirmed this agent exited (no agent, no children, settled). */ - onProcessExitConfirmed: (process: RecognizedAgentProcess) => void - dispose: () => void -} { +export function createPaneForegroundAgentTracker( + deps: PaneForegroundAgentTrackerDeps +): PaneForegroundAgentTracker { let disposed = false let readTimer: ReturnType | null = null let scheduledReadReason: ForegroundReadReason | null = null @@ -273,6 +231,10 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke } return { + resetForPtyReplacement() { + cancelPendingRead() + clearAgentEvidence() + }, // Why: onVisiblePtyBound refuses to schedule while a higher-authority // command read owns the pane, so "it scheduled nothing" must not be read // as "nothing will confirm this pane". diff --git a/src/renderer/src/components/terminal-pane/pty-connection-daemon-snapshot-replay.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-daemon-snapshot-replay.test.ts index f03c99fa7dda..6d8d9fba4f4b 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-daemon-snapshot-replay.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-daemon-snapshot-replay.test.ts @@ -9,6 +9,7 @@ import { } from '../../../../shared/terminal-mode-reset-profiles' import { replayEpilogue } from './pty-connection-test-replay-epilogue' import { Terminal } from '@xterm/headless' +import { NORMAL_BUFFER_PROLOGUE } from './pty-connection-test-constants' import { flushAsyncTicks, createDeferred, writeHeadlessTerminal } from './pty-connection-test-async' import { createRect } from './pty-connection-test-dom' import { @@ -770,7 +771,7 @@ describe('connectPanePty', () => { await flushAsyncTicks(8) replayCallback.current?.('blocking replay') await flushAsyncTicks(12) - expect(writes).toEqual(['\x1b[?2026l\x1b[2J\x1b[3J\x1b[H']) + expect(writes).toEqual([NORMAL_BUFFER_PROLOGUE]) reattachResult.resolve({ id: 'tab-pty', snapshot: 'stale authoritative snapshot' }) await flushAsyncTicks(12) const resizeCallsBeforeReplacement = transport.resize.mock.calls.length diff --git a/src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts index f4e8d8bd2bb3..f53c2b751f9f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts @@ -1,11 +1,17 @@ import type * as React from 'react' +import { Terminal } from '@xterm/headless' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { flushAsyncTicks, renderHeadlessBuffer } from './pty-connection-test-async' +import { + flushAsyncTicks, + renderHeadlessBuffer, + writeHeadlessTerminal +} from './pty-connection-test-async' import { createMockTransport, createPane, createManager } from './pty-connection-test-pane-fixtures' import type { ConnectCallbacks, MockTransport } from './pty-connection-test-pane-fixtures' import { buildPaneConnectionDeps } from './pty-connection-test-deps' import { createInitialStoreState, + buildReattachPaneTitleState, buildActiveRuntimeEnvironmentState } from './pty-connection-test-store-fixtures' import type { StoreState } from './pty-connection-test-store-state' @@ -62,7 +68,11 @@ vi.mock('@/store', () => ({ vi.mock('@/lib/agent-status', async (importOriginal) => { const { buildAgentStatusModuleMock } = await import('./pty-connection-test-environment') - return buildAgentStatusModuleMock(await importOriginal>()) + const actual = await importOriginal>() + return { + ...buildAgentStatusModuleMock(actual), + detectAgentStatusFromTitle: actual.detectAgentStatusFromTitle + } }) vi.mock('./cache-timer-seeding', () => ({ @@ -133,20 +143,32 @@ function createDeps(overrides: Record = {}) { return buildPaneConnectionDeps(() => mockStoreState, overrides) } -async function connectRemotePane(): Promise<{ +async function connectRemotePane( + title?: string, + incarnationId: string | null = 'inc-old' +): Promise<{ operations: { kind: 'resize' | 'write'; value: string }[] pane: ReturnType transport: MockTransport + live: (data: string) => void + rebind: (incarnationId?: string | null) => void replay: (data: string, meta?: Record) => void dispose: () => void }> { const { connectPanePty } = await import('./pty-connection') mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, 'env-1') + if (title) { + mockStoreState = buildReattachPaneTitleState(mockStoreState, title) + } const transport = createMockTransport('remote:env-1@@terminal-1') - const captured: { current: ConnectCallbacks['onReplayData'] | null } = { current: null } + const captured: { + current: ConnectCallbacks['onReplayData'] | null + live: ConnectCallbacks['onData'] | null + } = { current: null, live: null } transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { captured.current = callbacks.onReplayData ?? null - return { id: 'remote:env-1@@terminal-1', replay: '' } + captured.live = callbacks.onData ?? null + return { id: 'remote:env-1@@terminal-1', replay: '', incarnationId } }) transportFactoryQueue.push(transport) @@ -177,6 +199,14 @@ async function connectRemotePane(): Promise<{ operations, pane, transport, + live: (data) => captured.live?.(data), + rebind: (nextIncarnation) => { + const onRebind = createdTransportOptions.at(-1)?.onPtyRebind + if (typeof onRebind !== 'function') { + throw new Error('Transport was created without onPtyRebind') + } + onRebind('remote:env-1@@terminal-1', 'remote:env-1@@terminal-1', nextIncarnation) + }, replay: (data, meta) => captured.current?.(data, meta as never), dispose: () => disposable.dispose() } @@ -197,6 +227,104 @@ describe('pushed remote snapshot replay grid', () => { await restoreTerminalTestGlobals() }) + it.each([ + { name: 'replacement with shell ownership', owner: 'shell' as const, expectedMouse: 'none' }, + { + name: 'known replacement without ownership', + owner: undefined, + expectedMouse: 'none', + replacement: true + }, + { name: 'unknown legacy ownership', owner: undefined, expectedMouse: 'any' }, + { + name: 'unknown predecessor', + owner: undefined, + expectedMouse: 'any', + replacement: true, + unknownPredecessor: true + }, + { name: 'unknown successor', owner: undefined, expectedMouse: 'any', unknownSuccessor: true }, + { + name: 'same-incarnation rebind', + owner: undefined, + expectedMouse: 'any', + sameIncarnation: true + }, + { name: 'surviving agent', owner: undefined, expectedMouse: 'any', liveAgent: true }, + { + name: 'replacement agent', + owner: undefined, + expectedMouse: 'any', + liveAgent: true, + replacement: true + } + ])('reconciles mouse modes for a $name despite a retained Pi title', async (scenario) => { + const session = await connectRemotePane( + 'π - remote-session', + scenario.unknownPredecessor ? null : 'inc-old' + ) + const terminal = new Terminal({ cols: PANE_COLS, rows: PANE_ROWS, allowProposedApi: true }) + const mouseModes = '\x1b[?1003h\x1b[?1006h' + const snapshot = scenario.liveAgent ? `${mouseModes}LIVE_AGENT` : 'REPLACEMENT_SHELL$ ' + try { + await writeHeadlessTerminal(terminal, `OLD_AGENT_FRAME${mouseModes}`) + expect(terminal.modes.mouseTrackingMode).toBe('any') + if (scenario.replacement) { + session.rebind('inc-new') + } + if (scenario.sameIncarnation) { + session.rebind('inc-old') + } + if (scenario.unknownSuccessor) { + session.rebind(null) + } + session.replay(snapshot, { + snapshotCols: PANE_COLS, + snapshotRows: PANE_ROWS, + ...(scenario.owner ? { terminalOwner: scenario.owner, alternateScreen: false } : {}) + }) + await flushAsyncTicks(20) + const writes = session.operations.filter((operation) => operation.kind === 'write') + expect(writes.some((operation) => operation.value.includes(snapshot))).toBe(true) + for (const operation of writes) { + await writeHeadlessTerminal(terminal, operation.value) + } + expect(terminal.buffer.active.getLine(0)?.translateToString(true)).toContain( + scenario.liveAgent ? 'LIVE_AGENT' : 'REPLACEMENT_SHELL$' + ) + expect(terminal.modes.mouseTrackingMode).toBe(scenario.expectedMouse) + } finally { + session.dispose() + terminal.dispose() + } + }) + + it('grounds a retained invisible pen before painting a replacement shell snapshot', async () => { + const session = await connectRemotePane('π - remote-session') + const terminal = new Terminal({ cols: PANE_COLS, rows: PANE_ROWS, allowProposedApi: true }) + try { + await writeHeadlessTerminal(terminal, 'OLD_AGENT_FRAME\x1b[8m') + session.replay('REPLACEMENT_SHELL$ ', { + snapshotCols: PANE_COLS, + snapshotRows: PANE_ROWS, + terminalOwner: 'shell', + alternateScreen: false + }) + await flushAsyncTicks(20) + for (const operation of session.operations) { + if (operation.kind === 'write') { + await writeHeadlessTerminal(terminal, operation.value) + } + } + const line = terminal.buffer.active.getLine(0) + expect(line?.translateToString(true)).toContain('REPLACEMENT_SHELL$') + expect(line?.getCell(0)?.isInvisible()).toBe(0) + } finally { + session.dispose() + terminal.dispose() + } + }) + it('replays at the host grid and then pushes the pane grid back to the PTY', async () => { const session = await connectRemotePane() @@ -213,11 +341,73 @@ describe('pushed remote snapshot replay grid', () => { expect(frameWriteIndex).toBeGreaterThan(sourceResizeIndex) // Why the PTY push matters: the pane must not be left driving the host at // the replay geometry once the destination fit has run. - expect(session.transport.resize).toHaveBeenCalledWith(PANE_COLS, PANE_ROWS) + expect(session.transport.resize).toHaveBeenCalledWith(PANE_COLS, PANE_ROWS, { redraw: true }) expect(session.transport.resize).not.toHaveBeenCalledWith(HOST_COLS, HOST_ROWS) session.dispose() }) + it('fits locally after source replay without claiming an unknown remote owner grid', async () => { + const { setFitOverride, getFitOverrideForPty } = + await import('@/lib/pane-manager/mobile-fit-overrides') + const session = await connectRemotePane() + const id = 'remote:env-1@@terminal-1' + setFitOverride(id, 'remote-desktop-fit', 0, 0) + try { + session.replay('SHELL$', { snapshotCols: 2, snapshotRows: 1 }) + await flushAsyncTicks(20) + expect(session.pane.terminal.resize).toHaveBeenCalledWith(2, 1) + expect(session.pane.terminal.cols).toBe(PANE_COLS) + expect(session.pane.terminal.rows).toBe(PANE_ROWS) + expect(session.transport.resize).not.toHaveBeenCalled() + expect(window.api.pty.signal).not.toHaveBeenCalledWith(id, 'SIGWINCH') + expect(getFitOverrideForPty(id)).toEqual({ mode: 'remote-desktop-fit', cols: 0, rows: 0 }) + } finally { + setFitOverride(id, 'desktop-fit', 0, 0) + session.dispose() + } + }) + + it('retires an in-flight predecessor replay and keeps successor live output for a reused handle', async () => { + const session = await connectRemotePane('π - remote-session') + const write = session.pane.terminal.write.getMockImplementation()! + let finishOldWrite: (() => void) | undefined + session.pane.terminal.write.mockImplementation((data: string, callback?: () => void) => { + if (data === 'STALE_FRAME') { + write(data) + finishOldWrite = callback + } else { + write(data, callback) + } + }) + try { + session.replay('STALE_FRAME', { + snapshotCols: 2, + snapshotRows: 1, + pendingEscapeTailAnsi: '\x1b[999;' + }) + await flushAsyncTicks(10) + expect(finishOldWrite).toBeTypeOf('function') + session.live('STALE_ACK') + session.rebind('inc-new') + session.replay('SUCCESSOR_FRAME', { snapshotCols: 2, snapshotRows: 1 }) + session.live('LIVE_ACK') + finishOldWrite?.() + await flushAsyncTicks(30) + const writes = session.operations.filter((op) => op.kind === 'write').map((op) => op.value) + expect(writes).not.toContain('\x1b[999;') + expect(writes.join('')).not.toContain('STALE_ACK') + expect(writes.join('')).toContain('LIVE_ACK') + expect(writes.findIndex((data) => data.includes('LIVE_ACK'))).toBeGreaterThan( + writes.indexOf('SUCCESSOR_FRAME') + ) + expect(session.pane.terminal.cols).toBe(PANE_COLS) + expect(session.transport.resize).not.toHaveBeenCalledWith(2, 1) + } finally { + finishOldWrite?.() + session.dispose() + } + }) + it('keeps the pane grid when the host published no snapshot dimensions', async () => { const session = await connectRemotePane() diff --git a/src/renderer/src/components/terminal-pane/pty-connection-replay-payload-handling.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-replay-payload-handling.test.ts index 8214432ed82c..dd6329f28cdf 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-replay-payload-handling.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-replay-payload-handling.test.ts @@ -619,7 +619,7 @@ describe('connectPanePty', () => { expect(pane.terminal.write).toHaveBeenCalledTimes(1) expect(pane.terminal.write).toHaveBeenNthCalledWith( 1, - '\x1b[?2026l\x1b[2J\x1b[3J\x1b[H', + NORMAL_BUFFER_PROLOGUE, expect.any(Function) ) @@ -658,7 +658,7 @@ describe('connectPanePty', () => { callbacksRef.replay?.('authoritative replay') await flushAsyncTicks(8) - expect(writes).toEqual(['\x1b[?2026l\x1b[2J\x1b[3J\x1b[H']) + expect(writes).toEqual([NORMAL_BUFFER_PROLOGUE]) const acknowledgeLiveFrame = vi.fn() deliverTerminalDataWithDeferredCredit(acknowledgeLiveFrame, () => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts index ced77bdaa782..91a67fb8f107 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts @@ -1,3 +1,4 @@ +import { retireRemotePtyIncarnation } from './remote-pty-incarnation-replacement' import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph' import { useAppStore } from '@/store' // Why: a restored pane's stale-account prompt can only be raised once a PTY is @@ -204,7 +205,11 @@ export function installPanePtyVisibilityBind(session: ConnectPanePtySession): vo if (!session.canAdoptCapturedDirectSshRetryPty(ptyId)) { return } + const replacedIncarnationId = session.remotePtyIncarnationId session.remotePtyIncarnationId = incarnationId ?? null + if (replacedIncarnationId && incarnationId && replacedIncarnationId !== incarnationId) { + retireRemotePtyIncarnation(session, replacedPtyId, ptyId) + } // Why: provider handle rotation keeps the existing pane/session generation; // replace its stale store identity without fresh-spawn exit semantics. session.bindActivePanePty(ptyId, { replacePtyId: replacedPtyId }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts b/src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts index aad2384bb278..a68c0fb8397a 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts @@ -24,6 +24,7 @@ import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore' import { isCodexPaneStale } from './codex-pane-stale' import { installTerminalSelectionFitGuard } from '../terminal-selection-fit-guard' import { initializePaneGeometry, readPaneSize } from './read-pane-size' +import { installReattachGridPush } from './reattach-grid-push' import type { ConnectPanePtySession } from './connect-pane-pty-session' @@ -282,44 +283,7 @@ export function installPtyInputForward(session: ConnectPanePtySession): void { }, forwardResize: session.forwardPtyResize }) - // Why built here and not inside session.handleReattachResult: a hidden pane parks this until it is - // revealed, and a closure created in that scope would pin the whole reattach payload - // (snapshot/replay/coldRestore bytes) for as long as the pane stays hidden. Taking the - // generation and pty id by value keeps only connection-level state alive. - session.createReattachGridPush = ( - attemptGeneration: number, - reattachPtyId: string - ): { shouldContinue: () => boolean; continuation: () => void } => { - const isCurrent = (): boolean => - !session.disposed && - attemptGeneration === session.transportStreamGeneration && - session.transport.getPtyId() === reattachPtyId - return { - shouldContinue: isCurrent, - continuation: () => { - if (!isCurrent()) { - return - } - // Why re-checked at fire time: the caller's pre-check cannot see a mobile takeover that - // lands while the pane waits for a box, and transport.resize here bypasses - // forwardPtyResize's own suppression. - if (session.shouldSuppressDesktopPtyResize()) { - return - } - const reattachCols = session.pane.terminal.cols - const reattachRows = session.pane.terminal.rows - if (reattachCols > 0 && reattachRows > 0) { - session.transport.resize(reattachCols, reattachRows) - } - if (!isRemoteRuntimePtyId(reattachPtyId)) { - window.api.pty.signal(reattachPtyId, 'SIGWINCH') - } - if (session.deps.isVisibleRef.current) { - session.ptySizeReassertion.request({ fit: false }) - } - } - } - } + installReattachGridPush(session) session.pendingForegroundGridDriftCheckRaf = null session.lastForegroundGridDriftCheckAt = Number.NEGATIVE_INFINITY session.readProposedTerminalGrid = (): { cols: number; rows: number } | null => { diff --git a/src/renderer/src/components/terminal-pane/pty-connection/reattach-grid-push.ts b/src/renderer/src/components/terminal-pane/pty-connection/reattach-grid-push.ts new file mode 100644 index 000000000000..b66a0e5476a2 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/reattach-grid-push.ts @@ -0,0 +1,49 @@ +import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +export function installReattachGridPush(session: ConnectPanePtySession): void { + // Why built here and not inside session.handleReattachResult: a hidden pane parks this until it is + // revealed, and a closure created in that scope would pin the whole reattach payload + // (snapshot/replay/coldRestore bytes) for as long as the pane stays hidden. Taking the + // generation and pty id by value keeps only connection-level state alive. + session.createReattachGridPush = ( + attemptGeneration: number, + reattachPtyId: string + ): { shouldContinue: () => boolean; continuation: () => void } => { + const incarnationId = session.remotePtyIncarnationId + const isCurrent = (): boolean => + !session.disposed && + session.remotePtyIncarnationId === incarnationId && + attemptGeneration === session.transportStreamGeneration && + session.transport.getPtyId() === reattachPtyId + return { + shouldContinue: isCurrent, + continuation: () => { + if (!isCurrent()) { + return + } + // Why re-checked at fire time: the caller's pre-check cannot see a mobile takeover that + // lands while the pane waits for a box, and transport.resize here bypasses + // forwardPtyResize's own suppression. + if (session.shouldSuppressDesktopPtyResize()) { + return + } + const reattachCols = session.pane.terminal.cols + const reattachRows = session.pane.terminal.rows + if (reattachCols > 0 && reattachRows > 0) { + if (isRemoteRuntimePtyId(reattachPtyId)) { + session.transport.resize(reattachCols, reattachRows, { redraw: true }) + } else { + session.transport.resize(reattachCols, reattachRows) + } + } + if (!isRemoteRuntimePtyId(reattachPtyId)) { + window.api.pty.signal(reattachPtyId, 'SIGWINCH') + } + if (session.deps.isVisibleRef.current) { + session.ptySizeReassertion.request({ fit: false }) + } + } + } + } +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.test.ts new file mode 100644 index 000000000000..4f458566c5b3 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.test.ts @@ -0,0 +1,78 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ConnectPanePtySession } from './connect-pane-pty-session' +import { retireRemotePtyIncarnation } from './remote-pty-incarnation-replacement' + +const { state } = vi.hoisted(() => { + const agentStatusByPaneKey: Record = {} + const agentLaunchConfigByPaneKey: Record = {} + return { + state: { + agentStatusByPaneKey, + agentLaunchConfigByPaneKey, + removeAgentStatus: vi.fn(), + clearAgentLaunchConfig: vi.fn(), + clearPaneForegroundAgent: vi.fn() + } + } +}) +vi.mock('@/store', () => ({ useAppStore: { getState: () => state } })) + +function createSession() { + return { + cacheKey: 'pane', + authoritativeReattachGeneration: 1, + replayPayloadGeneration: 1, + clearHiddenOutputRestoreState: vi.fn(), + clearRestoredSnapshotBaseline: vi.fn(), + clearPaneMode2031State: vi.fn(), + kittyKeyboardModes: { reset: vi.fn() }, + paneForegroundAgentTracker: { resetForPtyReplacement: vi.fn() }, + clearCommandInferredPaneAgent: vi.fn(), + resetPendingShellCommandLine: vi.fn(), + rememberReattachPayloadAgentSignal: vi.fn(), + clearStaleAgentTabTitleOnConfirmedShell: vi.fn(), + deps: { setCacheTimerStartedAt: vi.fn() }, + writeReplayData: vi.fn() + } +} + +describe('remote PTY incarnation replacement publication ownership', () => { + beforeEach(() => { + vi.clearAllMocks() + state.agentStatusByPaneKey = {} + state.agentLaunchConfigByPaneKey = {} + }) + + it.each([ + { name: 'known predecessor', rowHandle: 'old', successorHandle: 'new', clear: true }, + { + name: 'successor published before rebind', + rowHandle: 'new', + successorHandle: 'new', + clear: false + }, + { + name: 'same-handle successor publication', + rowHandle: 'old', + successorHandle: 'old', + clear: false + }, + { name: 'unknown row ownership', rowHandle: undefined, successorHandle: 'new', clear: false } + ])('only retires a positively owned row: $name', ({ rowHandle, successorHandle, clear }) => { + const session = createSession() + state.agentStatusByPaneKey.pane = { terminalHandle: rowHandle } + state.agentLaunchConfigByPaneKey.pane = { identity: { terminalHandle: rowHandle } } + retireRemotePtyIncarnation( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies every session member retireRemotePtyIncarnation reads. + session as unknown as ConnectPanePtySession, + 'remote:env@@old', + `remote:env@@${successorHandle}` + ) + expect(state.removeAgentStatus).toHaveBeenCalledTimes(clear ? 1 : 0) + expect(state.clearAgentLaunchConfig).toHaveBeenCalledTimes(clear ? 1 : 0) + expect(session.deps.setCacheTimerStartedAt).toHaveBeenCalledTimes(clear ? 1 : 0) + expect(session.clearStaleAgentTabTitleOnConfirmedShell).not.toHaveBeenCalled() + expect(session.paneForegroundAgentTracker.resetForPtyReplacement).toHaveBeenCalledOnce() + expect(session.writeReplayData).toHaveBeenCalledOnce() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.ts b/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.ts new file mode 100644 index 000000000000..edcdb24146d1 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-connection/remote-pty-incarnation-replacement.ts @@ -0,0 +1,52 @@ +import { useAppStore } from '@/store' +import { parseRemoteRuntimePtyId } from '../../../../../shared/remote-runtime-pty-id' +import { + ABORT_TRUNCATED_CONTROL_STRING, + POST_REPLAY_MODE_RESET +} from '../../../../../shared/terminal-mode-reset-profiles' +import type { ConnectPanePtySession } from './connect-pane-pty-session' + +/** A proved replacement retires predecessor evidence, without spawning or claiming shell ownership. */ +export function retireRemotePtyIncarnation( + session: ConnectPanePtySession, + replacedPtyId: string, + ptyId: string +): void { + session.authoritativeReattachGeneration += 1 + session.replayPayloadGeneration += 1 + session.pendingReplayData = null + session.pendingReattachFit?.cancel() + session.pendingReattachFit = null + session.clearHiddenOutputRestoreState() + session.clearRestoredSnapshotBaseline() + session.deferredReattachLiveData?.discard() + session.clearPaneMode2031State() + session.kittyKeyboardModes.reset() + session.paneForegroundAgentTracker.resetForPtyReplacement() + session.visibleForegroundSamplePending = false + session.visibleForegroundSampleSettled = false + session.deferredCommandFinishedStatusDrop = null + session.deferredConfirmedShellReconcile = null + session.clearCommandInferredPaneAgent() + session.resetPendingShellCommandLine() + session.rememberReattachPayloadAgentSignal('', { fullScreenReplay: true }) + const state = useAppStore.getState() + const predecessorHandle = parseRemoteRuntimePtyId(replacedPtyId)?.handle + const successorHandle = parseRemoteRuntimePtyId(ptyId)?.handle + // Published rows can already belong to the successor; reused handles carry no incarnation fence. + if (predecessorHandle && successorHandle && predecessorHandle !== successorHandle) { + if (state.agentStatusByPaneKey[session.cacheKey]?.terminalHandle === predecessorHandle) { + state.removeAgentStatus(session.cacheKey) + session.deps.setCacheTimerStartedAt(session.cacheKey, null) + } + if ( + state.agentLaunchConfigByPaneKey[session.cacheKey]?.identity.terminalHandle === + predecessorHandle + ) { + state.clearAgentLaunchConfig(session.cacheKey) + } + } + state.clearPaneForegroundAgent(session.cacheKey) + session.replacementReplayPending = true + session.writeReplayData(`${ABORT_TRUNCATED_CONTROL_STRING}${POST_REPLAY_MODE_RESET}`) +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/replay-data-drain.ts b/src/renderer/src/components/terminal-pane/pty-connection/replay-data-drain.ts index 693ee4be67aa..332468f2470c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/replay-data-drain.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/replay-data-drain.ts @@ -1,4 +1,8 @@ -import { RELEASE_SYNCHRONIZED_OUTPUT } from '../../../../../shared/terminal-mode-reset-profiles' +import { + ABORT_TRUNCATED_CONTROL_STRING, + buildSnapshotReplayPrologue, + POST_REPLAY_LIVE_AGENT_SNAPSHOT_RESET +} from '../../../../../shared/terminal-mode-reset-profiles' import { waitForTerminalOutputParsed } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { safeFit, safeFitAndThen } from '@/lib/pane-manager/pane-tree-ops' import { getFitOverrideForPty } from '@/lib/pane-manager/mobile-fit-overrides' @@ -76,11 +80,13 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { let replayedAtSourceGrid = false const drainReplayDataQueue = async ( expectedPtyId: string | null, - expectedStreamGeneration: number + expectedStreamGeneration: number, + expectedIncarnationId: string | null | undefined ): Promise => { let appliedCurrentPayload = false while (session.pendingReplayData !== null) { if ( + session.remotePtyIncarnationId !== expectedIncarnationId || session.pendingReplayData.ptyId !== expectedPtyId || session.pendingReplayData.streamGeneration !== expectedStreamGeneration ) { @@ -118,12 +124,16 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { // Why ahead of the source-grid resize: the clear is grid-independent, so // dropping the scrollback first spares a reflow of history the very next // sequence discards (see use-terminal-container-fit-sync.ts on its cost). + const replacementReplay = session.replacementReplayPending === true if (clearBeforeReplay) { - // RELEASE_SYNCHRONIZED_OUTPUT: a reconnect is exactly the event that severs a - // frame mid-flight, so this xterm may hold an open 2026 latch — and \x1b[2J does - // not clear it, so the pane would stay frozen on its last painted frame and the - // whole replay would go unseen until xterm's 1s timeout. - await session.writeReplayDataAsync(`${RELEASE_SYNCHRONIZED_OUTPUT}\x1b[2J\x1b[3J\x1b[H`) + const paneOnAlternateScreen = session.pane.terminal.buffer.active.type === 'alternate' + await session.writeReplayDataAsync( + ABORT_TRUNCATED_CONTROL_STRING + + buildSnapshotReplayPrologue({ + targetAlternateScreen: alternateScreen ?? paneOnAlternateScreen, + paneOnAlternateScreen + }) + ) if (!isCurrentPayload()) { continue } @@ -164,7 +174,9 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { } if (clearBeforeReplay || data.length > 0) { await session.writeReplayEpilogue( - session.chooseReattachReplayReset(data, false, alternateScreen, terminalOwner), + replacementReplay && terminalOwner !== 'shell' + ? POST_REPLAY_LIVE_AGENT_SNAPSHOT_RESET + : session.chooseReattachReplayReset(data, false, alternateScreen, terminalOwner), session.writeReplayDataAsync ) if (!isCurrentPayload()) { @@ -187,6 +199,7 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { // empty buffer; rebuilding after replay parses seeds the glyph atlas // from the now-populated xterm state. session.manager.rebuildPaneWebgl(session.pane.id) + session.replacementReplayPending = false appliedCurrentPayload = true } return appliedCurrentPayload @@ -239,6 +252,7 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { return } const scheduledPtyId = session.pendingReplayData?.ptyId ?? null + const scheduledIncarnationId = session.remotePtyIncarnationId replayDrainQueued = true // Why reset here: a transaction whose restore was skipped never ran its // afterRestore, and a stale flag would fit a later drain that never left @@ -255,12 +269,17 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { .then(() => session.structuralReplayCoordinator.run( async () => { - replayCompleted = await drainReplayDataQueue(scheduledPtyId, scheduledStreamGeneration) + replayCompleted = await drainReplayDataQueue( + scheduledPtyId, + scheduledStreamGeneration, + scheduledIncarnationId + ) }, { shouldRestore: () => !session.disposed && session.transport.getPtyId() === scheduledPtyId && + session.remotePtyIncarnationId === scheduledIncarnationId && session.transportStreamGeneration === scheduledStreamGeneration, afterRestore: () => fitAfterSourceGridReplay(scheduledPtyId, scheduledStreamGeneration) } @@ -276,7 +295,11 @@ export function bindReplayDataDrain(session: ConnectPanePtySession): void { // re-reading it here could retag stale bytes for a replacement PTY. session.scheduleReplayDataDrain() } - session.finishReattachLiveDataDeferral(replayCompleted, scheduledStreamGeneration) + // A superseded image must not fail the successor's deferred live-output owner. + session.finishReattachLiveDataDeferral( + replayCompleted || session.remotePtyIncarnationId !== scheduledIncarnationId, + scheduledStreamGeneration + ) }) } } diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index dce25fd547cc..e2d27b7d01f6 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -206,6 +206,8 @@ export type PtyTransport = { cellW?: number cellH?: number claim?: boolean + /** Reattach repaint when the host's grid is unchanged; never claims control. */ + redraw?: boolean } ) => boolean isConnected: () => boolean diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-attachment-metadata-order.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-attachment-metadata-order.test.ts new file mode 100644 index 000000000000..ba995a0ab93d --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-attachment-metadata-order.test.ts @@ -0,0 +1,150 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types' +import type { RuntimeTerminalResolvePane } from '../../../../shared/runtime-terminal-contracts' +import { createDeferred, flushAsyncTicks } from './pty-connection-test-async' +import { + createRemoteRuntimeTransportMocks, + type MultiplexSubscriptionCallbacks +} from './remote-runtime-pty-transport-test-harness' + +let callbacks: MultiplexSubscriptionCallbacks = null +let resolvedHandle = 'terminal-current' +const mocks = createRemoteRuntimeTransportMocks({ + getCallbacks: () => callbacks, + setCallbacks: (next) => { + callbacks = next + }, + getResolvedPaneHandle: () => resolvedHandle, + setResolvedPaneHandle: (next) => { + resolvedHandle = next + } +}) +const currentMetadata = { + incarnationId: 'inc-current', + executionHostId: 'runtime:env-1', + hostPlatform: 'linux' +} as const +const obsoleteMetadata = { + incarnationId: 'inc-obsolete', + executionHostId: 'ssh:obsolete-host', + hostPlatform: 'win32' +} as const + +function inventoryFor( + terminal: string, + metadata: Pick +): RuntimeMobileSessionTabsResult { + return { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + 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, + ...metadata + } + ] + } +} + +describe('host mirror attachment metadata ordering', () => { + beforeEach(() => mocks.resetRemoteRuntimeTransport()) + + it.each(['activation', 'inventory'] as const)( + 'rejects obsolete %s metadata after a newer attachment completes', + async (source) => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const events = await import('../../runtime/web-session-terminal-handle-events') + const pending = createDeferred<{ ok: boolean; result: RuntimeMobileSessionTabsResult }>() + const currentInventory = inventoryFor('terminal-current', currentMetadata) + let activations = 0 + let inventories = 0 + mocks.runtimeCall.mockImplementation((args: { method: string }) => { + if (args.method === 'session.tabs.activate') { + activations += 1 + if (activations === 1) { + return source === 'activation' + ? pending.promise + : Promise.resolve({ ok: true, result: { ...currentInventory, tabs: [] } }) + } + return Promise.resolve({ ok: true, result: currentInventory }) + } + if (args.method === 'session.tabs.list') { + inventories += 1 + return pending.promise + } + if (args.method === 'terminal.resolvePane') { + return Promise.resolve({ + ok: true, + result: { + terminal: { + handle: 'terminal-current', + tabId: 'tab-1', + leafId: 'pane:1', + worktreeId: 'wt-1', + ...currentMetadata + } + } + }) + } + return Promise.resolve({ ok: true, result: {} }) + }) + const onPtyRebind = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtyRebind + }) + const attach = () => + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-current', + callbacks: {} + }) + try { + attach() + await vi.waitFor(() => expect(source === 'activation' ? activations : inventories).toBe(1)) + attach() + await vi.waitFor(() => expect(mocks.subscriptionSendBinary).toHaveBeenCalled()) + mocks.emitSnapshot(mocks.latestSubscribePayload().streamId, 'current image') + expect(onPtyRebind).toHaveBeenCalledExactlyOnceWith( + 'remote:env-1@@terminal-current', + 'remote:env-1@@terminal-current', + 'inc-current' + ) + onPtyRebind.mockClear() + pending.resolve({ ok: true, result: inventoryFor('terminal-obsolete', obsoleteMetadata) }) + await flushAsyncTicks(8) + expect(transport.getPtyId()).toBe('remote:env-1@@terminal-current') + expect.soft(transport.getExecutionHostId?.()).toBe('runtime:env-1') + expect.soft(transport.getRemotePlatform?.()).toBe('linux') + + // Keep inventory recovery pending so the next accepted publication exposes incarnation drift. + mocks.runtimeCall.mockImplementation(() => new Promise(() => {})) + callbacks?.onClose?.() + await vi.waitFor(() => + expect(events.getWebSessionTerminalHandleSubscriberCountForTests()).toBe(1) + ) + const subscriptionCount = mocks.subscribedTerminalHandles().length + events.queueAcceptedWebSessionTerminalSnapshot(currentInventory, 'env-1') + await flushAsyncTicks(8) + expect(onPtyRebind).not.toHaveBeenCalled() + expect(mocks.subscribedTerminalHandles()).toHaveLength(subscriptionCount) + expect(transport.getExecutionHostId?.()).toBe('runtime:env-1') + expect(transport.getRemotePlatform?.()).toBe('linux') + } finally { + transport.destroy?.() + } + } + ) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-incarnation-recovery.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-incarnation-recovery.test.ts new file mode 100644 index 000000000000..e693af210a1f --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-incarnation-recovery.test.ts @@ -0,0 +1,215 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + decodeTerminalStreamFrame, + TerminalStreamOpcode +} from '../../../../shared/terminal-stream-protocol' +import { + createRemoteRuntimeTransportMocks, + type MultiplexSubscriptionCallbacks +} from './remote-runtime-pty-transport-test-harness' + +let subscriptionCallbacks: MultiplexSubscriptionCallbacks = null +let resolvedPaneHandle = 'terminal-1' +const mocks = createRemoteRuntimeTransportMocks({ + getCallbacks: () => subscriptionCallbacks, + setCallbacks: (callbacks) => { + subscriptionCallbacks = callbacks + }, + getResolvedPaneHandle: () => resolvedPaneHandle, + setResolvedPaneHandle: (handle) => { + resolvedPaneHandle = handle + } +}) + +describe('remote PTY incarnation recovery', () => { + beforeEach(() => mocks.resetRemoteRuntimeTransport()) + + it.each([true, false])( + 'publishes initial attach identity before its replay (mirror=%s)', + async (mirror) => { + const originalCall = mocks.runtimeCall.getMockImplementation()! + mocks.runtimeCall.mockImplementation(async (request: { method: string }) => { + const response = await originalCall(request) + if (request.method === 'terminal.resolvePane') { + response.result.terminal.incarnationId = 'inc-old' + } + return response + }) + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const events: string[] = [] + const onPtySpawn = vi.fn() + const onPtyRebind = vi.fn((_id: string, _old: string, incarnationId?: string | null) => { + events.push(`identity:${incarnationId}`) + }) + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: mirror ? 'web-terminal-tab-1' : 'tab-1', + leafId: 'pane:1', + onPtySpawn, + onPtyRebind + }) + try { + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + cols: 75, + rows: 60, + callbacks: { onReplayData: () => events.push('replay') } + }) + await vi.waitFor(() => expect(mocks.subscriptionSendBinary).toHaveBeenCalled()) + mocks.emitSnapshot(mocks.latestSubscribePayload().streamId, 'FRAME') + await vi.waitFor(() => expect(events).toContain('replay')) + expect(events).toEqual(['identity:inc-old', 'replay']) + expect(onPtySpawn).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + } + ) + + it.each(['terminal-1', 'terminal-2'])( + 'uses the persisted session ID for connect reattachment to %s', + async (nextHandle) => { + resolvedPaneHandle = nextHandle + const originalCall = mocks.runtimeCall.getMockImplementation()! + mocks.runtimeCall.mockImplementation(async (request: { method: string }) => { + const response = await originalCall(request) + if (request.method === 'terminal.resolvePane') { + response.result.terminal.incarnationId = 'inc-new' + } + return response + }) + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const onPtyRebind = vi.fn() + const onPtySpawn = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtyRebind, + onPtySpawn + }) + try { + await transport.connect({ + url: '', + sessionId: 'remote:env-1@@terminal-1', + callbacks: {} + }) + expect(onPtyRebind).toHaveBeenCalledExactlyOnceWith( + `remote:env-1@@${nextHandle}`, + 'remote:env-1@@terminal-1', + 'inc-new' + ) + expect(onPtySpawn).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + } + ) + + it.each( + [ + { mirror: true, rotate: false, next: null, inventory: false }, + { mirror: false, rotate: false, next: null, inventory: false }, + { mirror: true, rotate: false, next: 'inc-new', inventory: true }, + { mirror: true, rotate: true, next: 'inc-new', inventory: true }, + { mirror: true, rotate: false, next: 'inc-new', inventory: false }, + { mirror: true, rotate: true, next: 'inc-old', inventory: false }, + { mirror: false, rotate: false, next: 'inc-new', inventory: false }, + { mirror: false, rotate: true, next: 'inc-old', inventory: false }, + { mirror: true, rotate: true, next: null, inventory: false } + ].flatMap((scenario) => + (['mobile-fit', 'remote-desktop-fit'] as const).map((holdMode) => ({ ...scenario, holdMode })) + ) + )( + 'preserves ownership while delivering identity: $mirror/$rotate/$next/$inventory/$holdMode', + async (scenario) => { + let incarnationId: string | null = 'inc-old' + const originalCall = mocks.runtimeCall.getMockImplementation()! + mocks.runtimeCall.mockImplementation(async (request: { method: string }) => { + const response = await originalCall(request) + if (request.method === 'terminal.resolvePane') { + response.result.terminal.incarnationId = incarnationId + } + if (request.method === 'session.tabs.activate' && scenario.inventory) { + response.result.tabs[0].incarnationId = incarnationId + } + return response + }) + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const { setFitOverride, getFitOverrideForPty, onOverrideChange } = + await import('../../lib/pane-manager/mobile-fit-overrides') + const { setDriverForPty, getDriverForPty, onDriverChange } = + await import('../../lib/pane-manager/mobile-driver-state') + const fitChanged = vi.fn() + const driverChanged = vi.fn() + const unsubscribeFit = onOverrideChange(fitChanged) + const unsubscribeDriver = onDriverChange(driverChanged) + const onPtyRebind = vi.fn() + const onPtySpawn = vi.fn() + const onPtyExit = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: scenario.mirror ? 'web-terminal-tab-1' : 'tab-1', + leafId: 'pane:1', + onPtyRebind, + onPtySpawn, + onPtyExit + }) + try { + await transport.connect({ url: '', callbacks: {} }) + await vi.waitFor(() => expect(mocks.subscriptionSendBinary).toHaveBeenCalled()) + setFitOverride('remote:env-1@@terminal-1', scenario.holdMode, 49, 20) + setDriverForPty('remote:env-1@@terminal-1', { kind: 'mobile', clientId: 'phone-1' }) + fitChanged.mockClear() + driverChanged.mockClear() + const initialSubscriptions = mocks.subscribedTerminalHandles().length + onPtySpawn.mockClear() + incarnationId = scenario.next + if (scenario.rotate) { + resolvedPaneHandle = 'terminal-2' + } + subscriptionCallbacks?.onClose?.() + await vi.waitFor(() => + expect(mocks.subscribedTerminalHandles().length).toBeGreaterThan(initialSubscriptions) + ) + if (scenario.mirror || scenario.rotate || scenario.next) { + expect(onPtyRebind).toHaveBeenCalledOnce() + expect(onPtyRebind).toHaveBeenCalledWith( + `remote:env-1@@${resolvedPaneHandle}`, + 'remote:env-1@@terminal-1', + ...(incarnationId ? [incarnationId] : []) + ) + } else { + expect(onPtyRebind).not.toHaveBeenCalled() + } + const nextPtyId = `remote:env-1@@${resolvedPaneHandle}` + expect(getFitOverrideForPty(nextPtyId)).toEqual({ + mode: scenario.holdMode, + cols: 49, + rows: 20 + }) + expect(getDriverForPty(nextPtyId)).toEqual({ kind: 'mobile', clientId: 'phone-1' }) + if (!scenario.rotate) { + expect(fitChanged).not.toHaveBeenCalled() + expect(driverChanged).not.toHaveBeenCalled() + } + expect( + mocks.subscriptionSendBinary.mock.calls.map( + ([bytes]) => decodeTerminalStreamFrame(bytes)?.opcode + ) + ).not.toContain(TerminalStreamOpcode.Resize) + expect( + mocks.subscriptionSendBinary.mock.calls.map( + ([bytes]) => decodeTerminalStreamFrame(bytes)?.opcode + ) + ).not.toContain(TerminalStreamOpcode.ClaimViewport) + expect(onPtySpawn).not.toHaveBeenCalled() + expect(onPtyExit).not.toHaveBeenCalled() + } finally { + unsubscribeFit() + unsubscribeDriver() + transport.destroy?.() + } + } + ) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-published-metadata-order.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-published-metadata-order.test.ts new file mode 100644 index 000000000000..c8c90a8775d1 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-published-metadata-order.test.ts @@ -0,0 +1,119 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types' +import { createDeferred, flushAsyncTicks } from './pty-connection-test-async' +import { + createRemoteRuntimeTransportMocks, + type MultiplexSubscriptionCallbacks +} from './remote-runtime-pty-transport-test-harness' + +let callbacks: MultiplexSubscriptionCallbacks = null +let resolvedHandle = 'terminal-1' +const mocks = createRemoteRuntimeTransportMocks({ + getCallbacks: () => callbacks, + setCallbacks: (next) => { + callbacks = next + }, + getResolvedPaneHandle: () => resolvedHandle, + setResolvedPaneHandle: (next) => { + resolvedHandle = next + } +}) + +function snapshotForHandle(terminal: string): RuntimeMobileSessionTabsResult { + return { + worktree: 'wt-1', + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + 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 + } + ] + } +} + +function metadataForHandle(handle: string) { + return { + ok: true, + result: { + terminal: { + handle, + tabId: 'tab-1', + leafId: 'pane:1', + worktreeId: 'wt-1', + incarnationId: `inc-${handle}` + } + } + } +} + +describe('accepted remote terminal metadata ordering', () => { + beforeEach(() => mocks.resetRemoteRuntimeTransport()) + + it.each(['terminal-3', 'terminal-1'])( + 'does not let an older lookup supersede a newer publication of %s', + async (newerHandle) => { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const events = await import('../../runtime/web-session-terminal-handle-events') + const onPtyRebind = vi.fn() + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'web-terminal-tab-1', + leafId: 'pane:1', + onPtyRebind + }) + try { + transport.attach({ existingPtyId: 'remote:env-1@@terminal-1', callbacks: {} }) + await vi.waitFor(() => expect(mocks.subscriptionSendBinary).toHaveBeenCalled()) + mocks.emitSnapshot(mocks.latestSubscribePayload().streamId, 'initial') + const oldLookup = createDeferred>() + const newLookup = createDeferred>() + let lookupCount = 0 + mocks.runtimeCall.mockImplementation((args: { method: string }) => { + if (args.method === 'terminal.resolvePane') { + lookupCount += 1 + return lookupCount === 1 ? oldLookup.promise : newLookup.promise + } + // Keep the inventory recovery pending so accepted publications own the race. + return new Promise(() => {}) + }) + callbacks?.onClose?.() + await vi.waitFor(() => + expect(events.getWebSessionTerminalHandleSubscriberCountForTests()).toBe(1) + ) + onPtyRebind.mockClear() + events.queueAcceptedWebSessionTerminalSnapshot(snapshotForHandle('terminal-2'), 'env-1') + await vi.waitFor(() => expect(lookupCount).toBe(1)) + events.queueAcceptedWebSessionTerminalSnapshot(snapshotForHandle(newerHandle), 'env-1') + await flushAsyncTicks(4) + expect(lookupCount).toBe(newerHandle === 'terminal-1' ? 1 : 2) + // The old lookup finishes first while the newer publication already owns recovery. + oldLookup.resolve(metadataForHandle('terminal-2')) + await flushAsyncTicks(8) + expect(transport.getPtyId()).toBe('remote:env-1@@terminal-1') + expect(onPtyRebind).not.toHaveBeenCalled() + if (newerHandle !== 'terminal-1') { + newLookup.resolve(metadataForHandle(newerHandle)) + await vi.waitFor(() => expect(transport.getPtyId()).toBe(`remote:env-1@@${newerHandle}`)) + expect(onPtyRebind).toHaveBeenCalledExactlyOnceWith( + `remote:env-1@@${newerHandle}`, + 'remote:env-1@@terminal-1', + `inc-${newerHandle}` + ) + } + } finally { + transport.destroy?.() + } + } + ) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-reattach-redraw.test.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-reattach-redraw.test.ts new file mode 100644 index 000000000000..2849d5caa4ac --- /dev/null +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-reattach-redraw.test.ts @@ -0,0 +1,133 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + createRemoteRuntimeTransportMocks, + type MultiplexSubscriptionCallbacks +} from './remote-runtime-pty-transport-test-harness' + +let callbacks: MultiplexSubscriptionCallbacks = null +let handle = 'terminal-1' +const mocks = createRemoteRuntimeTransportMocks({ + getCallbacks: () => callbacks, + setCallbacks: (next) => { + callbacks = next + }, + getResolvedPaneHandle: () => handle, + setResolvedPaneHandle: (next) => { + handle = next + } +}) + +async function attachTransport(onError = vi.fn()) { + const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') + const transport = createRemoteRuntimePtyTransport('env-1', { + worktreeId: 'wt-1', + tabId: 'tab-1', + leafId: 'pane:1' + }) + transport.attach({ + existingPtyId: 'remote:env-1@@terminal-1', + callbacks: { onError } + }) + await vi.waitFor(() => expect(mocks.subscriptionSendBinary).toHaveBeenCalled()) + mocks.emitSnapshot(mocks.latestSubscribePayload().streamId, 'authoritative state') + await vi.waitFor(() => expect(transport.isConnected()).toBe(true)) + mocks.runtimeCall.mockClear() + mocks.subscriptionSendBinary.mockClear() + return transport +} + +describe('remote reattach viewport redraw', () => { + beforeEach(() => mocks.resetRemoteRuntimeTransport()) + + it('uses one optional-field RPC and clears a queued ordinary resize', async () => { + const transport = await attachTransport() + try { + transport.resize(100, 30) + expect(transport.resize(80, 24, { redraw: true })).toBe(true) + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(mocks.runtimeCall).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + method: 'terminal.updateViewport', + params: { + terminal: 'terminal-1', + client: { id: expect.any(String), type: 'desktop' }, + viewport: { cols: 80, rows: 24 }, + redraw: true + } + }) + ) + expect(mocks.subscriptionSendBinary).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + }) + + it('tolerates an older host that ignores redraw and returns the old reply', async () => { + const onError = vi.fn() + const transport = await attachTransport(onError) + try { + mocks.runtimeCall.mockResolvedValue({ + ok: true, + result: { updated: true, applied: true, seq: 1 } + }) + expect(transport.resize(80, 24, { redraw: true })).toBe(true) + await Promise.resolve() + expect(onError).not.toHaveBeenCalled() + expect(transport.isConnected()).toBe(true) + } finally { + transport.destroy?.() + } + }) + + it('does not turn a best-effort redraw refusal into a terminal error', async () => { + const onError = vi.fn() + const transport = await attachTransport(onError) + try { + mocks.runtimeCall.mockResolvedValue({ + ok: false, + error: { code: 'internal_error', message: 'offline' } + }) + transport.resize(80, 24, { redraw: true }) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(onError).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + }) + + it.each([ + { cols: 10, rows: 4, viewport: { cols: 20, rows: 8 } }, + { cols: 500, rows: 300, viewport: { cols: 240, rows: 120 } } + ])( + 'requests redraw at the host-clamped grid for $cols×$rows panes', + async ({ cols, rows, viewport }) => { + const transport = await attachTransport() + try { + transport.resize(cols, rows, { redraw: true }) + await vi.waitFor(() => + expect(mocks.runtimeCall).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + method: 'terminal.updateViewport', + params: expect.objectContaining({ viewport, redraw: true }) + }) + ) + ) + expect(mocks.subscriptionSendBinary).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + } + ) + + it('does not send redraw after detaching', async () => { + const transport = await attachTransport() + try { + transport.detach?.() + mocks.runtimeCall.mockClear() + expect(transport.resize(80, 24, { redraw: true })).toBe(false) + expect(mocks.runtimeCall).not.toHaveBeenCalled() + } finally { + transport.destroy?.() + } + }) +}) diff --git a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts index cb78db75e9e3..a99ce33e1867 100644 --- a/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts @@ -2,6 +2,7 @@ import { createAgentSessionKeyboardOptions } from '@/runtime/agent-session-keybo import { withRemoteReattachInputBuffer } from './remote-reattach-input-buffer' /* eslint-disable max-lines -- Why: remote PTY transport keeps lifecycle, JSON fallback, and binary stream wiring together so reconnect/destroy ordering stays testable as one behavior surface. */ import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' +import { clampTerminalViewport } from '../../../../shared/terminal-viewport' import { isRecoverableRemoteRuntimeConnectionError, isRuntimeRpcQueueOverloadError, @@ -103,6 +104,7 @@ const TERMINAL_CREATE_RETRY_DELAYS_MS = [250, 500, 1000, 2000, 4000, 8000, 15_00 type HostHandleReplacementPolicy = 'reuse' | 'prefer-replacement' | 'require-replacement' type HostSessionHandleWaitResult = { + incarnationId?: string | null handle: string | null | undefined inventoryFailed: boolean } @@ -210,6 +212,7 @@ export function createRemoteRuntimePtyTransport( let sameHandleEndReuseAttachedAt: number | null = null let attachGeneration = 0 let subscriptionGeneration = 0 + let publishedHandleUpdateSequence = 0 function setAttachmentReady(ready: boolean): void { attachmentReady = ready @@ -533,10 +536,10 @@ export function createRemoteRuntimePtyTransport( ) } - function findReadyHostSessionHandle( + function findReadyHostSessionTerminal( snapshot: RuntimeMobileSessionTabsResult, hostTabId: string - ): string | null { + ): Extract | null { const terminalTabs = getHostSessionTerminalSurfaces(snapshot, hostTabId, { matchRequestedLeaf: false }) @@ -548,8 +551,7 @@ export function createRemoteRuntimePtyTransport( (tab) => tab.status === 'ready' && tab.parentTabId === hostTabId && tab.isActive ) ?? terminalTabs.find((tab) => tab.status === 'ready' && tab.parentTabId === hostTabId)) if (selected?.status === 'ready') { - authoritativePtyIncarnationId = selected.incarnationId ?? null - return selected.terminal + return selected } return null } @@ -624,9 +626,13 @@ export function createRemoteRuntimePtyTransport( throw error } } - const immediate = activated ? findReadyHostSessionHandle(activated, hostTabId) : undefined + if (!isCurrent()) { + return undefined + } + const immediate = activated ? findReadyHostSessionTerminal(activated, hostTabId) : undefined if (immediate) { - return immediate + adoptExecutionMetadata(immediate) + return immediate.terminal } const startedAt = Date.now() @@ -677,9 +683,13 @@ export function createRemoteRuntimePtyTransport( nextRequest = 'list' continue } - const handle = findReadyHostSessionHandle(snapshot, hostTabId) - if (handle) { - return handle + if (!isCurrent()) { + return undefined + } + const terminal = findReadyHostSessionTerminal(snapshot, hostTabId) + if (terminal) { + adoptExecutionMetadata(terminal) + return terminal.terminal } if (request === 'activate') { // Why: an activation response can race host publication, so inventory — not this snapshot — decides what exists. @@ -783,14 +793,18 @@ export function createRemoteRuntimePtyTransport( // 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 lastReadyTerminal: RuntimeMobileSessionTerminalClientTab | null = null const finishBoundedWait = (): HostSessionHandleWaitResult => { const effectivePolicy = stricterReplacementPolicy( replacementPolicy, getRecoveryReplacementPolicy(previousHandle) ) - if (effectivePolicy === 'prefer-replacement' && lastReadyHandle) { - return { handle: lastReadyHandle, inventoryFailed: false } + if (effectivePolicy === 'prefer-replacement' && lastReadyTerminal) { + return { + handle: lastReadyTerminal.terminal, + incarnationId: lastReadyTerminal.incarnationId, + inventoryFailed: false + } } if (lastRequestError) { console.warn( @@ -834,16 +848,21 @@ export function createRemoteRuntimePtyTransport( // must stay slept even though it publishes the same pending status. await activateHostSessionSurface(hostTabId, worktree, 'automatic', requestRemainingMs) lastRequestError = null - const nextHandle = findReadyHostSessionHandle(listed, hostTabId) - if (nextHandle) { - lastReadyHandle = nextHandle + const nextTerminal = findReadyHostSessionTerminal(listed, hostTabId) + const nextHandle = nextTerminal?.terminal + if (nextTerminal) { + lastReadyTerminal = nextTerminal } const effectivePolicy = stricterReplacementPolicy( replacementPolicy, getRecoveryReplacementPolicy(previousHandle) ) if (nextHandle && (effectivePolicy === 'reuse' || nextHandle !== previousHandle)) { - return { handle: nextHandle, inventoryFailed: false } + return { + handle: nextHandle, + incarnationId: nextTerminal?.incarnationId, + inventoryFailed: false + } } if (request === 'list') { if (!hasHostSessionTerminalSurface(listed, hostTabId)) { @@ -930,7 +949,7 @@ export function createRemoteRuntimePtyTransport( } async function attachHostSessionMirror( - options: { cols?: number; rows?: number }, + options: { cols?: number; rows?: number; existingPtyId?: string; sessionId?: string }, notifySpawn = true, expectedAttachGeneration?: number, expectedLifecycleEpoch?: number @@ -967,26 +986,9 @@ export function createRemoteRuntimePtyTransport( return undefined } - if (leafId && worktreeId && !resolvePaneUnavailable) { - try { - const resolved = await callRuntime<{ terminal: RuntimeTerminalResolvePane }>( - 'terminal.resolvePane', - { paneKey: `${hostTabId}:${leafId}`, worktreeId } - ) - const terminal = resolved.terminal - if ( - terminal.handle === hostHandle && - terminal.tabId === hostTabId && - terminal.leafId === leafId && - (!terminal.worktreeId || terminal.worktreeId === worktreeId) - ) { - adoptExecutionMetadata(terminal) - } - } catch (error) { - if (error instanceof RuntimeRpcCallError && error.code === 'method_not_found') { - resolvePaneUnavailable = true - } - } + const executionMetadata = await resolveHostSessionExecutionMetadata(hostTabId, hostHandle) + if (executionMetadata && isCurrent()) { + adoptExecutionMetadata(executionMetadata) } if (!isCurrent() || recovery.currentPhase === 'disconnected') { @@ -1002,6 +1004,13 @@ export function createRemoteRuntimePtyTransport( } if (notifySpawn) { onPtySpawn?.(remotePtyId) + } else if (authoritativePtyIncarnationId) { + // attach() has no result consumer; publish its identity before the first image. + onPtyRebind?.( + remotePtyId, + options.existingPtyId ?? options.sessionId ?? remotePtyId, + authoritativePtyIncarnationId + ) } try { @@ -1023,6 +1032,35 @@ export function createRemoteRuntimePtyTransport( } satisfies PtyConnectResult } + // Older inventory projections omit incarnation even when resolvePane can prove it. + async function resolveHostSessionExecutionMetadata( + hostTabId: string, + hostHandle: string + ): Promise { + if (!leafId || !worktreeId || resolvePaneUnavailable) { + return null + } + try { + const { terminal } = await callRuntime<{ terminal: RuntimeTerminalResolvePane }>( + 'terminal.resolvePane', + { paneKey: `${hostTabId}:${leafId}`, worktreeId } + ) + if ( + terminal.handle === hostHandle && + terminal.tabId === hostTabId && + terminal.leafId === leafId && + (!terminal.worktreeId || terminal.worktreeId === worktreeId) + ) { + return terminal + } + } catch (error) { + if (error instanceof RuntimeRpcCallError && error.code === 'method_not_found') { + resolvePaneUnavailable = true + } + } + return null + } + async function callRuntimeForEnvironment( environmentId: string, method: string, @@ -1266,7 +1304,7 @@ export function createRemoteRuntimePtyTransport( async function adoptResolvedHostPane( terminal: RuntimeTerminalResolvePane, - options: { cols?: number; rows?: number }, + options: { cols?: number; rows?: number; existingPtyId?: string }, notifySpawn = true, expectedAttachGeneration?: number ): Promise { @@ -1289,6 +1327,12 @@ export function createRemoteRuntimePtyTransport( } if (notifySpawn) { onPtySpawn?.(remotePtyId) + } else if (authoritativePtyIncarnationId) { + onPtyRebind?.( + remotePtyId, + options.existingPtyId ?? remotePtyId, + authoritativePtyIncarnationId + ) } emitRecoveryState() try { @@ -1499,13 +1543,14 @@ export function createRemoteRuntimePtyTransport( sendUnacknowledgedInput ) - function sendViewportUpdate(cols: number, rows: number, claim = false): void { + function sendViewportUpdate(cols: number, rows: number, claim = false, redraw = false): void { const targetHandle = handle if (!connected || !targetHandle || recoveryBlocksIo()) { return } const stream = getCurrentMultiplexedStream(targetHandle) - if (claim ? stream?.claimViewport(cols, rows) : stream?.resize(cols, rows)) { + // Redraw rides an optional RPC field, not a new opcode that older hosts silently drop. + if (!redraw && (claim ? stream?.claimViewport(cols, rows) : stream?.resize(cols, rows))) { if (claim && stream) { flushPendingClaimInput(stream) } @@ -1518,7 +1563,8 @@ export function createRemoteRuntimePtyTransport( terminal: targetHandle, client: { id: clientId, type: 'desktop' }, viewport: { cols, rows }, - ...(claim ? { claim: true } : {}) + ...(claim ? { claim: true } : {}), + ...(redraw ? { redraw: true } : {}) }).catch(() => {}) } @@ -1545,6 +1591,7 @@ export function createRemoteRuntimePtyTransport( } function clearPublishedHandleWait(): void { + publishedHandleUpdateSequence += 1 stopWaitingForPublishedHandle?.() stopWaitingForPublishedHandle = null publishedHandleWaitEpoch = null @@ -1601,8 +1648,10 @@ export function createRemoteRuntimePtyTransport( setAttachmentReady(false) // Why: host handle rotation preserves the pane generation; only the store identity changes, not spawn/exit semantics. if (replacedPtyId) { - replaceFitOverridePtyId(replacedPtyId, remotePtyId) - replaceDriverPtyId(replacedPtyId, remotePtyId) + if (replacedPtyId !== remotePtyId) { + replaceFitOverridePtyId(replacedPtyId, remotePtyId) + replaceDriverPtyId(replacedPtyId, remotePtyId) + } if (nextIncarnationId) { onPtyRebind?.(remotePtyId, replacedPtyId, nextIncarnationId) } else { @@ -1623,7 +1672,8 @@ export function createRemoteRuntimePtyTransport( hostTabId, leafId }, - (update) => { + async (update) => { + const updateSequence = ++publishedHandleUpdateSequence if (destroyed || !connected || handle !== previousHandle) { clearPublishedHandleWait() return @@ -1637,7 +1687,10 @@ export function createRemoteRuntimePtyTransport( if (!update.terminalHandle) { return } - if (update.terminalHandle === previousHandle) { + if ( + update.terminalHandle === previousHandle && + (!update.incarnationId || update.incarnationId === authoritativePtyIncarnationId) + ) { // Why: once the auto-recovery window is spent, a host still publishing this surface is evidence the fenced handle outlived the stale error. if (!autoRecoveryWindowSpent || getCurrentMultiplexedStream(previousHandle)) { return @@ -1658,7 +1711,20 @@ export function createRemoteRuntimePtyTransport( // Why: without a live epoch a failed resubscribe is swallowed as already-latched, leaving a pane with no handle and no way back. recovery.begin() } - rebindRemoteTerminalHandle(update.terminalHandle) + const expectedSubscriptionGeneration = subscriptionGeneration + const metadata = update.incarnationId + ? update + : await resolveHostSessionExecutionMetadata(hostTabId, update.terminalHandle) + if ( + destroyed || + !connected || + handle !== previousHandle || + subscriptionGeneration !== expectedSubscriptionGeneration || + publishedHandleUpdateSequence !== updateSequence + ) { + return + } + rebindRemoteTerminalHandle(update.terminalHandle, metadata?.incarnationId ?? null) const reboundHandle = handle const reboundPtyId = remotePtyId void subscribeToHandle().catch((error) => { @@ -1801,8 +1867,20 @@ export function createRemoteRuntimePtyTransport( if (effectivePolicy === 'require-replacement' && nextHandle === previousHandle) { return } - if (nextHandle !== previousHandle) { - rebindRemoteTerminalHandle(nextHandle) + const executionMetadata = waitResult.incarnationId + ? waitResult + : await resolveHostSessionExecutionMetadata(hostTabId, nextHandle) + if ( + destroyed || + !connected || + handle !== previousHandle || + !recovery.isCurrent(recoveryEpoch) + ) { + return + } + const nextIncarnationId = executionMetadata?.incarnationId ?? null + if (nextHandle !== previousHandle || nextIncarnationId !== authoritativePtyIncarnationId) { + rebindRemoteTerminalHandle(nextHandle, nextIncarnationId) } clearPublishedHandleWait() await subscribeToHandle( @@ -1827,10 +1905,13 @@ export function createRemoteRuntimePtyTransport( retireRemoteTerminalId(-1) return } - if (resolved.handle !== previousHandle) { - adoptExecutionMetadata(resolved) + if ( + resolved.handle !== previousHandle || + (resolved.incarnationId ?? null) !== authoritativePtyIncarnationId + ) { rebindRemoteTerminalHandle(resolved.handle, resolved.incarnationId ?? null) } + adoptExecutionMetadata(resolved) clearPublishedHandleWait() await subscribeToHandle( recoveryEpoch, @@ -2672,6 +2753,12 @@ export function createRemoteRuntimePtyTransport( sendViewportUpdate(cols, rows, true) return true } + if (meta?.redraw) { + viewportBatcher.clear() + const viewport = clampTerminalViewport(cols, rows) + sendViewportUpdate(viewport.cols, viewport.rows, false, true) + return true + } // Why: xterm fit emits resize bursts on drag/layout-restore; remote runtimes only need the last viewport per frame. viewportBatcher.queue(cols, rows) return true diff --git a/src/renderer/src/lib/pane-manager/pane-fit-unknown-owner-size.test.ts b/src/renderer/src/lib/pane-manager/pane-fit-unknown-owner-size.test.ts new file mode 100644 index 000000000000..b247d5206eb3 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/pane-fit-unknown-owner-size.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { readProposedPaneFitDimensions, safeFit } from './pane-fit' +import { getFitOverrideForPty, hydrateOverrides, setFitOverride } from './mobile-fit-overrides' +import type { ManagedPane } from './pane-manager-types' + +vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ recordRendererCrashBreadcrumb: vi.fn() })) +afterEach(() => hydrateOverrides([])) + +function createPane(width = 649): ManagedPane { + const terminal = { + cols: 120, + rows: 40, + resize: vi.fn((cols: number, rows: number) => { + terminal.cols = cols + terminal.rows = rows + }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies the pane members safeFit and readProposedPaneFitDimensions read. + return { + terminal, + container: { + dataset: { ptyId: 'held-pty' }, + getBoundingClientRect: () => ({ width, height: 964 }) + }, + fitAddon: { + proposeDimensions: vi.fn(() => ({ cols: 75, rows: 60 })), + fit: vi.fn(() => terminal.resize(75, 60)) + } + } as unknown as ManagedPane +} + +describe('safeFit with an owner whose geometry is unknown', () => { + it.each(['remote-desktop-fit', 'mobile-fit'] as const)( + 'retains the %s hold while fitting locally', + (mode) => { + const pane = createPane() + setFitOverride('held-pty', mode, 0, 0) + expect(readProposedPaneFitDimensions(pane)).toEqual({ cols: 75, rows: 60 }) + expect(safeFit(pane)).toBe(true) + expect(pane.terminal.resize).toHaveBeenCalledWith(75, 60) + expect(pane.terminal.resize).not.toHaveBeenCalledWith(0, 0) + expect(getFitOverrideForPty('held-pty')).toEqual({ mode, cols: 0, rows: 0 }) + setFitOverride('held-pty', mode, 2, 1) + expect(safeFit(pane)).toBe(true) + expect(pane.terminal.resize).toHaveBeenLastCalledWith(2, 1) + } + ) + + it.each([Number.NaN, Infinity, -1])('does not apply invalid owner dimension %s', (cols) => { + const pane = createPane() + setFitOverride('held-pty', 'remote-desktop-fit', cols, 40) + expect(safeFit(pane)).toBe(true) + expect(pane.terminal.resize).toHaveBeenCalledWith(75, 60) + expect(getFitOverrideForPty('held-pty')?.cols).toBe(cols) + }) + + it('does not guess a hidden destination grid', () => { + const pane = createPane(0) + setFitOverride('held-pty', 'remote-desktop-fit', 0, 0) + expect(readProposedPaneFitDimensions(pane)).toBeNull() + expect(safeFit(pane)).toBe(false) + expect(pane.terminal.resize).not.toHaveBeenCalled() + expect(getFitOverrideForPty('held-pty')).not.toBeNull() + }) +}) diff --git a/src/renderer/src/lib/pane-manager/pane-fit.ts b/src/renderer/src/lib/pane-manager/pane-fit.ts index 05e71b294dcd..2ce49ebfe007 100644 --- a/src/renderer/src/lib/pane-manager/pane-fit.ts +++ b/src/renderer/src/lib/pane-manager/pane-fit.ts @@ -63,7 +63,7 @@ export function readProposedPaneFitDimensions( const ptyId = pane.container?.dataset?.ptyId const override = ptyId ? getFitOverrideForPty(ptyId) : null const measurable = canMeasurePaneForFit(pane) - if (!measurable && !override) { + if (!measurable && !(override && hasKnownFitOverrideDimensions(override))) { return null } // Re-check after the metric flush: larger cells can push a narrow pane below @@ -71,12 +71,21 @@ export function readProposedPaneFitDimensions( if (measurable && flushDeferredPaneMetricOptions(pane) && !canMeasurePaneForFit(pane)) { return null } - if (override) { + if (override && hasKnownFitOverrideDimensions(override)) { return { cols: override.cols, rows: override.rows } } return getProposedPaneDimensions(pane) } +function hasKnownFitOverrideDimensions(dimensions: { cols: number; rows: number }): boolean { + return ( + Number.isFinite(dimensions.cols) && + Number.isFinite(dimensions.rows) && + dimensions.cols > 0 && + dimensions.rows > 0 + ) +} + function canPreserveScrollIntentForFit(pane: ManagedPane): boolean { // Why: split reparent has its own delayed restore; restoring here can fight that timer. return !( @@ -108,10 +117,10 @@ function performSafeFit(pane: ManagedPane): boolean { shouldRestoreScroll = true } try { - // Why: a mobile-owned PTY must stay at its phone grid on passive desktop panes. + // Why: an unknown host size retains the hold but cannot size the renderer to zero. const ptyId = pane.container?.dataset?.ptyId const override = ptyId ? getFitOverrideForPty(ptyId) : null - if (override) { + if (override && hasKnownFitOverrideDimensions(override)) { if (pane.terminal.cols !== override.cols || pane.terminal.rows !== override.rows) { if (canPreserveScrollIntentForFit(pane)) { captureScrollForFit() diff --git a/src/renderer/src/runtime/web-session-terminal-handle-events.test.ts b/src/renderer/src/runtime/web-session-terminal-handle-events.test.ts index ebf3616faf86..aa370eb51b96 100644 --- a/src/renderer/src/runtime/web-session-terminal-handle-events.test.ts +++ b/src/renderer/src/runtime/web-session-terminal-handle-events.test.ts @@ -22,41 +22,46 @@ function snapshot( } describe('accepted web-session terminal handle events', () => { - it('notifies only the matching runtime/worktree/pane and releases the listener', async () => { - const listener = vi.fn() - const unsubscribe = subscribeAcceptedWebSessionTerminalHandle( - { environmentId: 'env-1', worktreeId: 'wt-1', hostTabId: 'tab-1', leafId: 'leaf-1' }, - listener - ) + it.each([undefined, 'inc-new'])( + 'notifies only the matching runtime/worktree/pane with optional identity %s and releases the listener', + async (incarnationId) => { + const listener = vi.fn() + const unsubscribe = subscribeAcceptedWebSessionTerminalHandle( + { environmentId: 'env-1', worktreeId: 'wt-1', hostTabId: 'tab-1', leafId: 'leaf-1' }, + listener + ) - queueAcceptedWebSessionTerminalSnapshot(snapshot([]), 'env-2') - queueAcceptedWebSessionTerminalSnapshot(snapshot([], 'wt-2'), 'env-1') - queueAcceptedWebSessionTerminalSnapshot( - snapshot([ - { - type: 'terminal', - id: 'tab-1::leaf-1', - parentTabId: 'tab-1', - leafId: 'leaf-1', - title: 'Claude Code', - isActive: true, - status: 'ready', - terminal: 'terminal-replacement' - } - ]), - 'env-1' - ) - await Promise.resolve() + queueAcceptedWebSessionTerminalSnapshot(snapshot([]), 'env-2') + queueAcceptedWebSessionTerminalSnapshot(snapshot([], 'wt-2'), 'env-1') + queueAcceptedWebSessionTerminalSnapshot( + snapshot([ + { + type: 'terminal', + id: 'tab-1::leaf-1', + parentTabId: 'tab-1', + leafId: 'leaf-1', + title: 'Claude Code', + isActive: true, + status: 'ready', + terminal: 'terminal-replacement', + incarnationId + } + ]), + 'env-1' + ) + await Promise.resolve() - expect(listener).toHaveBeenCalledOnce() - expect(listener).toHaveBeenCalledWith({ - surfacePresent: true, - terminalHandle: 'terminal-replacement' - }) - expect(getWebSessionTerminalHandleSubscriberCountForTests()).toBe(1) - unsubscribe() - expect(getWebSessionTerminalHandleSubscriberCountForTests()).toBe(0) - }) + expect(listener).toHaveBeenCalledOnce() + expect(listener).toHaveBeenCalledWith({ + surfacePresent: true, + terminalHandle: 'terminal-replacement', + ...(incarnationId ? { incarnationId } : {}) + }) + expect(getWebSessionTerminalHandleSubscriberCountForTests()).toBe(1) + unsubscribe() + expect(getWebSessionTerminalHandleSubscriberCountForTests()).toBe(0) + } + ) it('distinguishes a pending handle from an explicitly removed surface', async () => { const listener = vi.fn() diff --git a/src/renderer/src/runtime/web-session-terminal-handle-events.ts b/src/renderer/src/runtime/web-session-terminal-handle-events.ts index 2fb22b8437be..7b90abdc45b7 100644 --- a/src/renderer/src/runtime/web-session-terminal-handle-events.ts +++ b/src/renderer/src/runtime/web-session-terminal-handle-events.ts @@ -6,6 +6,7 @@ import type { export type WebSessionTerminalHandleUpdate = { surfacePresent: boolean terminalHandle: string | null + incarnationId?: string | null } type TerminalHandleSubscriber = { @@ -48,7 +49,8 @@ function resolveSubscriberUpdate( mirroredSurfaces.find((surface) => surface.status === 'ready') return { surfacePresent: true, - terminalHandle: readySurface?.terminal ?? null + terminalHandle: readySurface?.terminal ?? null, + ...(readySurface?.incarnationId ? { incarnationId: readySurface.incarnationId } : {}) } } diff --git a/src/shared/rpc-contract/terminal-viewport-schemas-params.ts b/src/shared/rpc-contract/terminal-viewport-schemas-params.ts index 416ce7859e08..5bb4100cc096 100644 --- a/src/shared/rpc-contract/terminal-viewport-schemas-params.ts +++ b/src/shared/rpc-contract/terminal-viewport-schemas-params.ts @@ -44,7 +44,9 @@ export const TerminalUpdateViewport = TerminalHandle.extend({ cols: z.number().int().min(20).max(240), rows: z.number().int().min(8).max(120) }), - claim: z.boolean().optional() + claim: z.boolean().optional(), + // Older hosts strip this field and retain their existing viewport behavior. + redraw: z.boolean().optional() }) // Why: phone-fit auto-restore preference (docs/mobile-fit-hold.md); `null` = Indefinite, finite ms clamped to [5_000, 60min] server-side. diff --git a/src/shared/terminal-viewport.ts b/src/shared/terminal-viewport.ts new file mode 100644 index 000000000000..3130f9a1a06a --- /dev/null +++ b/src/shared/terminal-viewport.ts @@ -0,0 +1,7 @@ +// Clamp terminal dimensions to the PTY's supported range (cols 20–240, rows 8–120). +export function clampTerminalViewport(cols: number, rows: number): { cols: number; rows: number } { + return { + cols: Math.max(20, Math.min(240, Math.round(cols))), + rows: Math.max(8, Math.min(120, Math.round(rows))) + } +} diff --git a/tests/e2e/helpers/remote-terminal-geometry-probe.ts b/tests/e2e/helpers/remote-terminal-geometry-probe.ts new file mode 100644 index 000000000000..79aa6a3f1afa --- /dev/null +++ b/tests/e2e/helpers/remote-terminal-geometry-probe.ts @@ -0,0 +1,51 @@ +import type { Page } from '@stablyai/playwright-test' + +/** Records the actual mutation and its renderer metrics without changing terminal input. */ +export async function installRemoteTerminalGeometryProbe(page: Page, tabId: string): Promise { + await page.evaluate((id) => { + const pane = window.__paneManagers?.get(id)?.getActivePane?.() + if (!pane) { + throw new Error('No pane for geometry probe') + } + const events: unknown[] = [] + Reflect.set(window, '__remoteTerminalGeometryEvents', events) + const measure = () => { + const parent = pane.terminal.element?.parentElement + const core = Reflect.get(pane.terminal, '_core') + const style = parent ? getComputedStyle(parent) : null + return { + grid: { cols: pane.terminal.cols, rows: pane.terminal.rows }, + parent: { width: style?.width, height: style?.height, display: style?.display }, + cell: core?._renderService?.dimensions?.css?.cell, + ptyId: pane.container.dataset.ptyId, + time: performance.now() + } + } + const resize = pane.terminal.resize.bind(pane.terminal) + pane.terminal.resize = (cols, rows) => { + events.push({ + kind: 'resize', + cols, + rows, + ...measure(), + stack: new Error('terminal resize').stack + }) + resize(cols, rows) + } + const propose = pane.fitAddon.proposeDimensions.bind(pane.fitAddon) + pane.fitAddon.proposeDimensions = () => { + const proposal = propose() + events.push({ + kind: 'proposal', + proposal, + ...measure(), + stack: new Error('fit proposal').stack + }) + return proposal + } + }, tabId) +} + +export async function readRemoteTerminalGeometryProbe(page: Page): Promise { + return page.evaluate(() => Reflect.get(window, '__remoteTerminalGeometryEvents')) +} diff --git a/tests/e2e/paired-remote-terminal-replacement-state.spec.ts b/tests/e2e/paired-remote-terminal-replacement-state.spec.ts new file mode 100644 index 000000000000..1042dcf61150 --- /dev/null +++ b/tests/e2e/paired-remote-terminal-replacement-state.spec.ts @@ -0,0 +1,428 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { + expect, + test, + type ElectronApplication, + type Page, + type TestInfo +} from '@stablyai/playwright-test' +import { + installRemoteTerminalGeometryProbe, + readRemoteTerminalGeometryProbe +} from './helpers/remote-terminal-geometry-probe' +import { toWebTerminalSurfaceTabId } from '../../src/shared/terminal-surface-id' +import { toRemoteRuntimePtyId } from '../../src/shared/remote-runtime-pty-id' +import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import { launchPairedElectronClient } from './helpers/paired-electron-client' +import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' +import { + createHostCliTerminal, + readSink, + type RuntimeRpcCall +} from './helpers/host-created-terminal-retention-oracle' + +type TerminalSummary = { + handle: string + ptyId: string + incarnationId: string + agentIdentity?: string +} + +async function verifyReleaseBuild(app: ElectronApplication) { + const observed = await app.evaluate(({ app }) => ({ + appVersion: app.getVersion(), + electronVersion: process.versions.electron, + userDataDir: app.getPath('userData') + })) + const manifest = JSON.parse(readFileSync(path.join(process.cwd(), 'package.json'), 'utf8')) + const electronManifest = JSON.parse( + readFileSync(path.join(process.cwd(), 'node_modules', 'electron', 'package.json'), 'utf8') + ) + expect(observed.appVersion).toBe(manifest.version) + expect(observed.electronVersion).toBe(electronManifest.version) + return observed +} + +async function captureHiddenRenderer(page: Page, testInfo: TestInfo, name: string): Promise { + const cdp = await page.context().newCDPSession(page) + try { + const { data } = await cdp.send('Page.captureScreenshot', { format: 'png' }) + const screenshot = testInfo.outputPath(`${name}.png`) + writeFileSync(screenshot, Buffer.from(data, 'base64')) + await testInfo.attach(name, { path: screenshot, contentType: 'image/png' }) + } finally { + await cdp.detach() + } +} + +async function inspectPane(page: Page, tabId: string) { + return page.evaluate((id) => { + const manager = window.__paneManagers?.get(id) + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] + if (!pane) { + return null + } + const terminal = pane.terminal + const buffer = terminal.buffer.active + let text = '' + let invisibleCharacters = 0 + for (let y = 0; y < buffer.length; y++) { + const line = buffer.getLine(y) + text += `${y > 0 && !line?.isWrapped ? '\n' : ''}${line?.translateToString(true) ?? ''}` + for (let x = 0; x < terminal.cols; x++) { + const cell = line?.getCell(x) + if (cell?.getChars().trim() && cell.isInvisible()) { + invisibleCharacters++ + } + } + } + const prior = Reflect.get(window, '__replacementOriginalTerminal') + const state = window.__store?.getState() + return { + sameTerminal: terminal === prior, + mouseMode: terminal.modes.mouseTrackingMode, + bufferType: buffer.type, + viewportY: buffer.viewportY, + baseY: buffer.baseY, + text, + cols: terminal.cols, + rows: terminal.rows, + proposedGrid: pane.fitAddon.proposeDimensions(), + documentVisibility: document.visibilityState, + containerSize: { + width: pane.container.getBoundingClientRect().width, + height: pane.container.getBoundingClientRect().height + }, + agentStates: Object.values(state?.agentStatusByPaneKey ?? {}).map((entry) => ({ + agentType: entry.agentType, + state: entry.state, + terminalTitle: entry.terminalTitle + })), + invisibleCharacters, + title: state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find((tab) => tab.id === id) + ?.title, + ptyId: pane.container.dataset.ptyId, + recoveryPhase: pane.container.dataset.ptyRecoveryState + } + }, tabId) +} + +async function probeMouse(page: Page, tabId: string) { + return page.evaluate(async (id) => { + const manager = window.__paneManagers?.get(id) + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] + const screen = pane?.terminal.element?.querySelector('.xterm-screen') + if (!pane || !screen) { + throw new Error('No rendered terminal for mouse probe') + } + const terminal = pane.terminal + const reports: string[] = [] + const listener = terminal.onData((data) => { + if (data.includes('\x1b[<')) { + reports.push(data) + } + }) + const before = terminal.buffer.active.viewportY + try { + const rect = screen.getBoundingClientRect() + if (rect.width <= 0 || rect.height <= 0) { + throw new Error('Terminal has no layout') + } + for (const fraction of [0.2, 0.4, 0.6, 0.8]) { + screen.dispatchEvent( + new MouseEvent('mousemove', { + bubbles: true, + clientX: rect.x + rect.width * fraction, + clientY: rect.y + rect.height * 0.5, + buttons: 0 + }) + ) + } + screen.dispatchEvent( + new WheelEvent('wheel', { + bubbles: true, + cancelable: true, + deltaY: -120, + clientX: rect.x + rect.width * 0.5, + clientY: rect.y + rect.height * 0.5 + }) + ) + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + return { reports, before, after: terminal.buffer.active.viewportY } + } finally { + listener.dispose() + } + }, tabId) +} + +// oxlint-disable-next-line no-empty-pattern -- Manually owned host/client fixtures; testInfo is the second argument. +test('retained remote pane reconciles replacement shell and preserves a surviving agent', async ({}, testInfo) => { + test.skip(process.platform === 'win32', 'This diagnostic reproduces the POSIX shell replacement') + expect(process.env.ORCA_BACKGROUND_LAUNCH).toBe('1') + const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-replacement-state-')) + const fixturePath = path.join(scratch, 'agent.mjs') + const sinkPath = path.join(scratch, 'agent.log') + writeFileSync( + fixturePath, + [ + "import { appendFileSync } from 'node:fs'", + 'const sink = process.argv[2]', + 'appendFileSync(sink, `READY:${process.pid}\\n`)', + 'process.stdin.setRawMode?.(true)', + "process.stdout.write('\\x1b]0;π - replacement-test\\x07')", + 'process.stdout.write(\'\\x1b]9999;{"state":"idle","agentType":"pi"}\\x07\')', + 'for (let i = 0; i < 80; i++) process.stdout.write(`OLD_AGENT_ROW_${i}\\r\\n`)', + "process.stdout.write('AGENT_READY\\r\\n\\x1b[?1003h\\x1b[?1006h')", + 'process.stdin.on(\'data\', data => { appendFileSync(sink, `INPUT:${JSON.stringify(data.toString())}\\n`); if (data.toString().includes(\'WARM_PROBE\')) process.stdout.write(\'WARM_PROBE_ACK\\r\\n\'); if (data.toString().includes(\'ARM_STATUS\')) process.stdout.write(\'\\x1b]9999;{"state":"working","prompt":"fixture","agentType":"pi"}\\x07\') })', + 'let repaints = 0', + "process.on('SIGWINCH', () => { const marker = `WINCH_REPAINT_${++repaints}`; appendFileSync(sink, `${marker}\\n`); process.stdout.write(`${marker}\\r\\n`) })", + 'process.stdin.resume()' + ].join('\n') + ) + const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) + let client: Awaited> | undefined + const evidence: Record = {} + const hostCall: RuntimeRpcCall = async (method, params) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each call site names the result shape of the runtime RPC method it invokes. + (await host.client.call(method, params)).result as never + try { + evidence.hostBuild = await verifyReleaseBuild(host.app) + const added = await hostCall<{ repo: { id: string } }>('repo.add', { + path: scratch, + kind: 'folder' + }) + const listed = await hostCall<{ worktrees: { id: string }[] }>('worktree.list', { + repo: `id:${added.repo.id}` + }) + const worktreeId = listed.worktrees[0]?.id + if (!worktreeId) { + throw new Error('Host did not create the disposable folder workspace') + } + const created = await createHostCliTerminal(hostCall, worktreeId, fixturePath, sinkPath) + const before = await hostCall<{ terminal: TerminalSummary }>('terminal.show', { + terminal: created.handle + }) + evidence.hostBefore = before.terminal + const webTabId = toWebTerminalSurfaceTabId(created.tabId) + client = await launchPairedElectronClient(host.offer, testInfo, 'replacement-test') + evidence.clientBuild = await verifyReleaseBuild(client.app) + const { page } = client + await expect + .poll( + () => + page.evaluate( + (id) => + window.__store + ?.getState() + .allWorktrees() + .some((w) => w.id === id), + worktreeId + ), + { timeout: 60_000 } + ) + .toBe(true) + await page.evaluate( + ({ worktreeId, environmentId }) => { + window.__store?.getState().setActiveView('terminal') + window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) + }, + { worktreeId, environmentId: client.environmentId } + ) + await page + .locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) + .click({ timeout: 60_000 }) + await expect + .poll(async () => (await inspectPane(page, webTabId))?.text, { timeout: 30_000 }) + .toContain('AGENT_READY') + await page.evaluate((id) => { + const manager = window.__paneManagers?.get(id) + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] + Reflect.set(window, '__replacementOriginalTerminal', pane?.terminal) + }, webTabId) + await expect.poll(async () => (await inspectPane(page, webTabId))?.mouseMode).toBe('any') + await hostCall('terminal.send', { terminal: created.handle, text: 'ARM_STATUS' }) + await expect + .poll( + async () => + (await inspectPane(page, webTabId))?.agentStates.some( + (entry) => entry.agentType === 'pi' && entry.state === 'working' + ), + { timeout: 15_000 } + ) + .toBe(true) + await installRemoteTerminalGeometryProbe(page, webTabId) + evidence.before = await inspectPane(page, webTabId) + const mouseBefore = await probeMouse(page, webTabId) + evidence.mouseBefore = mouseBefore + expect(mouseBefore.reports.length).toBeGreaterThan(0) + await captureHiddenRenderer(page, testInfo, 'before-restart') + + const repaintsBeforeRestart = (readSink(sinkPath).match(/WINCH_REPAINT_/g) ?? []).length + // A process-only serve restart must not be confused with replacing its daemon-backed PTY. + await host.restartServeProcess() + evidence.warmHostBuild = await verifyReleaseBuild(host.app) + await expect + .poll(async () => (await inspectPane(page, webTabId))?.text, { timeout: 45_000 }) + .toContain('AGENT_READY') + let warm: TerminalSummary | undefined + await expect + .poll( + async () => { + const inventory = await hostCall<{ terminals: TerminalSummary[] }>('terminal.list', { + worktree: `id:${worktreeId}` + }) + warm = inventory.terminals.find((t) => t.ptyId === before.terminal.ptyId) + return warm?.incarnationId + }, + { timeout: 45_000 } + ) + .toBe(before.terminal.incarnationId) + if (!warm) { + throw new Error('Host did not re-publish the surviving terminal') + } + // An idle foreground process must repaint before any user input wakes it. + await expect + .poll(() => (readSink(sinkPath).match(/WINCH_REPAINT_/g) ?? []).length, { timeout: 30_000 }) + .toBeGreaterThan(repaintsBeforeRestart) + await expect + .poll(async () => (await inspectPane(page, webTabId))?.text, { timeout: 30_000 }) + .toContain(`WINCH_REPAINT_${repaintsBeforeRestart + 1}`) + await hostCall('terminal.send', { terminal: warm.handle, text: 'WARM_PROBE' }) + await expect + .poll(async () => (await inspectPane(page, webTabId))?.text, { + timeout: 45_000 + }) + .toContain('WARM_PROBE_ACK') + evidence.warmImmediate = await inspectPane(page, webTabId) + await expect + .configure({ soft: true }) + .poll( + async () => { + const pane = await inspectPane(page, webTabId) + return Boolean( + pane && pane.cols === pane.proposedGrid?.cols && pane.rows === pane.proposedGrid?.rows + ) + }, + { timeout: 10_000, message: 'Reconnect geometry did not recover within 10 seconds' } + ) + .toBe(true) + const warmPane = await inspectPane(page, webTabId) + evidence.warm = warmPane + await captureHiddenRenderer(page, testInfo, 'after-warm-restart') + expect.soft(warmPane?.sameTerminal).toBe(true) + expect.soft(warmPane?.mouseMode).toBe('any') + const mouseWarm = await probeMouse(page, webTabId) + evidence.mouseWarm = mouseWarm + expect.soft(mouseWarm.reports.length).toBeGreaterThan(0) + + // Only the daemon owned by this freshly-created temporary profile is retired. + await host.restartServeProcess({ betweenProcesses: () => cleanupE2EDaemons(host.userDataDir) }) + evidence.replacementHostBuild = await verifyReleaseBuild(host.app) + let replacement: TerminalSummary | undefined + await expect + .poll( + async () => { + const inventory = await hostCall<{ terminals: TerminalSummary[] }>('terminal.list', { + worktree: `id:${worktreeId}` + }) + replacement = inventory.terminals.find((t) => t.ptyId === before.terminal.ptyId) + return Boolean( + replacement?.incarnationId && + replacement.incarnationId !== before.terminal.incarnationId + ) + }, + { timeout: 60_000 } + ) + .toBe(true) + if (!replacement) { + throw new Error('Host never published the replacement terminal') + } + evidence.hostAfter = replacement + evidence.hostSessionAfter = await hostCall('session.tabs.list', { + worktree: `id:${worktreeId}` + }) + const hostScreen = await hostCall<{ terminal: { tail: string[]; source?: string } }>( + 'terminal.read', + { terminal: replacement.handle, screen: true } + ) + evidence.hostScreen = hostScreen + await expect + .poll( + async () => { + const pane = await inspectPane(page, webTabId) + return { ptyId: pane?.ptyId, phase: pane?.recoveryPhase } + }, + { timeout: 45_000 } + ) + .toEqual({ + ptyId: toRemoteRuntimePtyId(replacement.handle, client.environmentId), + phase: 'connected' + }) + await expect + .configure({ soft: true }) + .poll( + async () => { + const pane = await inspectPane(page, webTabId) + return Boolean( + pane && + pane.mouseMode === 'none' && + pane.cols === pane.proposedGrid?.cols && + pane.rows === pane.proposedGrid?.rows && + !pane.agentStates.some((entry) => entry.agentType === 'pi' && entry.state === 'working') + ) + }, + { timeout: 10_000, message: 'Replacement retained agent modes/status after settling' } + ) + .toBe(true) + const after = await inspectPane(page, webTabId) + evidence.after = after + const mouseAfter = await probeMouse(page, webTabId) + evidence.mouseAfter = mouseAfter + const afterMouse = await hostCall<{ terminal: { tail: string[] } }>('terminal.read', { + terminal: replacement.handle, + screen: true + }) + evidence.hostScreenAfterMouse = afterMouse + await captureHiddenRenderer(page, testInfo, 'after-replacement') + expect.soft(after?.sameTerminal).toBe(true) + expect.soft(after?.mouseMode).toBe('none') + expect.soft(after?.invisibleCharacters).toBe(0) + expect.soft(mouseAfter.reports).toHaveLength(0) + expect + .soft( + after?.agentStates.some((entry) => entry.agentType === 'pi' && entry.state === 'working') + ) + .toBe(false) + expect.soft(after?.cols).toBe(after?.proposedGrid?.cols) + expect.soft(after?.rows).toBe(after?.proposedGrid?.rows) + expect(hostScreen.terminal.source).toBe('screen') + const prompt = hostScreen.terminal.tail.at(-1)?.trim() + expect(prompt).toBeTruthy() + expect.soft(after?.text).toContain(prompt) + expect.soft(afterMouse.terminal.tail.join('\n')).not.toMatch(/(?:35|64);\d+;\d+[Mm]/) + expect + .soft( + readSink(sinkPath) + .split('\n') + .filter((line) => line.startsWith('READY:')) + ) + .toHaveLength(1) + } finally { + if (client) { + evidence.geometryEvents = await readRemoteTerminalGeometryProbe(client.page).catch(() => null) + } + evidence.fixtureLog = readSink(sinkPath) + writeFileSync( + testInfo.outputPath('replacement-evidence.json'), + JSON.stringify(evidence, null, 2) + ) + try { + await client?.dispose() + } finally { + await host.dispose() + rmSync(scratch, { recursive: true, force: true }) + } + } +}) diff --git a/tests/playwright.remote-replacement.config.ts b/tests/playwright.remote-replacement.config.ts new file mode 100644 index 000000000000..8ca6343f0dcb --- /dev/null +++ b/tests/playwright.remote-replacement.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from '@stablyai/playwright-test' + +process.env.ORCA_BACKGROUND_LAUNCH = '1' + +// This diagnostic owns its profiles and builds explicitly; no global CLI installation or SSH setup. +export default defineConfig({ + testDir: './e2e', + testMatch: 'paired-remote-terminal-replacement-state.spec.ts', + timeout: 420_000, + workers: 1, + retries: 0, + reporter: 'list', + outputDir: '../test-results/remote-replacement', + use: { trace: 'retain-on-failure' } +})