From daba81e8cf81e2be9b4ddcd6c8c599499610b48c Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sat, 25 Jul 2026 19:33:09 -0700 Subject: [PATCH] fix(terminal): recover wedged panes after input (#10617) * fix(terminal): recover wedged panes after input * refactor(terminal): make wedge probes explicit * fix(terminal): require quiet parser before recovery --- .../terminal-pane/pty-connection.test.ts | 50 ++++++++++++ .../terminal-pane/pty-connection.ts | 9 ++- .../terminal-write-pipeline-health.test.ts | 44 +++++++++++ .../terminal-write-pipeline-health.ts | 77 +++++++++++++++---- 4 files changed, 160 insertions(+), 20 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index cd03a7669..ab40d2246 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -4777,6 +4777,56 @@ describe('connectPanePty', () => { expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled() }) + it('recovers a wedged write pipeline after accepted input without renderer output', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const { settleTerminalWriteStallWatch, WRITE_PIPELINE_STALL_CHECK_MS } = + await import('@/lib/pane-manager/terminal-write-pipeline-health') + const remountTerminalTabForRecovery = vi.fn<(tabId: string) => boolean>(() => true) + mockStoreState = { ...mockStoreState, remountTerminalTabForRecovery } as StoreState + const transport = createMockTransport('pty-wedged') + transportFactoryQueue.push(transport) + const pane = createPane(1) + const binding = connectPanePty(pane as never, createManager(1) as never, createDeps() as never) + await flushAsyncTicks() + pane.terminal.write.mockClear() + pane.terminal.write.mockImplementation(() => {}) + + sendTerminalInputThroughPane(pane, 'x') + settleTerminalWriteStallWatch(pane.terminal) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS * 2) + await flushAsyncTicks() + + expect(transport.sendInput).toHaveBeenCalledWith('x') + expect(pane.terminal.write).toHaveBeenCalledWith('', expect.any(Function)) + expect(remountTerminalTabForRecovery).toHaveBeenCalledWith('tab-1') + binding.dispose() + }) + + it('does not arm the wedge probe when acknowledged input is rejected', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const { WRITE_PIPELINE_STALL_CHECK_MS } = + await import('@/lib/pane-manager/terminal-write-pipeline-health') + const transport = createMockTransport('pty-rejected') + transport.sendInputAccepted = vi.fn().mockResolvedValue(false) + transportFactoryQueue.push(transport) + const pane = createPane(1) + const binding = connectPanePty(pane as never, createManager(1) as never, createDeps() as never) + await flushAsyncTicks() + pane.terminal.write.mockClear() + pane.terminal.write.mockImplementation(() => {}) + + sendTerminalInputThroughPane(pane, '\x03') + await flushAsyncTicks() + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS * 2) + await flushAsyncTicks() + + expect(transport.sendInputAccepted).toHaveBeenCalledWith('\x03') + expect(pane.terminal.write).not.toHaveBeenCalledWith('', expect.any(Function)) + binding.dispose() + }) + it('blocks input when tab-level ptyId is stale even if panePtyId is null', async () => { const { connectPanePty } = await import('./pty-connection') diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 90c7aa097..df1e39e6e 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -76,7 +76,8 @@ import { } from './replay-guard' import { isTerminalWritePipelineCertifiedDead, - registerUndeliverableWriteHandler + registerUndeliverableWriteHandler, + requestTerminalWritePipelineProbe } from '@/lib/pane-manager/terminal-write-pipeline-health' import { captureTerminalPaneRecoveryGeneration, @@ -3357,6 +3358,8 @@ export function connectPanePty( const MAX_DEFERRED_REATTACH_LIVE_CHUNKS = 1_024 const markTerminalInputSent = (): void => { lastTerminalInputAt = performance.now() + // Why: input must probe a wedged xterm even when the PTY produces no renderer output. + requestTerminalWritePipelineProbe(pane.terminal) } const recordTerminalInputForHibernation = (): void => { useAppStore.getState().recordTerminalInput(cacheKey) @@ -3728,12 +3731,12 @@ export function connectPanePty( cancelSuspendedShellCommandInference() } clearPendingTerminalInputIntent() - markTerminalInputSent() const writePromise = transport .sendInputAccepted(data) .then((accepted) => { if (accepted) { - recordTerminalInputForHibernationFallback() + // Why: rejected writes use transport recovery and must not arm a parser probe. + markAcceptedTerminalInputSent() observeAcceptedShellCommandInput(data) observeAcceptedTerminalInput(data, acknowledgedIntent) interruptInference.observeInputIntent(acknowledgedIntent) diff --git a/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.test.ts b/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.test.ts index 960c0c541..f88cbe02f 100644 --- a/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.test.ts +++ b/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.test.ts @@ -9,6 +9,7 @@ import { isTerminalWritePipelineCertifiedDead, notifyUndeliverableWrite, registerUndeliverableWriteHandler, + requestTerminalWritePipelineProbe, settleTerminalWriteStallWatch, WRITE_PIPELINE_STALL_CHECK_MS } from './terminal-write-pipeline-health' @@ -113,6 +114,23 @@ describe('terminal write pipeline health', () => { _resetWritePipelineHealthForTests(terminal) }) + it('keeps a requested probe armed through unrelated parse progress', () => { + vi.useFakeTimers() + const terminal = makeTerminal() + terminal.dropCallbacks = true + const handler = vi.fn() + registerUndeliverableWriteHandler(terminal, handler) + + armTerminalWriteStallWatch(terminal) + requestTerminalWritePipelineProbe(terminal) + settleTerminalWriteStallWatch(terminal) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS * 2) + + expect(handler).toHaveBeenCalledWith('write-stalled') + expect(isTerminalWritePipelineCertifiedDead(terminal)).toBe(true) + _resetWritePipelineHealthForTests(terminal) + }) + it('a slow-but-alive pipeline disarms when the probe parses', () => { vi.useFakeTimers() const terminal = makeTerminal() @@ -218,6 +236,32 @@ describe('terminal write pipeline health', () => { _resetWritePipelineHealthForTests(terminal) }) + it('keeps a requested probe alive while the pipeline makes parse progress', () => { + vi.useFakeTimers() + const terminal = makeTerminal() + terminal.dropCallbacks = true + const handler = vi.fn() + registerUndeliverableWriteHandler(terminal, handler) + + requestTerminalWritePipelineProbe(terminal) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS / 2) + settleTerminalWriteStallWatch(terminal) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS / 2) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS / 2) + settleTerminalWriteStallWatch(terminal) + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS / 2) + + expect(handler).not.toHaveBeenCalled() + expect(isTerminalWritePipelineCertifiedDead(terminal)).toBe(false) + + vi.advanceTimersByTime(WRITE_PIPELINE_STALL_CHECK_MS) + + expect(handler).toHaveBeenCalledWith('write-stalled') + expect(isTerminalWritePipelineCertifiedDead(terminal)).toBe(true) + _resetWritePipelineHealthForTests(terminal) + }) + it('notifies at most once per terminal instance', () => { const terminal = makeTerminal() const handler = vi.fn() diff --git a/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.ts b/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.ts index 39e0b72c2..5c67e7138 100644 --- a/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.ts +++ b/src/renderer/src/lib/pane-manager/terminal-write-pipeline-health.ts @@ -6,10 +6,11 @@ // delivery ack credits leak, and the pane becomes a fossil the user can only // cure by reloading the window. Detection here is probe-certified (mirroring // replay-guard.ts): a stalled completion triggers an empty probe write; xterm -// parses in FIFO order, so a probe that also never completes proves the -// pipeline is dead rather than slow. Certification notifies a per-terminal -// handler (registered by the pane's PTY connection) that requests pane -// recovery — a remount that rebuilds the xterm and reattaches the live PTY. +// parses in FIFO order, so a completing probe proves preceding work drained. A +// silent probe is only certified dead after a full interval without any parse +// progress. Certification notifies a per-terminal handler (registered by the +// pane's PTY connection) that requests pane recovery — a remount that rebuilds +// the xterm and reattaches the live PTY. type WriteTarget = { write(data: string, callback?: () => void): void @@ -42,9 +43,12 @@ export function hasTerminalParseProgressSince(terminal: object, generation: numb return captureTerminalParseProgressGeneration(terminal) !== generation } +type StallWatchMode = 'output-completion' | 'fifo-probe' + type StallWatch = { timer: ReturnType onCertifiedDead?: () => void + mode: StallWatchMode } const stallWatchByTerminal = new WeakMap() @@ -106,31 +110,54 @@ export function isTerminalWritePipelineCertifiedDead(terminal: object): boolean * Arm (or keep armed) the stall watch for a terminal that just had a write * issued. Cleared by settleTerminalWriteStallWatch from the write-completion * callback. If the completion never arrives, an empty probe write certifies - * dead-vs-slow exactly like replay-guard.ts: probe completes → pipeline is - * alive (slow parse), re-arm and keep waiting; probe silent for another - * interval → dead, notify. + * dead-vs-slow conservatively like replay-guard.ts: probe completes → pipeline + * is alive (slow parse), re-arm and keep waiting; probe silent for another + * interval without any parse progress → dead, notify. */ -export function armTerminalWriteStallWatch( +function armTerminalWritePipelineWatch( terminal: WriteTarget, - options: { onCertifiedDead?: () => void; stallCheckMs?: number } = {} + options: { + mode: StallWatchMode + onCertifiedDead?: () => void + stallCheckMs?: number + } ): void { - if (stallWatchByTerminal.has(terminal) || certifiedDeadTerminals.has(terminal)) { + if (certifiedDeadTerminals.has(terminal)) { + return + } + const existingWatch = stallWatchByTerminal.get(terminal) + if (existingWatch) { + if (options.mode === 'fifo-probe') { + existingWatch.mode = 'fifo-probe' + } return } const stallCheckMs = options.stallCheckMs ?? WRITE_PIPELINE_STALL_CHECK_MS const watch: StallWatch = { + mode: options.mode, onCertifiedDead: options.onCertifiedDead, timer: setTimeout(probeForStall, stallCheckMs) } const certifyDead = (): void => certifyTerminalWritePipelineDead(terminal, watch) + function armProbeQuietWindow(quietSinceGeneration: number): void { + watch.timer = setTimeout(() => { + if (stallWatchByTerminal.get(terminal) !== watch) { + return + } + if (hasTerminalParseProgressSince(terminal, quietSinceGeneration)) { + armProbeQuietWindow(captureTerminalParseProgressGeneration(terminal)) + return + } + certifyDead() + }, stallCheckMs) + } function probeForStall(): void { if (stallWatchByTerminal.get(terminal) !== watch) { return } - let probeParsed = false + const probeQueuedAtGeneration = captureTerminalParseProgressGeneration(terminal) try { terminal.write('', () => { - probeParsed = true // Why: replay guards share this terminal-scoped generation; even an // auxiliary FIFO probe proves the parser is alive and making progress. recordTerminalParseProgress(terminal) @@ -146,15 +173,28 @@ export function armTerminalWriteStallWatch( certifyDead() return } - watch.timer = setTimeout(() => { - if (!probeParsed) { - certifyDead() - } - }, stallCheckMs) + if (stallWatchByTerminal.get(terminal) === watch) { + armProbeQuietWindow(probeQueuedAtGeneration) + } } stallWatchByTerminal.set(terminal, watch) } +export function armTerminalWriteStallWatch( + terminal: WriteTarget, + options: { onCertifiedDead?: () => void; stallCheckMs?: number } = {} +): void { + armTerminalWritePipelineWatch(terminal, { ...options, mode: 'output-completion' }) +} + +/** Require the active watch to reach its FIFO probe before it may settle. */ +export function requestTerminalWritePipelineProbe( + terminal: WriteTarget, + options: { stallCheckMs?: number } = {} +): void { + armTerminalWritePipelineWatch(terminal, { ...options, mode: 'fifo-probe' }) +} + /** Cancel a pending watch without claiming that any bytes parsed. */ export function cancelTerminalWriteStallWatch(terminal: object): void { const watch = stallWatchByTerminal.get(terminal) @@ -168,6 +208,9 @@ export function cancelTerminalWriteStallWatch(terminal: object): void { /** Write completed normally — the pipeline is healthy; drop any pending watch. */ export function settleTerminalWriteStallWatch(terminal: object): void { recordTerminalParseProgress(terminal) + if (stallWatchByTerminal.get(terminal)?.mode === 'fifo-probe') { + return + } cancelTerminalWriteStallWatch(terminal) }