From 7ff5d481b3ce7c4f75ca731bc8c7d71ee1d208e3 Mon Sep 17 00:00:00 2001 From: Phil Date: Sat, 5 Dec 2026 01:55:20 +0100 Subject: [PATCH 1/6] fix(terminal): recycle dead shell-integration terminals before reuse (issue 704) --- .../tla/TerminalReuse.NoRecycleSweep.cfg | 8 + .../tla/TerminalReuse.NoStallSweep.cfg | 8 + docs/architecture/tla/TerminalReuse.cfg | 3 + docs/architecture/tla/TerminalReuse.tla | 166 ++++++++++++++++++ docs/architecture/tla/TerminalReuseMC.tla | 12 ++ src/integrations/terminal/BaseTerminal.ts | 9 + src/integrations/terminal/Terminal.ts | 33 ++++ src/integrations/terminal/TerminalRegistry.ts | 35 ++++ .../__tests__/TerminalRegistry.spec.ts | 151 ++++++++++++++++ src/integrations/terminal/types.ts | 6 + 10 files changed, 431 insertions(+) create mode 100644 docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg create mode 100644 docs/architecture/tla/TerminalReuse.NoStallSweep.cfg create mode 100644 docs/architecture/tla/TerminalReuse.cfg create mode 100644 docs/architecture/tla/TerminalReuse.tla create mode 100644 docs/architecture/tla/TerminalReuseMC.tla diff --git a/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg new file mode 100644 index 00000000000..ca859ec8f95 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg @@ -0,0 +1,8 @@ +\* Sabotage check. The recycle sweep is removed from the selection path. +\* NoDeadSelection must fail: a terminal whose death VS Code reported is +\* selected for a command. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- NoSweep +INVARIANTS TypeOK NoDeadSelection diff --git a/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg new file mode 100644 index 00000000000..043e697f7b5 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg @@ -0,0 +1,8 @@ +\* Sabotage check. The sweep keeps only the death VS Code reports; a +\* terminal marked stalled (observed failure, no report) is no longer +\* recycled. NoDeadSelection must fail: the stalled terminal is selected. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepReportedOnly +INVARIANTS TypeOK NoDeadSelection diff --git a/docs/architecture/tla/TerminalReuse.cfg b/docs/architecture/tla/TerminalReuse.cfg new file mode 100644 index 00000000000..ebea2cc2861 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK NoDeadSelection NoDeadIdleAtSelection diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla new file mode 100644 index 00000000000..58a5d6f19d0 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.tla @@ -0,0 +1,166 @@ +---- MODULE TerminalReuse ---- +(* Models TerminalRegistry.getOrCreateTerminal in + src/integrations/terminal/TerminalRegistry.ts. + Source: ShellDies and FailIntegration. ShellDies is a death VS Code + reports (Terminal.shellIntegration drops). FailIntegration is a death the + environment does not report; the terminal only stalls (the long-session + zombie of issue #704). MarkDead records that observed failure. + Sink: RunReused, the selection of an existing terminal for a command. + Failure: execute_command keeps reusing a dead shell-integration terminal + after long sessions, so commands fail with Shell Integration Error until + a manual restart. + Invariants: + NoDeadSelection - no command is placed on a terminal whose integration + was confirmed before and is gone or stalled now. + NoDeadIdleAtSelection - while the last selection's sweep is current, no + dead idle terminal lingers in the registry; the sweep recycles it and the + freed slot takes the replacement spawn. A death after the selection + clears the currency flag; the next selection restores it. + Expected before the run: the base cfg passes. The NoRecycleSweep variant + fails NoDeadSelection (a reported-death terminal is reused). The + NoStallSweep variant fails NoDeadSelection (a marked-stall terminal is + reused); the marking itself stays intact. + Run each cfg on TerminalReuseMC.tla. The MC module holds both sabotage + operators. + Result: the base cfg passes in 121 distinct states (under 5 s). The + NoRecycleSweep variant fails NoDeadSelection in 24 states. The + NoStallSweep variant fails NoDeadSelection in 24 states. + Review ratchet: 0 covered, 0 added, 0 gap (first version). *) + +EXTENDS Naturals, FiniteSets + +Ids == {1, 2} \* two slots cover reuse plus one replacement + +NullId == 0 \* no terminal is selected for a command + +VARIABLES + registry, \* set of entries, one per live VS Code terminal + selected, \* id of the terminal a command runs on, NullId when idle + sweepClean \* TRUE while no death has happened after the last selection's sweep + +\* integ is the VS Code shell-integration report. seen records that +\* integration was confirmed at least once. stalled marks a terminal whose +\* command failed the integration wait (death the report does not show). +\* busy and closed mirror RooTerminal.busy and Terminal.isClosed(). +Entry(id) == [id |-> id, integ |-> "off", seen |-> FALSE, busy |-> FALSE, closed |-> FALSE, stalled |-> FALSE] + +IsDead(e) == e.seen /\ (e.integ = "off" \/ e.stalled) \* confirmed once, dead now + +Reuseable(e) == ~e.busy /\ ~e.closed \* the selection gate; the sweep owns death + +\* The sweep recycles dead idle terminals before a selection. +Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy} + +\* The marking records an observed integration failure (no_shell_integration +\* on a terminal that passed the wait before). +MarkDead(e) == [e EXCEPT !.stalled = TRUE] + +Init == + /\ registry = {} + /\ selected = NullId + /\ sweepClean = TRUE + +\* No candidate survives the sweep, so getOrCreateTerminal spawns a fresh +\* terminal and the command claims it (Terminal.runCommand sets busy). +RunNew == + \E id \in Ids : + /\ selected = NullId + /\ ~\E e \in Sweep(registry) : e.id = id + /\ registry' = Sweep(registry) \cup {[Entry(id) EXCEPT !.busy = TRUE]} + /\ selected' = id + /\ sweepClean' = TRUE + +\* getOrCreateTerminal reuses an idle terminal for the command. +RunReused == + \E e \in Sweep(registry) : + /\ selected = NullId + /\ Reuseable(e) + /\ registry' = {f \in Sweep(registry) : f.id /= e.id} \cup {[e EXCEPT !.busy = TRUE]} + /\ selected' = e.id + /\ sweepClean' = TRUE + +\* shellExecutionComplete releases the terminal after the command. +CompleteCommand == + /\ selected /= NullId + /\ \E e \in registry : + /\ e.id = selected + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.busy = FALSE]} + /\ selected' = NullId + /\ sweepClean' = sweepClean + +\* Shell integration activates on the first prompt (waitForShellIntegration +\* resolves): the report turns on and the terminal counts as proven. +Activate == + \E e \in registry : + /\ ~e.seen + /\ ~e.stalled + /\ e.integ = "off" + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "on", !.seen = TRUE]} + /\ UNCHANGED selected + /\ UNCHANGED sweepClean + +\* A long idle session kills the shell behind the terminal, and VS Code +\* reports it. The terminal object stays, so closed keeps FALSE. +ShellDies == + \E e \in registry : + /\ ~e.busy + /\ e.seen + /\ ~e.stalled + /\ e.integ = "on" + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "off"]} + /\ UNCHANGED selected + /\ sweepClean' = FALSE + +\* A command on a proven-alive terminal fails the integration wait +\* (no_shell_integration): the shell died mid-session and only the failed +\* command reveals it. The command ends at once; MarkDead records the +\* observed failure and the terminal is released for the next selection. +FailIntegration == + \E e \in registry : + /\ e.busy + /\ e.seen + /\ ~e.stalled + /\ e.integ = "on" + /\ selected = e.id + /\ registry' = {f \in registry : f.id /= e.id} \cup {[MarkDead(e) EXCEPT !.busy = FALSE]} + /\ selected' = NullId + /\ sweepClean' = FALSE + +\* The user closes the terminal (onDidCloseTerminal sets exitStatus). +CloseTerminal == + \E e \in registry : + /\ ~e.busy + /\ ~e.closed + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.closed = TRUE]} + /\ UNCHANGED selected + /\ sweepClean' = FALSE + +Next == RunNew \/ RunReused \/ CompleteCommand \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ selected \in Ids \cup {NullId} + /\ sweepClean \in BOOLEAN + /\ \A e \in registry : + /\ e.id \in Ids + /\ e.integ \in {"on", "off"} + /\ e.seen \in BOOLEAN + /\ e.busy \in BOOLEAN + /\ e.closed \in BOOLEAN + /\ e.stalled \in BOOLEAN + /\ Cardinality({f \in registry : f.id = e.id}) = 1 + /\ (selected /= NullId) => (\E e \in registry : e.id = selected /\ e.busy) + +\* Safety Rule 1: a command never runs on a dead terminal. +NoDeadSelection == + \/ selected = NullId + \/ ~IsDead(CHOOSE e \in registry : e.id = selected) + +\* Safety Rule 2: while the last selection's sweep is current, no dead idle +\* terminal lingers in the registry, so the replacement spawn cannot pile +\* dead terminals up. A death after that selection clears the flag. +NoDeadIdleAtSelection == + \/ ~sweepClean + \/ ~\E e \in registry : IsDead(e) /\ ~e.busy +==== diff --git a/docs/architecture/tla/TerminalReuseMC.tla b/docs/architecture/tla/TerminalReuseMC.tla new file mode 100644 index 00000000000..5bd35f7b86c --- /dev/null +++ b/docs/architecture/tla/TerminalReuseMC.tla @@ -0,0 +1,12 @@ +---- MODULE TerminalReuseMC ---- +\* Model-checking settings for TerminalReuse. +EXTENDS TerminalReuse + +\* Sabotage: the recycle sweep is removed from the selection path. +NoSweep(nm) == nm + +\* Sabotage: the sweep keeps only the death VS Code reports. A terminal +\* marked stalled (observed failure, no report) is no longer recycled. +SweepReportedOnly(nm) == {e \in nm : ~(e.seen /\ e.integ = "off") \/ e.busy} + +==== diff --git a/src/integrations/terminal/BaseTerminal.ts b/src/integrations/terminal/BaseTerminal.ts index 45e6c022907..c91897b1306 100644 --- a/src/integrations/terminal/BaseTerminal.ts +++ b/src/integrations/terminal/BaseTerminal.ts @@ -39,6 +39,15 @@ export abstract class BaseTerminal implements RooTerminal { abstract isClosed(): boolean + /** + * True when this terminal can no longer run shell-integrated commands. + * Execa terminals run each command in a fresh process, so there is + * nothing to lose; the VS Code terminal overrides this. + */ + public hasLostShellIntegration(): boolean { + return false + } + abstract runCommand(command: string, callbacks: RooTerminalCallbacks): RooTerminalProcessResultPromise /** diff --git a/src/integrations/terminal/Terminal.ts b/src/integrations/terminal/Terminal.ts index 21f98b86c6f..9a02a24d175 100644 --- a/src/integrations/terminal/Terminal.ts +++ b/src/integrations/terminal/Terminal.ts @@ -16,6 +16,12 @@ export class Terminal extends BaseTerminal { public activeShellExecution?: vscode.TerminalShellExecution + // Shell-integration liveness tracking (#704): seen records that the + // integration wait passed at least once; lost records an observed + // no_shell_integration failure on a terminal that had passed it before. + private shellIntegrationSeen: boolean = false + private shellIntegrationLost: boolean = false + constructor(id: number, terminal: vscode.Terminal | undefined, cwd: string) { super("vscode", id, cwd, Terminal.getReuseKey()) @@ -59,6 +65,12 @@ export class Terminal extends BaseTerminal { if (Terminal.getTerminalZdotdir() && !Terminal.getTerminalProfile()) { ShellIntegrationManager.terminalTmpDirs.set(id, env.ZDOTDIR) } + + // An adopted terminal may already have integration active, which counts + // as a confirmed start (#704). + if (terminal?.shellIntegration) { + this.shellIntegrationSeen = true + } } /** @@ -77,6 +89,17 @@ export class Terminal extends BaseTerminal { return this.terminal.exitStatus !== undefined } + /** + * True when this terminal can no longer run shell-integrated commands: + * the integration wait passed before, but VS Code no longer reports the + * integration (the shell behind the terminal died), or a command already + * observed the loss. exitStatus stays undefined for such terminals, so + * isClosed() cannot catch them (#704). + */ + public override hasLostShellIntegration(): boolean { + return this.shellIntegrationLost || (this.shellIntegrationSeen && !this.terminal.shellIntegration) + } + public override runCommand(command: string, callbacks: RooTerminalCallbacks): RooTerminalProcessResultPromise { // We set busy before the command is running because the terminal may be // waiting on terminal integration, and we must prevent another instance @@ -126,6 +149,9 @@ export class Terminal extends BaseTerminal { // Clean up temporary directory if shell integration is available, zsh did its job: ShellIntegrationManager.zshCleanupTmpDir(this.id) + // The wait passed: this terminal is proven integrated (#704). + this.shellIntegrationSeen = true + // Run the command in the terminal void process.run(command).catch((error) => process.emit("error", error)) }) @@ -135,6 +161,13 @@ export class Terminal extends BaseTerminal { // Clean up temporary directory if shell integration is not available ShellIntegrationManager.zshCleanupTmpDir(this.id) + // A terminal that passed the wait before and now fails it is + // dead: the shell behind it died mid-session (#704). Record the + // loss so the next selection recycles it instead of reusing it. + if (this.shellIntegrationSeen) { + this.shellIntegrationLost = true + } + process.emit("no_shell_integration", { message: `Shell integration initialization sequence '\\x1b]633;A' was not received within ${Terminal.getShellIntegrationTimeout() / 1000}s. Shell integration has been disabled for this terminal instance. Increase the timeout in the settings if necessary.`, commandSubmitted: false, diff --git a/src/integrations/terminal/TerminalRegistry.ts b/src/integrations/terminal/TerminalRegistry.ts index da4b3dd16d0..2a9742dd0f4 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -220,6 +220,17 @@ export class TerminalRegistry { taskId?: string, provider: RooTerminalProvider = "vscode", ): Promise { + // Re-validate idle terminals before reuse (#704): a VS Code terminal + // whose shell integration died keeps exitStatus undefined, so isClosed() + // never filters it and every command would replay the shell-integration + // timeout on it. Recycle it so the selection below spawns a replacement. + // The for-of walks a snapshot; recycleTerminal reassigns this.terminals. + for (const terminal of this.terminals) { + if (!terminal.busy && terminal.hasLostShellIntegration()) { + this.recycleTerminal(terminal.id) + } + } + const terminals = this.getAllTerminals() const reuseKey = provider === "vscode" ? Terminal.getReuseKey() : provider let terminal: RooTerminal | undefined @@ -359,6 +370,30 @@ export class TerminalRegistry { }) } + /** + * Removes a terminal from the registry and closes its VS Code terminal + * ("recycle"), so the next getOrCreateTerminal() spawns a replacement + * (#704). Busy terminals are never recycled: a recycle targets terminals + * that failed shell-integration revalidation while idle. + */ + public static recycleTerminal(id: number): void { + const terminal = this.terminals.find((t) => t.id === id) + + if (!terminal || terminal.busy) { + return + } + + if (terminal instanceof Terminal && !terminal.isClosed()) { + try { + terminal.terminal.dispose() + } catch (error) { + console.error(`[TerminalRegistry] Error disposing terminal ${id} on recycle:`, error) + } + } + + this.removeTerminal(id) + } + /** * Releases all terminals associated with a task. * diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index 3a29bc4c6eb..3da59af6407 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -9,6 +9,7 @@ import { ShellIntegrationManager } from "../ShellIntegrationManager" import { Terminal } from "../Terminal" import { TerminalProcess } from "../TerminalProcess" import { TerminalRegistry } from "../TerminalRegistry" +import type { RooTerminalCallbacks } from "../types" const PAGER = process.platform === "win32" ? "" : "cat" @@ -480,4 +481,154 @@ describe("TerminalRegistry", () => { expect(terminal.taskId).toBeUndefined() }) }) + + describe("dead shell-integration terminals (#704)", () => { + // Builds a vscode.Terminal double whose integration report the test can + // drop to simulate a long-session shell death (exitStatus stays + // undefined: VS Code never fired the close event). + const makeVsceTerminal = () => ({ + exitStatus: undefined, + name: "Zoo Code", + processId: Promise.resolve(123), + creationOptions: {}, + state: { isInteractedWith: true, shell: { id: "test-shell", executable: "/bin/bash", args: [] } }, + dispose: vi.fn(), + hide: vi.fn(), + show: vi.fn(), + sendText: vi.fn(), + shellIntegration: undefined as vscode.TerminalShellIntegration | undefined, + }) + + // Drops the integration report on a Terminal's underlying double. The + // double assertion is the sanctioned test-double shape; the shell + // integration field is what the fix observes (readonly on the real API). + const setIntegrationReport = (terminal: Terminal, value: vscode.TerminalShellIntegration | undefined) => { + ;( + terminal.terminal as unknown as { shellIntegration: vscode.TerminalShellIntegration | undefined } + ).shellIntegration = value + } + const dropIntegrationReport = (terminal: Terminal) => setIntegrationReport(terminal, undefined) + + it("recycles a terminal whose confirmed integration is gone and spawns a replacement", async () => { + const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal + + // Long-session death: the integration wait passed before (seen), VS + // Code no longer reports it, exitStatus is still undefined. + first["shellIntegrationSeen"] = true + dropIntegrationReport(first) + + const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(second).not.toBe(first) + expect(first.terminal.dispose).toHaveBeenCalledTimes(1) + expect(mockCreateTerminal).toHaveBeenCalledTimes(2) + }) + + it("keeps a terminal that never confirmed integration (cold start) across selections", async () => { + // A cold terminal (integration not active yet) must not be recycled, + // or every command against a slow-starting shell spawns a new terminal. + const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal + dropIntegrationReport(first) + + const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(second).toBe(first) + expect(first.terminal.dispose).not.toHaveBeenCalled() + }) + + it("does not recycle a busy terminal even when its integration is gone", async () => { + const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal + first["shellIntegrationSeen"] = true + dropIntegrationReport(first) + first.busy = true + + const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + // Busy wins: the in-flight command must not lose its terminal, but the + // command itself needs a fresh one. + expect(first.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(first) + expect(second).not.toBe(first) + }) + + it("reports lost integration only after a confirmed start", () => { + const vsce = makeVsceTerminal() + const terminal = new Terminal(90, vsce as unknown as vscode.Terminal, "/test/path") + + // Cold: no confirmed start and no report - reusable. + expect(terminal.hasLostShellIntegration()).toBe(false) + + // Confirmed start with the report present - reusable. + terminal["shellIntegrationSeen"] = true + setIntegrationReport(terminal, { executeCommand: vi.fn() } as unknown as vscode.TerminalShellIntegration) + expect(terminal.hasLostShellIntegration()).toBe(false) + + // Confirmed start, report gone - the #704 zombie. + setIntegrationReport(terminal, undefined) + expect(terminal.hasLostShellIntegration()).toBe(true) + + // An observed failure marks the terminal dead on its own. + const marked = new Terminal(92, makeVsceTerminal() as unknown as vscode.Terminal, "/test/path") + marked["shellIntegrationLost"] = true + expect(marked.hasLostShellIntegration()).toBe(true) + }) + + it("never flags an Execa terminal as integration-lost", () => { + const execa = TerminalRegistry.createTerminal("/test/path", "execa") as ExecaTerminal + expect(execa.hasLostShellIntegration()).toBe(false) + }) + + it("marks a proven terminal dead when its integration wait times out", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() // no integration, never activates + const terminal = new Terminal(91, vsce as unknown as vscode.Terminal, "/test/path") + // The terminal passed the wait before (long session). + terminal["shellIntegrationSeen"] = true + + const callbacks = { + onLine: vi.fn(), + onCompleted: vi.fn(), + onShellExecutionStarted: vi.fn(), + onShellExecutionComplete: vi.fn(), + } satisfies RooTerminalCallbacks + + const run = terminal.runCommand("echo hi", callbacks) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + + expect(terminal["shellIntegrationLost"]).toBe(true) + expect(terminal.hasLostShellIntegration()).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it("does not mark a cold terminal dead when its first integration wait times out", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() // no integration, never activates + const terminal = new Terminal(93, vsce as unknown as vscode.Terminal, "/test/path") + // No confirmed start yet: a slow-starting shell must stay reusable. + + const callbacks = { + onLine: vi.fn(), + onCompleted: vi.fn(), + onShellExecutionStarted: vi.fn(), + onShellExecutionComplete: vi.fn(), + } satisfies RooTerminalCallbacks + + const run = terminal.runCommand("echo hi", callbacks) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + + expect(terminal["shellIntegrationLost"]).toBe(false) + expect(terminal.hasLostShellIntegration()).toBe(false) + } finally { + vi.useRealTimers() + } + }) + }) }) diff --git a/src/integrations/terminal/types.ts b/src/integrations/terminal/types.ts index 8224875b607..28ab2f54a76 100644 --- a/src/integrations/terminal/types.ts +++ b/src/integrations/terminal/types.ts @@ -12,6 +12,12 @@ export interface RooTerminal { process?: RooTerminalProcess getCurrentWorkingDirectory(): string isClosed: () => boolean + /** + * True when this terminal can no longer run shell-integrated commands: + * the integration was confirmed before but is gone or marked dead now. + * Used by TerminalRegistry to recycle the terminal instead of reusing it. + */ + hasLostShellIntegration: () => boolean runCommand: (command: string, callbacks: RooTerminalCallbacks) => RooTerminalProcessResultPromise setActiveStream(stream: AsyncIterable | undefined, pid?: number): void shellExecutionComplete(exitDetails: ExitCodeDetails): void From cfc9266e0432203b523abaefdec64a5d8ce3d859 Mon Sep 17 00:00:00 2001 From: Phil Date: Sat, 5 Dec 2026 06:07:46 +0100 Subject: [PATCH 2/6] fix(terminal): record stream-start failures and keep unread output on recycle (CR round 1) CodeRabbit round 1 on #2862 (issue #704). Terminal.runCommand records shellIntegrationLost in its no_shell_integration handler when the terminal was confirmed before the call (an earlier wait passed, or the constructor adopted a report) and the shell is not cmd.exe. The handler now covers the stream-start failures TerminalProcess.run reports (no stream within the timeout, or the report gone between the wait and run), which left the failed terminal reusable. The wait-timeout marking moved into the same handler. Cold terminals and the cmd.exe shortcut are never marked. The submitted command is not replayed. TerminalRegistry.recycleTerminal keeps a terminal that holds output no consumer read yet (the getBackgroundTerminals predicate); the sweep recycles it after getEnvironmentDetails read it. Both selection gates refuse a terminal that lost shell integration, so a deferred dead terminal is never reused. Tests: pending-call checks before the deadline in both fake-timer tests; runCommand success path, adopted-terminal constructor, dispose-throws, stream-start failure and unread-output deferral (both red on the previous head), cold stream start. TerminalReuse.tla: overlapping selections, ShellDies during a command, selection gate, BusyTerminalKept, UnreadOutputKept, ReadOutput; cfgs NoDeadGate, NoBusyGuard, NoUnreadGuard added, NoRecycleSweep and NoStallSweep re-pointed to NoDeadIdleAtSelection. Base cfg passes in 225 states; each sabotage cfg fails its named property. --- .../tla/TerminalReuse.NoBusyGuard.cfg | 8 + .../tla/TerminalReuse.NoDeadGate.cfg | 9 + .../tla/TerminalReuse.NoRecycleSweep.cfg | 8 +- .../tla/TerminalReuse.NoStallSweep.cfg | 6 +- .../tla/TerminalReuse.NoUnreadGuard.cfg | 8 + docs/architecture/tla/TerminalReuse.cfg | 3 +- docs/architecture/tla/TerminalReuse.tla | 200 ++++++++++-------- docs/architecture/tla/TerminalReuseMC.tla | 11 +- src/integrations/terminal/Terminal.ts | 29 ++- src/integrations/terminal/TerminalRegistry.ts | 31 ++- .../__tests__/TerminalRegistry.spec.ts | 189 ++++++++++++++++- 11 files changed, 391 insertions(+), 111 deletions(-) create mode 100644 docs/architecture/tla/TerminalReuse.NoBusyGuard.cfg create mode 100644 docs/architecture/tla/TerminalReuse.NoDeadGate.cfg create mode 100644 docs/architecture/tla/TerminalReuse.NoUnreadGuard.cfg diff --git a/docs/architecture/tla/TerminalReuse.NoBusyGuard.cfg b/docs/architecture/tla/TerminalReuse.NoBusyGuard.cfg new file mode 100644 index 00000000000..b6994f18b6e --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoBusyGuard.cfg @@ -0,0 +1,8 @@ +\* Sabotage check. The sweep drops busy terminals with it. BusyTerminalKept +\* must fail: a command that is running on a dead terminal loses it. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepDropsBusy +INVARIANTS TypeOK +PROPERTY BusyTerminalKept diff --git a/docs/architecture/tla/TerminalReuse.NoDeadGate.cfg b/docs/architecture/tla/TerminalReuse.NoDeadGate.cfg new file mode 100644 index 00000000000..c39a87b6c3f --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoDeadGate.cfg @@ -0,0 +1,9 @@ +\* Sabotage check. The selection gate no longer refuses a dead terminal. +\* NoDeadSelection must fail: a dead idle terminal the sweep kept for its +\* unread output is selected for a command. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Reuseable <- ReuseableNoDeath +INVARIANTS TypeOK +PROPERTY NoDeadSelection diff --git a/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg index ca859ec8f95..8daf718c563 100644 --- a/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg +++ b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg @@ -1,8 +1,10 @@ \* Sabotage check. The recycle sweep is removed from the selection path. -\* NoDeadSelection must fail: a terminal whose death VS Code reported is -\* selected for a command. +\* NoDeadIdleAtSelection must fail: a dead idle terminal stays in the +\* registry after a selection. The gate still refuses it, so +\* NoDeadSelection holds. SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS Sweep <- NoSweep -INVARIANTS TypeOK NoDeadSelection +INVARIANTS TypeOK +PROPERTY NoDeadIdleAtSelection diff --git a/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg index 043e697f7b5..4e8bcef710f 100644 --- a/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg +++ b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg @@ -1,8 +1,10 @@ \* Sabotage check. The sweep keeps only the death VS Code reports; a \* terminal marked stalled (observed failure, no report) is no longer -\* recycled. NoDeadSelection must fail: the stalled terminal is selected. +\* recycled. NoDeadIdleAtSelection must fail: the stalled idle terminal +\* stays in the registry after a selection. SPECIFICATION Spec CHECK_DEADLOCK FALSE CONSTANTS Sweep <- SweepReportedOnly -INVARIANTS TypeOK NoDeadSelection +INVARIANTS TypeOK +PROPERTY NoDeadIdleAtSelection diff --git a/docs/architecture/tla/TerminalReuse.NoUnreadGuard.cfg b/docs/architecture/tla/TerminalReuse.NoUnreadGuard.cfg new file mode 100644 index 00000000000..9eb4e45ec23 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoUnreadGuard.cfg @@ -0,0 +1,8 @@ +\* Sabotage check. The sweep ignores unread output. UnreadOutputKept must +\* fail: a dead idle terminal that holds output no consumer read is removed. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepIgnoresUnread +INVARIANTS TypeOK +PROPERTY UnreadOutputKept diff --git a/docs/architecture/tla/TerminalReuse.cfg b/docs/architecture/tla/TerminalReuse.cfg index ebea2cc2861..5b4f504185c 100644 --- a/docs/architecture/tla/TerminalReuse.cfg +++ b/docs/architecture/tla/TerminalReuse.cfg @@ -1,3 +1,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE -INVARIANTS TypeOK NoDeadSelection NoDeadIdleAtSelection +INVARIANTS TypeOK +PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla index 58a5d6f19d0..f80a3846c1d 100644 --- a/docs/architecture/tla/TerminalReuse.tla +++ b/docs/architecture/tla/TerminalReuse.tla @@ -2,165 +2,179 @@ (* Models TerminalRegistry.getOrCreateTerminal in src/integrations/terminal/TerminalRegistry.ts. Source: ShellDies and FailIntegration. ShellDies is a death VS Code - reports (Terminal.shellIntegration drops). FailIntegration is a death the - environment does not report; the terminal only stalls (the long-session - zombie of issue #704). MarkDead records that observed failure. - Sink: RunReused, the selection of an existing terminal for a command. + reports (Terminal.shellIntegration drops), during a command or while + idle. FailIntegration is a death the environment does not report; only + the command fails (no_shell_integration: the integration wait or the + stream start times out). MarkDead records that observed failure. + Sink: RunReused and RunNew select a terminal for a command; the Sweep + runs first. Selections overlap: a command can start while another one + runs on another terminal. Failure: execute_command keeps reusing a dead shell-integration terminal after long sessions, so commands fail with Shell Integration Error until a manual restart. - Invariants: - NoDeadSelection - no command is placed on a terminal whose integration - was confirmed before and is gone or stalled now. - NoDeadIdleAtSelection - while the last selection's sweep is current, no - dead idle terminal lingers in the registry; the sweep recycles it and the - freed slot takes the replacement spawn. A death after the selection - clears the currency flag; the next selection restores it. - Expected before the run: the base cfg passes. The NoRecycleSweep variant - fails NoDeadSelection (a reported-death terminal is reused). The - NoStallSweep variant fails NoDeadSelection (a marked-stall terminal is - reused); the marking itself stays intact. - Run each cfg on TerminalReuseMC.tla. The MC module holds both sabotage + Properties: + NoDeadSelection - a selection never places a command on a dead terminal + (the sweep recycles it, and the gate refuses what the sweep kept). + NoDeadIdleAtSelection - after a selection, no dead idle terminal without + unread output stays in the registry. + BusyTerminalKept - a selection never removes a busy terminal: the + command on it keeps its terminal. + UnreadOutputKept - a selection never removes a terminal that holds + output no consumer read yet; ReadOutput releases it for the next sweep. + Expected before the run: the base cfg passes. NoRecycleSweep and + NoStallSweep fail NoDeadIdleAtSelection. NoDeadGate fails + NoDeadSelection. NoBusyGuard fails BusyTerminalKept. NoUnreadGuard + fails UnreadOutputKept. + Run each cfg on TerminalReuseMC.tla. The MC module holds the sabotage operators. - Result: the base cfg passes in 121 distinct states (under 5 s). The - NoRecycleSweep variant fails NoDeadSelection in 24 states. The - NoStallSweep variant fails NoDeadSelection in 24 states. - Review ratchet: 0 covered, 0 added, 0 gap (first version). *) + Result: the base cfg passes in 225 distinct states (under 10 s). + NoRecycleSweep fails NoDeadIdleAtSelection in 48 states. + NoStallSweep fails NoDeadIdleAtSelection in 48 states. + NoDeadGate fails NoDeadSelection in 89 states. + NoBusyGuard fails BusyTerminalKept in 48 states. + NoUnreadGuard fails UnreadOutputKept in 89 states. + Review ratchet (PR #2862, CodeRabbit round 1): 2 covered, 2 added, 3 gap. + Added: overlapping commands, ShellDies during a command, the selection + gate, BusyTerminalKept, NoDeadSelection as a selection-time property + (discussion_r4808051264). Added: the unread field, ReadOutput, + UnreadOutputKept, cfg NoUnreadGuard (discussion_r4808051294). + Covered: a stream-start failure on a confirmed terminal is FailIntegration + (discussion_r4808051286). Covered: the sweep removes the entry whatever + VS Code's dispose does; dispose is an oracle (Regression Evidence 3). + Gap: the pending-call test rule (discussion_r4808051276) and the + runCommand success-path and constructor evidence tests (Regression + Evidence 1, 2) are test-evidence demands, not behavior. *) EXTENDS Naturals, FiniteSets -Ids == {1, 2} \* two slots cover reuse plus one replacement +Ids == {1, 2} \* two slots: one busy terminal plus one replacement -NullId == 0 \* no terminal is selected for a command +VARIABLE registry \* set of entries, one per registered VS Code terminal -VARIABLES - registry, \* set of entries, one per live VS Code terminal - selected, \* id of the terminal a command runs on, NullId when idle - sweepClean \* TRUE while no death has happened after the last selection's sweep - -\* integ is the VS Code shell-integration report. seen records that -\* integration was confirmed at least once. stalled marks a terminal whose -\* command failed the integration wait (death the report does not show). -\* busy and closed mirror RooTerminal.busy and Terminal.isClosed(). -Entry(id) == [id |-> id, integ |-> "off", seen |-> FALSE, busy |-> FALSE, closed |-> FALSE, stalled |-> FALSE] +(* integ is the VS Code shell-integration report. seen records that the + integration was confirmed at least once. stalled marks a terminal whose + command observed a failure the report does not show. unread marks output + of a completed command that no consumer read yet. busy mirrors + RooTerminal.busy. A closed terminal leaves the registry + (onDidCloseTerminal removes it). *) +Entry(id) == [id |-> id, integ |-> "off", seen |-> FALSE, busy |-> FALSE, stalled |-> FALSE, unread |-> FALSE] IsDead(e) == e.seen /\ (e.integ = "off" \/ e.stalled) \* confirmed once, dead now -Reuseable(e) == ~e.busy /\ ~e.closed \* the selection gate; the sweep owns death +(* The selection gate (the find calls in getOrCreateTerminal). A dead + terminal the sweep kept (busy, or unread output) is not selected. *) +Reuseable(e) == ~e.busy /\ ~IsDead(e) -\* The sweep recycles dead idle terminals before a selection. -Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy} +(* The sweep before a selection: recycle dead idle terminals without unread + output. Keep busy terminals and terminals that hold unread output. *) +Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread} -\* The marking records an observed integration failure (no_shell_integration -\* on a terminal that passed the wait before). +(* The marking records an observed integration failure (no_shell_integration + on a terminal that was confirmed before the command). *) MarkDead(e) == [e EXCEPT !.stalled = TRUE] -Init == - /\ registry = {} - /\ selected = NullId - /\ sweepClean = TRUE +Init == registry = {} -\* No candidate survives the sweep, so getOrCreateTerminal spawns a fresh -\* terminal and the command claims it (Terminal.runCommand sets busy). +(* getOrCreateTerminal spawns a fresh terminal and the command claims it + (Terminal.runCommand sets busy). *) RunNew == \E id \in Ids : - /\ selected = NullId /\ ~\E e \in Sweep(registry) : e.id = id /\ registry' = Sweep(registry) \cup {[Entry(id) EXCEPT !.busy = TRUE]} - /\ selected' = id - /\ sweepClean' = TRUE -\* getOrCreateTerminal reuses an idle terminal for the command. +(* getOrCreateTerminal reuses an idle terminal for the command. *) RunReused == \E e \in Sweep(registry) : - /\ selected = NullId /\ Reuseable(e) /\ registry' = {f \in Sweep(registry) : f.id /= e.id} \cup {[e EXCEPT !.busy = TRUE]} - /\ selected' = e.id - /\ sweepClean' = TRUE -\* shellExecutionComplete releases the terminal after the command. +(* shellExecutionComplete releases the terminal after the command. The + completed command can leave output that no consumer read yet. *) CompleteCommand == - /\ selected /= NullId - /\ \E e \in registry : - /\ e.id = selected - /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.busy = FALSE]} - /\ selected' = NullId - /\ sweepClean' = sweepClean - -\* Shell integration activates on the first prompt (waitForShellIntegration -\* resolves): the report turns on and the terminal counts as proven. + \E e \in registry : + /\ e.busy + /\ \E u \in BOOLEAN : + registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.busy = FALSE, !.unread = e.unread \/ u]} + +(* A consumer (getEnvironmentDetails) reads the unread output. *) +ReadOutput == + \E e \in registry : + /\ e.unread + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.unread = FALSE]} + +(* Shell integration activates (waitForShellIntegration resolves, or an + adopted terminal reports it): the report turns on and the terminal + counts as proven. *) Activate == \E e \in registry : /\ ~e.seen /\ ~e.stalled /\ e.integ = "off" /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "on", !.seen = TRUE]} - /\ UNCHANGED selected - /\ UNCHANGED sweepClean -\* A long idle session kills the shell behind the terminal, and VS Code -\* reports it. The terminal object stays, so closed keeps FALSE. +(* A long session kills the shell behind the terminal, and VS Code reports + it, during a command or while idle. The terminal object stays. *) ShellDies == \E e \in registry : - /\ ~e.busy /\ e.seen /\ ~e.stalled /\ e.integ = "on" /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "off"]} - /\ UNCHANGED selected - /\ sweepClean' = FALSE -\* A command on a proven-alive terminal fails the integration wait -\* (no_shell_integration): the shell died mid-session and only the failed -\* command reveals it. The command ends at once; MarkDead records the -\* observed failure and the terminal is released for the next selection. +(* A command on a terminal confirmed before it fails (no_shell_integration): + the shell died mid-session and only the failed command reveals it. The + command ends at once; MarkDead records the observed failure and the + terminal is released for the next selection. *) FailIntegration == \E e \in registry : /\ e.busy /\ e.seen /\ ~e.stalled /\ e.integ = "on" - /\ selected = e.id /\ registry' = {f \in registry : f.id /= e.id} \cup {[MarkDead(e) EXCEPT !.busy = FALSE]} - /\ selected' = NullId - /\ sweepClean' = FALSE -\* The user closes the terminal (onDidCloseTerminal sets exitStatus). +(* The user closes an idle terminal (onDidCloseTerminal removes it). *) CloseTerminal == \E e \in registry : /\ ~e.busy - /\ ~e.closed - /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.closed = TRUE]} - /\ UNCHANGED selected - /\ sweepClean' = FALSE + /\ registry' = {f \in registry : f.id /= e.id} -Next == RunNew \/ RunReused \/ CompleteCommand \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal +Next == RunNew \/ RunReused \/ CompleteCommand \/ ReadOutput \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal -Spec == Init /\ [][Next]_<> +Spec == Init /\ [][Next]_registry TypeOK == - /\ selected \in Ids \cup {NullId} - /\ sweepClean \in BOOLEAN /\ \A e \in registry : /\ e.id \in Ids /\ e.integ \in {"on", "off"} /\ e.seen \in BOOLEAN /\ e.busy \in BOOLEAN - /\ e.closed \in BOOLEAN /\ e.stalled \in BOOLEAN + /\ e.unread \in BOOLEAN + /\ (e.integ = "on") => e.seen + /\ e.stalled => e.seen /\ Cardinality({f \in registry : f.id = e.id}) = 1 - /\ (selected /= NullId) => (\E e \in registry : e.id = selected /\ e.busy) -\* Safety Rule 1: a command never runs on a dead terminal. +Selection == RunNew \/ RunReused + +(* Selection-time safety: a command is never placed on a dead terminal. The + terminal keeps its state; only busy changes (a fresh spawn has another + state, so it is not this terminal). *) NoDeadSelection == - \/ selected = NullId - \/ ~IsDead(CHOOSE e \in registry : e.id = selected) + [][ Selection => \A e \in registry : (~e.busy /\ [e EXCEPT !.busy = TRUE] \in registry') => ~IsDead(e) ]_registry -\* Safety Rule 2: while the last selection's sweep is current, no dead idle -\* terminal lingers in the registry, so the replacement spawn cannot pile -\* dead terminals up. A death after that selection clears the flag. +(* After a selection, no dead idle terminal without unread output stays in + the registry: the sweep recycled it, so dead terminals do not pile up. *) NoDeadIdleAtSelection == - \/ ~sweepClean - \/ ~\E e \in registry : IsDead(e) /\ ~e.busy + [][ Selection => ~\E e \in registry' : IsDead(e) /\ ~e.busy /\ ~e.unread ]_registry + +(* Continued execution: the sweep never removes a busy terminal. *) +BusyTerminalKept == + [][ Selection => \A e \in registry : e.busy => e \in registry' ]_registry + +(* The sweep never removes a terminal that holds unread output. A live + terminal with unread output can be selected; its output stays. *) +UnreadOutputKept == + [][ Selection => \A e \in registry : e.unread => \E f \in registry' : f.id = e.id /\ f.unread ]_registry + ==== diff --git a/docs/architecture/tla/TerminalReuseMC.tla b/docs/architecture/tla/TerminalReuseMC.tla index 5bd35f7b86c..a718511e59c 100644 --- a/docs/architecture/tla/TerminalReuseMC.tla +++ b/docs/architecture/tla/TerminalReuseMC.tla @@ -7,6 +7,15 @@ NoSweep(nm) == nm \* Sabotage: the sweep keeps only the death VS Code reports. A terminal \* marked stalled (observed failure, no report) is no longer recycled. -SweepReportedOnly(nm) == {e \in nm : ~(e.seen /\ e.integ = "off") \/ e.busy} +SweepReportedOnly(nm) == {e \in nm : ~(e.seen /\ e.integ = "off") \/ e.busy \/ e.unread} + +\* Sabotage: the sweep drops busy terminals with it (no busy guard). +SweepDropsBusy(nm) == {e \in nm : ~IsDead(e) \/ e.unread} + +\* Sabotage: the sweep ignores unread output (a deferred terminal is recycled). +SweepIgnoresUnread(nm) == {e \in nm : ~IsDead(e) \/ e.busy} + +\* Sabotage: the selection gate no longer refuses a dead terminal. +ReuseableNoDeath(e) == ~e.busy ==== diff --git a/src/integrations/terminal/Terminal.ts b/src/integrations/terminal/Terminal.ts index 9a02a24d175..d9aaf33fd9e 100644 --- a/src/integrations/terminal/Terminal.ts +++ b/src/integrations/terminal/Terminal.ts @@ -106,6 +106,15 @@ export class Terminal extends BaseTerminal { // from selecting the terminal for use during that time. this.busy = true + // TRUE only when an earlier command or an adopted report proved this + // terminal integrated before this call (#704). A terminal that passes + // the wait for the first time inside this call is still cold. + const confirmedBefore = this.shellIntegrationSeen + + // cmd.exe cannot report shell integration (VS Code issue #164646): a + // failure there is a platform property, not a death. + const integrationImpossible = Terminal.isActiveShellCmdExe() + const process = new TerminalProcess(this) process.command = command this.process = process @@ -117,7 +126,18 @@ export class Terminal extends BaseTerminal { process.once("completed", (output) => callbacks.onCompleted(output, process)) process.once("shell_execution_started", (pid) => callbacks.onShellExecutionStarted(pid, process)) process.once("shell_execution_complete", (details) => callbacks.onShellExecutionComplete(details, process)) - process.once("no_shell_integration", (details) => callbacks.onNoShellIntegration?.(details, process)) + process.once("no_shell_integration", (details) => { + // A proven terminal that fails the integration wait or the stream + // start is dead: the shell behind it died mid-session, and VS Code + // can keep the integration object (#704). Record the loss so the + // next selection recycles the terminal. The submitted command is + // not replayed. + if (confirmedBefore && !integrationImpossible) { + this.shellIntegrationLost = true + } + + callbacks.onNoShellIntegration?.(details, process) + }) const promise = new Promise((resolve, reject) => { // Set up event handlers @@ -127,7 +147,7 @@ export class Terminal extends BaseTerminal { reject(error) }) - if (Terminal.isActiveShellCmdExe()) { + if (integrationImpossible) { // Keep this defensive fallback for callers that invoke Terminal.runCommand() // directly instead of routing through executeCommandInTerminal(). // cmd.exe cannot emit OSC 633;A — skip the timeout entirely and go @@ -162,11 +182,8 @@ export class Terminal extends BaseTerminal { ShellIntegrationManager.zshCleanupTmpDir(this.id) // A terminal that passed the wait before and now fails it is - // dead: the shell behind it died mid-session (#704). Record the + // dead (#704): the no_shell_integration handler records the // loss so the next selection recycles it instead of reusing it. - if (this.shellIntegrationSeen) { - this.shellIntegrationLost = true - } process.emit("no_shell_integration", { message: `Shell integration initialization sequence '\\x1b]633;A' was not received within ${Terminal.getShellIntegrationTimeout() / 1000}s. Shell integration has been disabled for this terminal instance. Increase the timeout in the settings if necessary.`, diff --git a/src/integrations/terminal/TerminalRegistry.ts b/src/integrations/terminal/TerminalRegistry.ts index 2a9742dd0f4..bc84ed6229c 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -224,6 +224,9 @@ export class TerminalRegistry { // whose shell integration died keeps exitStatus undefined, so isClosed() // never filters it and every command would replay the shell-integration // timeout on it. Recycle it so the selection below spawns a replacement. + // A dead terminal that holds output no consumer read yet waits for its + // reader (getEnvironmentDetails): recycleTerminal keeps it, and the + // selection gates below skip it, so it is never reused. // The for-of walks a snapshot; recycleTerminal reassigns this.terminals. for (const terminal of this.terminals) { if (!terminal.busy && terminal.hasLostShellIntegration()) { @@ -239,7 +242,13 @@ export class TerminalRegistry { // matching directory. if (taskId) { terminal = terminals.find((t) => { - if (t.busy || t.taskId !== taskId || t.provider !== provider || t.reuseKey !== reuseKey) { + if ( + t.busy || + t.hasLostShellIntegration() || + t.taskId !== taskId || + t.provider !== provider || + t.reuseKey !== reuseKey + ) { return false } @@ -256,7 +265,7 @@ export class TerminalRegistry { // Second priority: Find any available terminal with matching directory. if (!terminal) { terminal = terminals.find((t) => { - if (t.busy || t.provider !== provider || t.reuseKey !== reuseKey) { + if (t.busy || t.hasLostShellIntegration() || t.provider !== provider || t.reuseKey !== reuseKey) { return false } @@ -370,11 +379,21 @@ export class TerminalRegistry { }) } + /** + * True when a terminal holds output that no consumer read yet: completed + * processes with unretrieved output, or an active process with some. This + * is the predicate getBackgroundTerminals uses to list terminals. + */ + private static hasUnreadOutput(terminal: RooTerminal): boolean { + return terminal.getProcessesWithOutput().length > 0 || Boolean(terminal.process?.hasUnretrievedOutput()) + } + /** * Removes a terminal from the registry and closes its VS Code terminal * ("recycle"), so the next getOrCreateTerminal() spawns a replacement * (#704). Busy terminals are never recycled: a recycle targets terminals - * that failed shell-integration revalidation while idle. + * that failed shell-integration revalidation while idle. Terminals that + * hold unread output wait for their reader (see getOrCreateTerminal). */ public static recycleTerminal(id: number): void { const terminal = this.terminals.find((t) => t.id === id) @@ -383,6 +402,12 @@ export class TerminalRegistry { return } + // Output no consumer read yet stays reachable. The getOrCreateTerminal + // sweep recycles the terminal again once the output is read (#704). + if (this.hasUnreadOutput(terminal)) { + return + } + if (terminal instanceof Terminal && !terminal.isClosed()) { try { terminal.terminal.dispose() diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index 3da59af6407..c296eae6b89 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -509,6 +509,37 @@ describe("TerminalRegistry", () => { } const dropIntegrationReport = (terminal: Terminal) => setIntegrationReport(terminal, undefined) + // An integration double whose executeCommand() never starts a stream: + // no onDidStartTerminalShellExecution, so TerminalProcess.run hits its + // stream timeout. executeCommand only; the real object also has cwd. + const stalledIntegration = () => + ({ executeCommand: vi.fn().mockReturnValue({}) }) as unknown as vscode.TerminalShellIntegration + + // Tracks whether a runCommand() call settled, so a test can assert the + // call is still pending before its deadline. + const trackSettled = (run: PromiseLike) => { + const state = { settled: false } + run.then( + () => { + state.settled = true + }, + () => { + state.settled = true + }, + ) + return state + } + + // Fresh callbacks per test: shared vi.fn()s would accumulate calls. + const makeCallbacks = () => + ({ + onLine: vi.fn(), + onCompleted: vi.fn(), + onShellExecutionStarted: vi.fn(), + onShellExecutionComplete: vi.fn(), + onNoShellIntegration: vi.fn(), + }) satisfies RooTerminalCallbacks + it("recycles a terminal whose confirmed integration is gone and spawns a replacement", async () => { const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal @@ -595,7 +626,14 @@ describe("TerminalRegistry", () => { } satisfies RooTerminalCallbacks const run = terminal.runCommand("echo hi", callbacks) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + // The terminal is busy for the whole wait, and the call is still + // pending before the deadline (path rule: check a pending call). + const settled = trackSettled(run) + expect(terminal.busy).toBe(true) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2) + expect(terminal.busy).toBe(true) + expect(settled.settled).toBe(false) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2 + 100) await run expect(terminal["shellIntegrationLost"]).toBe(true) @@ -621,7 +659,14 @@ describe("TerminalRegistry", () => { } satisfies RooTerminalCallbacks const run = terminal.runCommand("echo hi", callbacks) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + // The terminal is busy for the whole wait, and the call is still + // pending before the deadline (path rule: check a pending call). + const settled = trackSettled(run) + expect(terminal.busy).toBe(true) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2) + expect(terminal.busy).toBe(true) + expect(settled.settled).toBe(false) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2 + 100) await run expect(terminal["shellIntegrationLost"]).toBe(false) @@ -630,5 +675,145 @@ describe("TerminalRegistry", () => { vi.useRealTimers() } }) + + it("marks a proven terminal dead when its command stream does not start", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() + // VS Code keeps the integration object, so the wait resolves at + // once; the shell behind it no longer starts a stream (#704). + vsce.shellIntegration = stalledIntegration() + // The adoption confirmed the terminal before the command. + const terminal = new Terminal(94, vsce as unknown as vscode.Terminal, "/test/path") + const callbacks = makeCallbacks() + + const run = terminal.runCommand("echo hi", callbacks) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + + expect(callbacks.onNoShellIntegration).toHaveBeenCalledWith( + expect.objectContaining({ commandSubmitted: true }), + expect.anything(), + ) + expect(terminal.hasLostShellIntegration()).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it("does not mark a cold terminal whose first stream start fails", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() + const terminal = new Terminal(95, vsce as unknown as vscode.Terminal, "/test/path") + // The report arrives after construction: the first wait passes + // inside this call, so the terminal is still cold. + setIntegrationReport(terminal, stalledIntegration()) + const callbacks = makeCallbacks() + + const run = terminal.runCommand("echo hi", callbacks) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + + expect(callbacks.onNoShellIntegration).toHaveBeenCalledTimes(1) + expect(terminal.hasLostShellIntegration()).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + it("a successful run proves the terminal; the loss shows when the report goes", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + // The terminal starts cold; the report arrives before the call, + // so the fast-path wait resolves and the run proves the terminal. + const vsce = makeVsceTerminal() + const terminal = new Terminal(96, vsce as unknown as vscode.Terminal, "/test/path") + setIntegrationReport(terminal, stalledIntegration()) + expect(terminal.hasLostShellIntegration()).toBe(false) + const callbacks = makeCallbacks() + + const run = terminal.runCommand("echo hi", callbacks) + await vi.advanceTimersByTimeAsync(0) + expect(vsce.shellIntegration?.executeCommand).toHaveBeenCalledTimes(1) + + // The start and end events VS Code fires for the execution. + terminal.setActiveStream((async function* () {})()) + terminal.shellExecutionComplete({ exitCode: 0 }) + await run + + expect(callbacks.onCompleted).toHaveBeenCalledTimes(1) + expect(terminal.busy).toBe(false) + expect(terminal.hasLostShellIntegration()).toBe(false) + + // Long-session death: VS Code drops the report. + dropIntegrationReport(terminal) + expect(terminal.hasLostShellIntegration()).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it("an adopted terminal that reports integration is proven until the report goes", () => { + const vsce = makeVsceTerminal() + vsce.shellIntegration = stalledIntegration() + const terminal = new Terminal(97, vsce as unknown as vscode.Terminal, "/test/path") + + expect(terminal.hasLostShellIntegration()).toBe(false) + + dropIntegrationReport(terminal) + + expect(terminal.hasLostShellIntegration()).toBe(true) + }) + + it("defers recycling a dead terminal that holds unread output until a consumer reads it", async () => { + const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal + first["shellIntegrationSeen"] = true + dropIntegrationReport(first) + // A completed command left output that no consumer read yet. + // TerminalProcess double provides the three output-queue members. + const hasOutput = vi.fn(() => true) + const completed = { + command: "tail -f log", + getUnretrievedOutput: vi.fn(() => "tail output"), + hasUnretrievedOutput: hasOutput, + trimRetrievedOutput: vi.fn(), + } as unknown as TerminalProcess + first.completedProcesses.push(completed) + + const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + // The dead terminal waits for its reader; the command gets another one. + expect(second).not.toBe(first) + expect(first.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(first) + expect(TerminalRegistry.getUnretrievedOutput(first.id)).toBe("tail output") + + // The consumer read the output: the next selection recycles it. + hasOutput.mockReturnValue(false) + await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(first.terminal.dispose).toHaveBeenCalledTimes(1) + expect(TerminalRegistry["terminals"]).not.toContain(first) + }) + + it("removes the terminal from the registry even when VS Code's dispose throws", () => { + const terminal = TerminalRegistry.createTerminal("/test/path", "vscode") as Terminal + vi.mocked(terminal.terminal.dispose).mockImplementation(() => { + throw new Error("dispose failed") + }) + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + TerminalRegistry.recycleTerminal(terminal.id) + + expect(TerminalRegistry["terminals"]).not.toContain(terminal) + expect(errorSpy).toHaveBeenCalledWith( + `[TerminalRegistry] Error disposing terminal ${terminal.id} on recycle:`, + expect.objectContaining({ message: "dispose failed" }), + ) + }) }) }) From 45b79f7a4ed83f09aab122f356f233cd840cd2c7 Mon Sep 17 00:00:00 2001 From: Phil Date: Sat, 5 Dec 2026 06:35:17 +0100 Subject: [PATCH 3/6] fix(terminal): keep a terminal with a running submitted execution out of recycle (CR round 2) CodeRabbit round 2 on #2862 (issue #704). TerminalRegistry.recycleTerminal returns early while Terminal.activeShellExecution is set: executeCommand() ran and the stream start timed out, so the submitted command can still run in the terminal and a dispose would stop it. The onDidEndTerminalShellExecution handler clears the execution, the next getOrCreateTerminal sweep recycles the terminal; reuse stays blocked by the hasLostShellIntegration gates. The stream-timeout catch block documents that activeShellExecution is kept on purpose. Tests: pending-call checks before the stream deadline in both stream-timeout tests; cmd.exe shortcut never marks (red when the integrationImpossible guard is removed); second-priority gate refuses a deferred dead terminal for another task; execution guard test (red on the previous head). TerminalReuse.tla: Pick records confirmed when a command starts and FailIntegration marks only a confirmed terminal (MarkedOnlyIfConfirmed, cfg NoConfirmationGate); exec/ExecEnd/RunningExecutionKept with cfg NoExecutionGuard. Base cfg passes in 1,089 states; each sabotage cfg fails its named property. --- .../tla/TerminalReuse.NoConfirmationGate.cfg | 8 ++ .../tla/TerminalReuse.NoExecutionGuard.cfg | 9 ++ docs/architecture/tla/TerminalReuse.cfg | 4 +- docs/architecture/tla/TerminalReuse.tla | 120 +++++++++++++----- docs/architecture/tla/TerminalReuseMC.tla | 20 ++- src/integrations/terminal/TerminalProcess.ts | 5 + src/integrations/terminal/TerminalRegistry.ts | 10 ++ .../__tests__/TerminalRegistry.spec.ts | 112 ++++++++++++++-- 8 files changed, 238 insertions(+), 50 deletions(-) create mode 100644 docs/architecture/tla/TerminalReuse.NoConfirmationGate.cfg create mode 100644 docs/architecture/tla/TerminalReuse.NoExecutionGuard.cfg diff --git a/docs/architecture/tla/TerminalReuse.NoConfirmationGate.cfg b/docs/architecture/tla/TerminalReuse.NoConfirmationGate.cfg new file mode 100644 index 00000000000..3b523144f6d --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoConfirmationGate.cfg @@ -0,0 +1,8 @@ +\* Sabotage check. A failure marks the terminal whether or not it was +\* confirmed before the command. MarkedOnlyIfConfirmed must fail: a first +\* command that fails marks its cold terminal dead (no retry path). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + FailIntegration <- FailIntegrationIgnoresConfirmation +INVARIANTS TypeOK MarkedOnlyIfConfirmed diff --git a/docs/architecture/tla/TerminalReuse.NoExecutionGuard.cfg b/docs/architecture/tla/TerminalReuse.NoExecutionGuard.cfg new file mode 100644 index 00000000000..5b40e061d3f --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoExecutionGuard.cfg @@ -0,0 +1,9 @@ +\* Sabotage check. The sweep ignores a running execution. RunningExecutionKept +\* must fail: a dead idle terminal whose submitted command can still run is +\* removed, so its dispose can stop that command. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepDropsExecution +INVARIANTS TypeOK +PROPERTY RunningExecutionKept diff --git a/docs/architecture/tla/TerminalReuse.cfg b/docs/architecture/tla/TerminalReuse.cfg index 5b4f504185c..c1e750f7497 100644 --- a/docs/architecture/tla/TerminalReuse.cfg +++ b/docs/architecture/tla/TerminalReuse.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE -INVARIANTS TypeOK -PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept +INVARIANTS TypeOK MarkedOnlyIfConfirmed +PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept RunningExecutionKept diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla index f80a3846c1d..bd206aa0f2b 100644 --- a/docs/architecture/tla/TerminalReuse.tla +++ b/docs/architecture/tla/TerminalReuse.tla @@ -15,24 +15,32 @@ Properties: NoDeadSelection - a selection never places a command on a dead terminal (the sweep recycles it, and the gate refuses what the sweep kept). - NoDeadIdleAtSelection - after a selection, no dead idle terminal without - unread output stays in the registry. + NoDeadIdleAtSelection - after a selection, no dead idle terminal that the + sweep may recycle stays in the registry. BusyTerminalKept - a selection never removes a busy terminal: the command on it keeps its terminal. UnreadOutputKept - a selection never removes a terminal that holds output no consumer read yet; ReadOutput releases it for the next sweep. + RunningExecutionKept - a selection never removes a terminal whose + submitted execution can still run; ExecEnd releases it. + MarkedOnlyIfConfirmed - only a terminal that was proven before its + command is marked dead by a failure; a first command that fails stays + reusable (the retry path). Expected before the run: the base cfg passes. NoRecycleSweep and NoStallSweep fail NoDeadIdleAtSelection. NoDeadGate fails NoDeadSelection. NoBusyGuard fails BusyTerminalKept. NoUnreadGuard - fails UnreadOutputKept. + fails UnreadOutputKept. NoExecutionGuard fails RunningExecutionKept. + NoConfirmationGate fails MarkedOnlyIfConfirmed. Run each cfg on TerminalReuseMC.tla. The MC module holds the sabotage operators. - Result: the base cfg passes in 225 distinct states (under 10 s). - NoRecycleSweep fails NoDeadIdleAtSelection in 48 states. - NoStallSweep fails NoDeadIdleAtSelection in 48 states. - NoDeadGate fails NoDeadSelection in 89 states. - NoBusyGuard fails BusyTerminalKept in 48 states. - NoUnreadGuard fails UnreadOutputKept in 89 states. + Result: the base cfg passes in 1,089 distinct states (under 10 s). + NoRecycleSweep fails NoDeadIdleAtSelection in 108 states. + NoStallSweep fails NoDeadIdleAtSelection in 216 states. + NoDeadGate fails NoDeadSelection in 113 states. + NoBusyGuard fails BusyTerminalKept in 50 states. + NoUnreadGuard fails UnreadOutputKept in 113 states. + NoExecutionGuard fails RunningExecutionKept in 114 states. + NoConfirmationGate fails MarkedOnlyIfConfirmed in 21 states. Review ratchet (PR #2862, CodeRabbit round 1): 2 covered, 2 added, 3 gap. Added: overlapping commands, ShellDies during a command, the selection gate, BusyTerminalKept, NoDeadSelection as a selection-time property @@ -43,7 +51,16 @@ VS Code's dispose does; dispose is an oracle (Regression Evidence 3). Gap: the pending-call test rule (discussion_r4808051276) and the runCommand success-path and constructor evidence tests (Regression - Evidence 1, 2) are test-evidence demands, not behavior. *) + Evidence 1, 2) are test-evidence demands, not behavior. + Review ratchet (PR #2862, CodeRabbit round 2): 2 covered, 2 added, 1 gap. + Added: confirmed is recorded when the command starts and FailIntegration + marks only a confirmed terminal, MarkedOnlyIfConfirmed, cfg + NoConfirmationGate (discussion_r4809292609). Added: exec, ExecEnd, + RunningExecutionKept, cfg NoExecutionGuard (discussion_r4809292614). + Covered: a cmd.exe terminal is never confirmed, so FailIntegration never + marks it (Regression Evidence 1). Covered: both selection gates are + Reuseable (Regression Evidence 2). Gap: the pending-call rule for the two + stream-timeout tests (discussion_r4809292612) is a test rule. *) EXTENDS Naturals, FiniteSets @@ -52,47 +69,58 @@ Ids == {1, 2} \* two slots: one busy terminal plus one replacement VARIABLE registry \* set of entries, one per registered VS Code terminal (* integ is the VS Code shell-integration report. seen records that the - integration was confirmed at least once. stalled marks a terminal whose - command observed a failure the report does not show. unread marks output - of a completed command that no consumer read yet. busy mirrors + integration was confirmed at least once. confirmed records that the + terminal was seen when its command started (Terminal.runCommand captures + confirmedBefore). stalled marks a terminal whose command observed a + failure the report does not show. unread marks output of a completed + command that no consumer read yet. exec marks a submitted execution that + can still run (Terminal.activeShellExecution is set). busy mirrors RooTerminal.busy. A closed terminal leaves the registry (onDidCloseTerminal removes it). *) -Entry(id) == [id |-> id, integ |-> "off", seen |-> FALSE, busy |-> FALSE, stalled |-> FALSE, unread |-> FALSE] +Entry(id) == + [id |-> id, integ |-> "off", seen |-> FALSE, confirmed |-> FALSE, busy |-> FALSE, stalled |-> FALSE, unread |-> FALSE, + exec |-> FALSE] IsDead(e) == e.seen /\ (e.integ = "off" \/ e.stalled) \* confirmed once, dead now (* The selection gate (the find calls in getOrCreateTerminal). A dead - terminal the sweep kept (busy, or unread output) is not selected. *) + terminal the sweep kept (busy, unread output, or a running execution) + is not selected. *) Reuseable(e) == ~e.busy /\ ~IsDead(e) -(* The sweep before a selection: recycle dead idle terminals without unread - output. Keep busy terminals and terminals that hold unread output. *) -Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread} +(* The sweep before a selection (recycleTerminal): recycle dead idle + terminals. Keep busy terminals, terminals that hold unread output, and + terminals whose submitted execution can still run. *) +Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread \/ e.exec} (* The marking records an observed integration failure (no_shell_integration on a terminal that was confirmed before the command). *) MarkDead(e) == [e EXCEPT !.stalled = TRUE] +(* The command starts on the terminal. confirmed captures whether the + terminal was proven before this command. *) +Pick(e) == [e EXCEPT !.busy = TRUE, !.confirmed = e.seen] + Init == registry = {} -(* getOrCreateTerminal spawns a fresh terminal and the command claims it - (Terminal.runCommand sets busy). *) +(* getOrCreateTerminal spawns a fresh terminal and the command claims it. *) RunNew == \E id \in Ids : /\ ~\E e \in Sweep(registry) : e.id = id - /\ registry' = Sweep(registry) \cup {[Entry(id) EXCEPT !.busy = TRUE]} + /\ registry' = Sweep(registry) \cup {Pick(Entry(id))} (* getOrCreateTerminal reuses an idle terminal for the command. *) RunReused == \E e \in Sweep(registry) : /\ Reuseable(e) - /\ registry' = {f \in Sweep(registry) : f.id /= e.id} \cup {[e EXCEPT !.busy = TRUE]} + /\ registry' = {f \in Sweep(registry) : f.id /= e.id} \cup {Pick(e)} (* shellExecutionComplete releases the terminal after the command. The completed command can leave output that no consumer read yet. *) CompleteCommand == \E e \in registry : /\ e.busy + /\ ~e.exec /\ \E u \in BOOLEAN : registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.busy = FALSE, !.unread = e.unread \/ u]} @@ -102,6 +130,13 @@ ReadOutput == /\ e.unread /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.unread = FALSE]} +(* VS Code reports the end of the submitted execution + (onDidEndTerminalShellExecution clears Terminal.activeShellExecution). *) +ExecEnd == + \E e \in registry : + /\ e.exec + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.exec = FALSE]} + (* Shell integration activates (waitForShellIntegration resolves, or an adopted terminal reports it): the report turns on and the terminal counts as proven. *) @@ -121,25 +156,30 @@ ShellDies == /\ e.integ = "on" /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "off"]} -(* A command on a terminal confirmed before it fails (no_shell_integration): - the shell died mid-session and only the failed command reveals it. The - command ends at once; MarkDead records the observed failure and the - terminal is released for the next selection. *) +(* A command on a proven terminal fails (no_shell_integration). The wait + timeout submitted nothing; the stream timeout submitted the command, so + an execution can still run (exec). A terminal confirmed before the + command is marked dead; a terminal proven inside this command stays + reusable (the retry path). The command ends at once. *) FailIntegration == \E e \in registry : /\ e.busy /\ e.seen /\ ~e.stalled /\ e.integ = "on" - /\ registry' = {f \in registry : f.id /= e.id} \cup {[MarkDead(e) EXCEPT !.busy = FALSE]} + /\ \E s \in BOOLEAN : + IF e.confirmed + THEN registry' = {f \in registry : f.id /= e.id} \cup {[MarkDead(e) EXCEPT !.busy = FALSE, !.exec = s]} + ELSE registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.busy = FALSE, !.exec = s]} (* The user closes an idle terminal (onDidCloseTerminal removes it). *) CloseTerminal == \E e \in registry : /\ ~e.busy + /\ ~e.exec /\ registry' = {f \in registry : f.id /= e.id} -Next == RunNew \/ RunReused \/ CompleteCommand \/ ReadOutput \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal +Next == RunNew \/ RunReused \/ CompleteCommand \/ ReadOutput \/ ExecEnd \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal Spec == Init /\ [][Next]_registry @@ -148,25 +188,29 @@ TypeOK == /\ e.id \in Ids /\ e.integ \in {"on", "off"} /\ e.seen \in BOOLEAN + /\ e.confirmed \in BOOLEAN /\ e.busy \in BOOLEAN /\ e.stalled \in BOOLEAN /\ e.unread \in BOOLEAN + /\ e.exec \in BOOLEAN /\ (e.integ = "on") => e.seen /\ e.stalled => e.seen + /\ e.confirmed => e.seen /\ Cardinality({f \in registry : f.id = e.id}) = 1 Selection == RunNew \/ RunReused (* Selection-time safety: a command is never placed on a dead terminal. The - terminal keeps its state; only busy changes (a fresh spawn has another - state, so it is not this terminal). *) + terminal keeps its state; only busy and confirmed change (a fresh spawn + has another state, so it is not this terminal). *) NoDeadSelection == - [][ Selection => \A e \in registry : (~e.busy /\ [e EXCEPT !.busy = TRUE] \in registry') => ~IsDead(e) ]_registry + [][ Selection => \A e \in registry : (~e.busy /\ Pick(e) \in registry') => ~IsDead(e) ]_registry -(* After a selection, no dead idle terminal without unread output stays in - the registry: the sweep recycled it, so dead terminals do not pile up. *) +(* After a selection, no dead idle terminal that the sweep may recycle + stays in the registry: the sweep recycled it, so dead terminals do not + pile up. *) NoDeadIdleAtSelection == - [][ Selection => ~\E e \in registry' : IsDead(e) /\ ~e.busy /\ ~e.unread ]_registry + [][ Selection => ~\E e \in registry' : IsDead(e) /\ ~e.busy /\ ~e.unread /\ ~e.exec ]_registry (* Continued execution: the sweep never removes a busy terminal. *) BusyTerminalKept == @@ -177,4 +221,12 @@ BusyTerminalKept == UnreadOutputKept == [][ Selection => \A e \in registry : e.unread => \E f \in registry' : f.id = e.id /\ f.unread ]_registry +(* The sweep never removes a terminal whose submitted execution can still + run: a dispose can stop that command. *) +RunningExecutionKept == + [][ Selection => \A e \in registry : e.exec => \E f \in registry' : f.id = e.id /\ f.exec ]_registry + +(* A failure marks only a terminal that was confirmed before its command. *) +MarkedOnlyIfConfirmed == \A e \in registry : e.stalled => e.confirmed + ==== diff --git a/docs/architecture/tla/TerminalReuseMC.tla b/docs/architecture/tla/TerminalReuseMC.tla index a718511e59c..12c2632a261 100644 --- a/docs/architecture/tla/TerminalReuseMC.tla +++ b/docs/architecture/tla/TerminalReuseMC.tla @@ -7,15 +7,29 @@ NoSweep(nm) == nm \* Sabotage: the sweep keeps only the death VS Code reports. A terminal \* marked stalled (observed failure, no report) is no longer recycled. -SweepReportedOnly(nm) == {e \in nm : ~(e.seen /\ e.integ = "off") \/ e.busy \/ e.unread} +SweepReportedOnly(nm) == {e \in nm : ~(e.seen /\ e.integ = "off") \/ e.busy \/ e.unread \/ e.exec} \* Sabotage: the sweep drops busy terminals with it (no busy guard). -SweepDropsBusy(nm) == {e \in nm : ~IsDead(e) \/ e.unread} +SweepDropsBusy(nm) == {e \in nm : ~IsDead(e) \/ e.unread \/ e.exec} \* Sabotage: the sweep ignores unread output (a deferred terminal is recycled). -SweepIgnoresUnread(nm) == {e \in nm : ~IsDead(e) \/ e.busy} +SweepIgnoresUnread(nm) == {e \in nm : ~IsDead(e) \/ e.busy \/ e.exec} + +\* Sabotage: the sweep ignores a running execution (the terminal is disposed). +SweepDropsExecution(nm) == {e \in nm : ~IsDead(e) \/ e.busy \/ e.unread} \* Sabotage: the selection gate no longer refuses a dead terminal. ReuseableNoDeath(e) == ~e.busy +\* Sabotage: a failure marks the terminal whether or not it was confirmed +\* before the command (no confirmation gate). +FailIntegrationIgnoresConfirmation == + \E e \in registry : + /\ e.busy + /\ e.seen + /\ ~e.stalled + /\ e.integ = "on" + /\ \E s \in BOOLEAN : + registry' = {f \in registry : f.id /= e.id} \cup {[MarkDead(e) EXCEPT !.busy = FALSE, !.exec = s]} + ==== diff --git a/src/integrations/terminal/TerminalProcess.ts b/src/integrations/terminal/TerminalProcess.ts index d1643dec3a4..ada4de4e095 100644 --- a/src/integrations/terminal/TerminalProcess.ts +++ b/src/integrations/terminal/TerminalProcess.ts @@ -222,6 +222,11 @@ export class TerminalProcess extends BaseTerminalProcess { // Stream timeout or other error occurred console.error("[Terminal Process] Stream error:", error.message) + // Deliberately keep terminal.activeShellExecution set: it is the + // signal TerminalRegistry.recycleTerminal uses to refuse disposal + // while this submitted execution may still be running; only the + // onDidEndTerminalShellExecution handler may clear it here. + // Emit completed event with error message this.emit( "completed", diff --git a/src/integrations/terminal/TerminalRegistry.ts b/src/integrations/terminal/TerminalRegistry.ts index bc84ed6229c..96109903bfb 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -402,6 +402,16 @@ export class TerminalRegistry { return } + // Do not dispose while a submitted execution may still be running: + // executeCommand() ran, then the stream start timed out. The + // onDidEndTerminalShellExecution handler clears activeShellExecution, + // releasing this deferral; the next getOrCreateTerminal() sweep then + // recycles the terminal (#704). Reuse stays blocked meanwhile by the + // hasLostShellIntegration() selection gates. + if (terminal instanceof Terminal && terminal.activeShellExecution !== undefined) { + return + } + // Output no consumer read yet stays reachable. The getOrCreateTerminal // sweep recycles the terminal again once the output is read (#704). if (this.hasUnreadOutput(terminal)) { diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index c296eae6b89..88a8a3382a1 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -540,6 +540,21 @@ describe("TerminalRegistry", () => { onNoShellIntegration: vi.fn(), }) satisfies RooTerminalCallbacks + // Pushes a completed process with unread output into the terminal's + // queue. TerminalProcess double provides the three output-queue + // members. Returns the hasUnretrievedOutput mock so a test can end + // the deferral (the consumer read the output). + const pushUnreadOutput = (terminal: Terminal) => { + const hasOutput = vi.fn(() => true) + terminal.completedProcesses.push({ + command: "tail -f log", + getUnretrievedOutput: vi.fn(() => "tail output"), + hasUnretrievedOutput: hasOutput, + trimRetrievedOutput: vi.fn(), + } as unknown as TerminalProcess) + return hasOutput + } + it("recycles a terminal whose confirmed integration is gone and spawns a replacement", async () => { const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal @@ -689,7 +704,14 @@ describe("TerminalRegistry", () => { const callbacks = makeCallbacks() const run = terminal.runCommand("echo hi", callbacks) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + // The call is pending and the terminal busy before the stream + // deadline (path rule: check a pending call). + const settled = trackSettled(run) + expect(terminal.busy).toBe(true) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2) + expect(terminal.busy).toBe(true) + expect(settled.settled).toBe(false) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2 + 100) await run expect(callbacks.onNoShellIntegration).toHaveBeenCalledWith( @@ -714,7 +736,14 @@ describe("TerminalRegistry", () => { const callbacks = makeCallbacks() const run = terminal.runCommand("echo hi", callbacks) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + // The call is pending and the terminal busy before the stream + // deadline (path rule: check a pending call). + const settled = trackSettled(run) + expect(terminal.busy).toBe(true) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2) + expect(terminal.busy).toBe(true) + expect(settled.settled).toBe(false) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2 + 100) await run expect(callbacks.onNoShellIntegration).toHaveBeenCalledTimes(1) @@ -774,15 +803,7 @@ describe("TerminalRegistry", () => { first["shellIntegrationSeen"] = true dropIntegrationReport(first) // A completed command left output that no consumer read yet. - // TerminalProcess double provides the three output-queue members. - const hasOutput = vi.fn(() => true) - const completed = { - command: "tail -f log", - getUnretrievedOutput: vi.fn(() => "tail output"), - hasUnretrievedOutput: hasOutput, - trimRetrievedOutput: vi.fn(), - } as unknown as TerminalProcess - first.completedProcesses.push(completed) + const hasOutput = pushUnreadOutput(first) const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") @@ -815,5 +836,74 @@ describe("TerminalRegistry", () => { expect.objectContaining({ message: "dispose failed" }), ) }) + + it("does not select a deferred dead terminal for another task (second-priority gate)", async () => { + const first = (await TerminalRegistry.getOrCreateTerminal("/test/path", "owner", "vscode")) as Terminal + first["shellIntegrationSeen"] = true + dropIntegrationReport(first) + pushUnreadOutput(first) + + const other = await TerminalRegistry.getOrCreateTerminal("/test/path", "other", "vscode") + + expect(other).not.toBe(first) + expect(first.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(first) + }) + + it("keeps a terminal whose submitted execution may still run until VS Code reports its end", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() + // The adoption confirmed the terminal before the command; the + // integration object stays, so the wait resolves at once. + vsce.shellIntegration = stalledIntegration() + const terminal = new Terminal(98, vsce as unknown as vscode.Terminal, "/test/path") + TerminalRegistry["terminals"].push(terminal) + terminal.taskId = "task" + const run = terminal.runCommand("echo hi", makeCallbacks()) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + // The stream timed out after executeCommand(): dead and idle, + // but the submitted execution is still open. + expect(terminal.hasLostShellIntegration()).toBe(true) + expect(terminal.busy).toBe(false) + expect(terminal.activeShellExecution).toBeDefined() + + const during = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + // A dispose can stop the command that still runs. + expect(during).not.toBe(terminal) + expect(terminal.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(terminal) + + // onDidEndTerminalShellExecution clears the execution: the + // next selection recycles the terminal. + terminal.activeShellExecution = undefined + await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(terminal.terminal.dispose).toHaveBeenCalledTimes(1) + expect(TerminalRegistry["terminals"]).not.toContain(terminal) + } finally { + vi.useRealTimers() + } + }) + + it("never marks a cmd.exe terminal: the shortcut's failure is a platform property", async () => { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(true) + const vsce = makeVsceTerminal() + // Adopted with a report, so the terminal is confirmed before the call. + vsce.shellIntegration = stalledIntegration() + const terminal = new Terminal(99, vsce as unknown as vscode.Terminal, "/test/path") + const callbacks = makeCallbacks() + + await terminal.runCommand("echo hi", callbacks) + + expect(callbacks.onNoShellIntegration).toHaveBeenCalledWith( + expect.objectContaining({ commandSubmitted: false }), + expect.anything(), + ) + expect(terminal.hasLostShellIntegration()).toBe(false) + }) }) }) From aeacc2bed17b7678a624cfdacdab3996492f0da8 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 14:19:50 +0100 Subject: [PATCH 4/6] fix(terminal): bound the recycle deferral for a stalled execution (CR round 3) The recycle deferral for an open activeShellExecution was unbounded: if VS Code never fires onDidEndTerminalShellExecution, the terminal stayed registered forever (Lifecycle Resource Cleanup pre-merge check). runCommand now records stalledExecutionAt when the stream-start timeout marks a confirmed terminal dead; hasExecutionStallOutlivedDeferral expires the protection after one more shell-integration timeout; recycleTerminal then disposes and removes the terminal on the next sweep. A terminal whose execution never stalled keeps the round-2 protection. Tests: bounded-deferral recycle test + repeated-stall pile-up test (both RED-verified on the pre-fix code), pending-call assertions in the stream-timeout test (CR Minor 4809359735). TLA: TerminalReuse gains expired/DeferralElapses/StalledNotPinnedForever (base cfg passes 1,369 states; NoBoundedRelease sabotage fails it at 374; all sabotages fail their named invariants, reproduced twice). Ratchet: 0 covered, 1 added, 1 gap. --- .../tla/TerminalReuse.NoBoundedRelease.cfg | 9 +++ docs/architecture/tla/TerminalReuse.cfg | 2 +- docs/architecture/tla/TerminalReuse.tla | 69 ++++++++++++---- docs/architecture/tla/TerminalReuseMC.tla | 4 + src/integrations/terminal/Terminal.ts | 29 +++++++ src/integrations/terminal/TerminalRegistry.ts | 6 +- .../__tests__/TerminalRegistry.spec.ts | 80 ++++++++++++++++++- 7 files changed, 180 insertions(+), 19 deletions(-) create mode 100644 docs/architecture/tla/TerminalReuse.NoBoundedRelease.cfg diff --git a/docs/architecture/tla/TerminalReuse.NoBoundedRelease.cfg b/docs/architecture/tla/TerminalReuse.NoBoundedRelease.cfg new file mode 100644 index 00000000000..b06c522e959 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoBoundedRelease.cfg @@ -0,0 +1,9 @@ +\* Sabotage check. The sweep keeps a stalled execution after its deferral +\* expired. StalledNotPinnedForever must fail: VS Code never reporting the +\* execution's end pins the dead terminal in the registry forever. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepKeepsExpired +INVARIANTS TypeOK +PROPERTY StalledNotPinnedForever diff --git a/docs/architecture/tla/TerminalReuse.cfg b/docs/architecture/tla/TerminalReuse.cfg index c1e750f7497..70049ddea07 100644 --- a/docs/architecture/tla/TerminalReuse.cfg +++ b/docs/architecture/tla/TerminalReuse.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE INVARIANTS TypeOK MarkedOnlyIfConfirmed -PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept RunningExecutionKept +PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept RunningExecutionKept StalledNotPinnedForever diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla index bd206aa0f2b..ba330444a38 100644 --- a/docs/architecture/tla/TerminalReuse.tla +++ b/docs/architecture/tla/TerminalReuse.tla @@ -23,6 +23,10 @@ output no consumer read yet; ReadOutput releases it for the next sweep. RunningExecutionKept - a selection never removes a terminal whose submitted execution can still run; ExecEnd releases it. + StalledNotPinnedForever - after a selection, no terminal whose stalled + execution outlived its bounded deferral stays in the registry: the + sweep disposes it even though VS Code never reported the execution's + end. A running execution (no stall observed) never expires. MarkedOnlyIfConfirmed - only a terminal that was proven before its command is marked dead by a failure; a first command that fails stays reusable (the retry path). @@ -30,17 +34,20 @@ NoStallSweep fail NoDeadIdleAtSelection. NoDeadGate fails NoDeadSelection. NoBusyGuard fails BusyTerminalKept. NoUnreadGuard fails UnreadOutputKept. NoExecutionGuard fails RunningExecutionKept. - NoConfirmationGate fails MarkedOnlyIfConfirmed. + NoConfirmationGate fails MarkedOnlyIfConfirmed. NoBoundedRelease + fails StalledNotPinnedForever. Run each cfg on TerminalReuseMC.tla. The MC module holds the sabotage operators. - Result: the base cfg passes in 1,089 distinct states (under 10 s). - NoRecycleSweep fails NoDeadIdleAtSelection in 108 states. - NoStallSweep fails NoDeadIdleAtSelection in 216 states. - NoDeadGate fails NoDeadSelection in 113 states. - NoBusyGuard fails BusyTerminalKept in 50 states. - NoUnreadGuard fails UnreadOutputKept in 113 states. + Result: the base cfg passes in 1,369 distinct states (under 10 s; + 1,089 before the round-3 expired field). NoRecycleSweep fails + NoDeadIdleAtSelection in 108 states. NoStallSweep fails + NoDeadIdleAtSelection in 216 states. NoDeadGate fails + NoDeadSelection in 113 states. NoBusyGuard fails BusyTerminalKept + in 50 states. NoUnreadGuard fails UnreadOutputKept in 113 states. NoExecutionGuard fails RunningExecutionKept in 114 states. NoConfirmationGate fails MarkedOnlyIfConfirmed in 21 states. + NoBoundedRelease fails StalledNotPinnedForever in 374 states. Counts + reproduced twice. Review ratchet (PR #2862, CodeRabbit round 1): 2 covered, 2 added, 3 gap. Added: overlapping commands, ShellDies during a command, the selection gate, BusyTerminalKept, NoDeadSelection as a selection-time property @@ -60,7 +67,13 @@ Covered: a cmd.exe terminal is never confirmed, so FailIntegration never marks it (Regression Evidence 1). Covered: both selection gates are Reuseable (Regression Evidence 2). Gap: the pending-call rule for the two - stream-timeout tests (discussion_r4809292612) is a test rule. *) + stream-timeout tests (discussion_r4809292612) is a test rule. + Review ratchet (PR #2862, CodeRabbit round 3): 0 covered, 1 added, + 1 gap. Added: expired, DeferralElapses, StalledNotPinnedForever, the + sweep keeps only a non-expired execution, cfg NoBoundedRelease + (Lifecycle Resource Cleanup pre-merge check, review 6200865221). + Gap: the pending-call rule for the timeout test + (discussion_r4809359735) is a test rule, not model behavior. *) EXTENDS Naturals, FiniteSets @@ -74,12 +87,13 @@ VARIABLE registry \* set of entries, one per registered VS Code terminal confirmedBefore). stalled marks a terminal whose command observed a failure the report does not show. unread marks output of a completed command that no consumer read yet. exec marks a submitted execution that - can still run (Terminal.activeShellExecution is set). busy mirrors - RooTerminal.busy. A closed terminal leaves the registry + can still run (Terminal.activeShellExecution is set). expired marks a + stalled execution whose bounded deferral passed without an end event. + busy mirrors RooTerminal.busy. A closed terminal leaves the registry (onDidCloseTerminal removes it). *) Entry(id) == [id |-> id, integ |-> "off", seen |-> FALSE, confirmed |-> FALSE, busy |-> FALSE, stalled |-> FALSE, unread |-> FALSE, - exec |-> FALSE] + exec |-> FALSE, expired |-> FALSE] IsDead(e) == e.seen /\ (e.integ = "off" \/ e.stalled) \* confirmed once, dead now @@ -90,8 +104,9 @@ Reuseable(e) == ~e.busy /\ ~IsDead(e) (* The sweep before a selection (recycleTerminal): recycle dead idle terminals. Keep busy terminals, terminals that hold unread output, and - terminals whose submitted execution can still run. *) -Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread \/ e.exec} + terminals whose submitted execution has not outlived its bounded + deferral. *) +Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread \/ (e.exec /\ ~e.expired)} (* The marking records an observed integration failure (no_shell_integration on a terminal that was confirmed before the command). *) @@ -137,6 +152,18 @@ ExecEnd == /\ e.exec /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.exec = FALSE]} +(* The bounded deferral for a stalled execution expires (PR #2862 round 3, + Lifecycle Resource Cleanup): the stream start timed out, VS Code never + reported the execution's end, and one more shell-integration timeout + passed. The next sweep disposes the terminal. Only a stalled execution + expires; a running one never does. *) +DeferralElapses == + \E e \in registry : + /\ e.exec + /\ e.stalled + /\ ~e.expired + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.expired = TRUE]} + (* Shell integration activates (waitForShellIntegration resolves, or an adopted terminal reports it): the report turns on and the terminal counts as proven. *) @@ -179,7 +206,7 @@ CloseTerminal == /\ ~e.exec /\ registry' = {f \in registry : f.id /= e.id} -Next == RunNew \/ RunReused \/ CompleteCommand \/ ReadOutput \/ ExecEnd \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal +Next == RunNew \/ RunReused \/ CompleteCommand \/ ReadOutput \/ ExecEnd \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal \/ DeferralElapses Spec == Init /\ [][Next]_registry @@ -193,6 +220,7 @@ TypeOK == /\ e.stalled \in BOOLEAN /\ e.unread \in BOOLEAN /\ e.exec \in BOOLEAN + /\ e.expired \in BOOLEAN /\ (e.integ = "on") => e.seen /\ e.stalled => e.seen /\ e.confirmed => e.seen @@ -222,9 +250,18 @@ UnreadOutputKept == [][ Selection => \A e \in registry : e.unread => \E f \in registry' : f.id = e.id /\ f.unread ]_registry (* The sweep never removes a terminal whose submitted execution can still - run: a dispose can stop that command. *) + run: a dispose can stop that command. A stalled execution whose deferral + expired is not protected (StalledNotPinnedForever). *) RunningExecutionKept == - [][ Selection => \A e \in registry : e.exec => \E f \in registry' : f.id = e.id /\ f.exec ]_registry + [][ Selection => \A e \in registry : (e.exec /\ ~e.expired) => \E f \in registry' : f.id = e.id /\ f.exec /\ ~f.expired ]_registry + +(* After a selection, no abandoned stalled execution pins its terminal in + the registry: the sweep disposed it. VS Code staying silent about the + execution's end pins nothing forever. Unread output still holds the + terminal for its reader (UnreadOutputKept); the next sweep after + ReadOutput disposes it. *) +StalledNotPinnedForever == + [][ Selection => ~\E e \in registry' : e.exec /\ e.expired /\ ~e.unread ]_registry (* A failure marks only a terminal that was confirmed before its command. *) MarkedOnlyIfConfirmed == \A e \in registry : e.stalled => e.confirmed diff --git a/docs/architecture/tla/TerminalReuseMC.tla b/docs/architecture/tla/TerminalReuseMC.tla index 12c2632a261..0751f26e730 100644 --- a/docs/architecture/tla/TerminalReuseMC.tla +++ b/docs/architecture/tla/TerminalReuseMC.tla @@ -18,6 +18,10 @@ SweepIgnoresUnread(nm) == {e \in nm : ~IsDead(e) \/ e.busy \/ e.exec} \* Sabotage: the sweep ignores a running execution (the terminal is disposed). SweepDropsExecution(nm) == {e \in nm : ~IsDead(e) \/ e.busy \/ e.unread} +\* Sabotage: the sweep keeps a stalled execution after its deferral expired +\* (the sweep before the bounded release). +SweepKeepsExpired(nm) == {e \in nm : ~IsDead(e) \/ e.busy \/ e.unread \/ e.exec} + \* Sabotage: the selection gate no longer refuses a dead terminal. ReuseableNoDeath(e) == ~e.busy diff --git a/src/integrations/terminal/Terminal.ts b/src/integrations/terminal/Terminal.ts index d9aaf33fd9e..076d6ef8843 100644 --- a/src/integrations/terminal/Terminal.ts +++ b/src/integrations/terminal/Terminal.ts @@ -22,6 +22,11 @@ export class Terminal extends BaseTerminal { private shellIntegrationSeen: boolean = false private shellIntegrationLost: boolean = false + // When this terminal's stream start timed out on a confirmed terminal: + // the moment the stall was observed. Starts the bounded recycle deferral + // (hasExecutionStallOutlivedDeferral); the next runCommand clears it. + private stalledExecutionAt?: number + constructor(id: number, terminal: vscode.Terminal | undefined, cwd: string) { super("vscode", id, cwd, Terminal.getReuseKey()) @@ -100,12 +105,33 @@ export class Terminal extends BaseTerminal { return this.shellIntegrationLost || (this.shellIntegrationSeen && !this.terminal.shellIntegration) } + /** + * True when the stalled submitted execution has outlived the bounded + * deferral. The stream start timed out on this terminal, so the command + * was submitted but its execution was never confirmed. recycleTerminal + * defers disposal while the execution may still run; VS Code can stay + * silent about the execution's end forever, so the deferral expires + * after one more shell-integration timeout and the next sweep disposes + * the terminal (#704, Lifecycle Resource Cleanup). An execution whose + * stream start never timed out never expires. + */ + public hasExecutionStallOutlivedDeferral(): boolean { + return ( + this.stalledExecutionAt !== undefined && + Date.now() - this.stalledExecutionAt >= Terminal.getShellIntegrationTimeout() + ) + } + public override runCommand(command: string, callbacks: RooTerminalCallbacks): RooTerminalProcessResultPromise { // We set busy before the command is running because the terminal may be // waiting on terminal integration, and we must prevent another instance // from selecting the terminal for use during that time. this.busy = true + // A new command runs on its own stall clock: an old mark must not + // expire this command's deferral before its own stream start fails. + this.stalledExecutionAt = undefined + // TRUE only when an earlier command or an adopted report proved this // terminal integrated before this call (#704). A terminal that passes // the wait for the first time inside this call is still cold. @@ -134,6 +160,9 @@ export class Terminal extends BaseTerminal { // not replayed. if (confirmedBefore && !integrationImpossible) { this.shellIntegrationLost = true + // The submitted execution was never confirmed: start the + // bounded recycle deferral for it (#704). + this.stalledExecutionAt = Date.now() } callbacks.onNoShellIntegration?.(details, process) diff --git a/src/integrations/terminal/TerminalRegistry.ts b/src/integrations/terminal/TerminalRegistry.ts index 96109903bfb..c2f7d1c011c 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -408,7 +408,11 @@ export class TerminalRegistry { // releasing this deferral; the next getOrCreateTerminal() sweep then // recycles the terminal (#704). Reuse stays blocked meanwhile by the // hasLostShellIntegration() selection gates. - if (terminal instanceof Terminal && terminal.activeShellExecution !== undefined) { + if ( + terminal instanceof Terminal && + terminal.activeShellExecution !== undefined && + !terminal.hasExecutionStallOutlivedDeferral() + ) { return } diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index 88a8a3382a1..cfb05f51ec1 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -862,7 +862,14 @@ describe("TerminalRegistry", () => { TerminalRegistry["terminals"].push(terminal) terminal.taskId = "task" const run = terminal.runCommand("echo hi", makeCallbacks()) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + // The call is pending and the terminal busy before the stream + // deadline (path rule: check a pending call). + const settled = trackSettled(run) + expect(terminal.busy).toBe(true) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2) + expect(terminal.busy).toBe(true) + expect(settled.settled).toBe(false) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() / 2 + 100) await run // The stream timed out after executeCommand(): dead and idle, // but the submitted execution is still open. @@ -889,6 +896,77 @@ describe("TerminalRegistry", () => { } }) + it("recycles a dead terminal once its stalled execution outlives the bounded deferral", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const vsce = makeVsceTerminal() + vsce.shellIntegration = stalledIntegration() + const terminal = new Terminal(100, vsce as unknown as vscode.Terminal, "/test/path") + TerminalRegistry["terminals"].push(terminal) + terminal.taskId = "task" + const run = terminal.runCommand("echo hi", makeCallbacks()) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + // VS Code never fires onDidEndTerminalShellExecution here. + expect(terminal.activeShellExecution).toBeDefined() + + // Within the deferral the execution still protects the terminal. + const during = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + expect(during).not.toBe(terminal) + expect(terminal.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(terminal) + + // Past the deferral the execution no longer protects the terminal: + // the next selection recycles it like any other dead terminal. + await vi.advanceTimersByTimeAsync(60_000) + const after = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(after).not.toBe(terminal) + expect(terminal.terminal.dispose).toHaveBeenCalledTimes(1) + expect(TerminalRegistry["terminals"]).not.toContain(terminal) + } finally { + vi.useRealTimers() + } + }) + + it("does not let dead terminals pile up across repeated stalled commands", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + const stalled: Terminal[] = [] + + for (let attempt = 0; attempt < 3; attempt++) { + const terminal = (await TerminalRegistry.getOrCreateTerminal( + "/test/path", + "task", + "vscode", + )) as Terminal + // Proven before the command; the integration object stays, but its + // executeCommand() never starts a stream. + terminal["shellIntegrationSeen"] = true + setIntegrationReport(terminal, stalledIntegration()) + const run = terminal.runCommand("echo hi", makeCallbacks()) + await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await run + expect(terminal.hasLostShellIntegration()).toBe(true) + stalled.push(terminal) + await vi.advanceTimersByTimeAsync(60_000) + } + + const live = (await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode")) as Terminal + + // Every stalled terminal was recycled; only the live one stays registered. + expect(stalled).not.toContain(live) + for (const terminal of stalled) { + expect(terminal.terminal.dispose).toHaveBeenCalledTimes(1) + } + expect(TerminalRegistry["terminals"]).toStrictEqual([live]) + } finally { + vi.useRealTimers() + } + }) + it("never marks a cmd.exe terminal: the shortcut's failure is a platform property", async () => { vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(true) const vsce = makeVsceTerminal() From 874c943e219187678949d7a78e4de9a65d007f38 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 14:47:35 +0100 Subject: [PATCH 5/6] test(terminal): pin the exact deferral boundary (CR round 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bounded-deferral test advanced 60s past the stall, which cannot detect a wrongly shortened deferral. Stub a known timeout and assert retention one millisecond before expiry, then recycling one millisecond after — sabotage-checked against a halved deferral, which the 60s advance passed and the boundary assertions fail. TerminalReuse.tla header records the round-4 ratchet (test-rule gap); no model change, TLC 9/9 polarity unchanged. --- docs/architecture/tla/TerminalReuse.tla | 6 +++++- .../__tests__/TerminalRegistry.spec.ts | 20 ++++++++++++------- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla index ba330444a38..f4c5ce7b4bf 100644 --- a/docs/architecture/tla/TerminalReuse.tla +++ b/docs/architecture/tla/TerminalReuse.tla @@ -73,7 +73,11 @@ sweep keeps only a non-expired execution, cfg NoBoundedRelease (Lifecycle Resource Cleanup pre-merge check, review 6200865221). Gap: the pending-call rule for the timeout test - (discussion_r4809359735) is a test rule, not model behavior. *) + (discussion_r4809359735) is a test rule, not model behavior. + Review ratchet (PR #2862, CodeRabbit round 4): 0 covered, 0 added, + 1 gap. Gap: the exact-deferral-boundary test rule (1 ms before and + after expiry, discussion_r4816998303) is a test rule, not model + behavior. *) EXTENDS Naturals, FiniteSets diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index cfb05f51ec1..d3b97fbfbfc 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -900,26 +900,32 @@ describe("TerminalRegistry", () => { vi.useFakeTimers() try { vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + // A known timeout pins the deferral boundary: the stall is + // recorded when the stream-start timeout fires (t=1000), the + // deferral lasts exactly one more timeout (expiry t=2000). + vi.spyOn(Terminal, "getShellIntegrationTimeout").mockReturnValue(1_000) const vsce = makeVsceTerminal() vsce.shellIntegration = stalledIntegration() const terminal = new Terminal(100, vsce as unknown as vscode.Terminal, "/test/path") TerminalRegistry["terminals"].push(terminal) terminal.taskId = "task" const run = terminal.runCommand("echo hi", makeCallbacks()) - await vi.advanceTimersByTimeAsync(Terminal.getShellIntegrationTimeout() + 100) + await vi.advanceTimersByTimeAsync(1_000 + 100) await run // VS Code never fires onDidEndTerminalShellExecution here. expect(terminal.activeShellExecution).toBeDefined() - // Within the deferral the execution still protects the terminal. - const during = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") - expect(during).not.toBe(terminal) + // One millisecond before the deferral expires the execution + // still protects the terminal. + await vi.advanceTimersByTimeAsync(999 - 100) + const before = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + expect(before).not.toBe(terminal) expect(terminal.terminal.dispose).not.toHaveBeenCalled() expect(TerminalRegistry["terminals"]).toContain(terminal) - // Past the deferral the execution no longer protects the terminal: - // the next selection recycles it like any other dead terminal. - await vi.advanceTimersByTimeAsync(60_000) + // One millisecond later the deferral has expired: the next + // selection recycles it like any other dead terminal. + await vi.advanceTimersByTimeAsync(1) const after = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") expect(after).not.toBe(terminal) From ba4ab5e702fd84283bf1ca0206e6c15cf0aa5479 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 15:35:22 +0100 Subject: [PATCH 6/6] fix(terminal): start the stall deferral on every submitted stream timeout (CR round 5) The round-3 deferral was gated on confirmedBefore, so a cold first command whose stream start timed out never recorded the stall. Its orphaned activeShellExecution pinned the terminal forever once the shell later died (Lifecycle Resource Cleanup). runCommand now records stalledExecutionAt for every no_shell_integration that submitted the command (non-cmd.exe); the shellIntegrationLost mark stays gated on confirmation, so the cold retry path is unchanged. Tests: cold-orphan regression test (RED-verified with the confirmation gate restored), and the unread live-process output deferral test with the process-disjunct sabotage check (Regression Evidence). TLA: DeferralElapses applies to every open idle execution (stall-free) and Pick restarts the deferral clock on reuse; StalledNotPinnedForever scoped to dead terminals (the sweep only recycles those). Base cfg passes 2,025 states; NoBoundedRelease fails at 239; all sabotages fail their named invariants, reproduced twice. Ratchet: 1 added, 1 gap. --- docs/architecture/tla/TerminalReuse.tla | 66 +++++++++++-------- src/integrations/terminal/Terminal.ts | 10 ++- .../__tests__/TerminalRegistry.spec.ts | 66 +++++++++++++++++++ 3 files changed, 114 insertions(+), 28 deletions(-) diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla index f4c5ce7b4bf..366dbc161ca 100644 --- a/docs/architecture/tla/TerminalReuse.tla +++ b/docs/architecture/tla/TerminalReuse.tla @@ -38,16 +38,17 @@ fails StalledNotPinnedForever. Run each cfg on TerminalReuseMC.tla. The MC module holds the sabotage operators. - Result: the base cfg passes in 1,369 distinct states (under 10 s; - 1,089 before the round-3 expired field). NoRecycleSweep fails - NoDeadIdleAtSelection in 108 states. NoStallSweep fails - NoDeadIdleAtSelection in 216 states. NoDeadGate fails - NoDeadSelection in 113 states. NoBusyGuard fails BusyTerminalKept - in 50 states. NoUnreadGuard fails UnreadOutputKept in 113 states. - NoExecutionGuard fails RunningExecutionKept in 114 states. + Result: the base cfg passes in 2,025 distinct states (under 10 s; + 1,089 before the round-3 expired field, 1,369 after it). NoRecycleSweep + fails NoDeadIdleAtSelection in 112 states. NoStallSweep fails + NoDeadIdleAtSelection in 234 states. NoDeadGate fails + NoDeadSelection in 117 states. NoBusyGuard fails BusyTerminalKept + in 50 states. NoUnreadGuard fails UnreadOutputKept in 117 states. + NoExecutionGuard fails RunningExecutionKept in 118 states. NoConfirmationGate fails MarkedOnlyIfConfirmed in 21 states. - NoBoundedRelease fails StalledNotPinnedForever in 374 states. Counts - reproduced twice. + NoBoundedRelease fails StalledNotPinnedForever in 239 states. Counts + reproduced twice (round-5 numbers; the round-3 cfg family measured + 108/216/113/50/113/114/21/374 on the pre-round-5 model). Review ratchet (PR #2862, CodeRabbit round 1): 2 covered, 2 added, 3 gap. Added: overlapping commands, ShellDies during a command, the selection gate, BusyTerminalKept, NoDeadSelection as a selection-time property @@ -77,7 +78,16 @@ Review ratchet (PR #2862, CodeRabbit round 4): 0 covered, 0 added, 1 gap. Gap: the exact-deferral-boundary test rule (1 ms before and after expiry, discussion_r4816998303) is a test rule, not model - behavior. *) + behavior. + Review ratchet (PR #2862, CodeRabbit round 5): 1 added, 1 gap. + Added: DeferralElapses expires every open execution, not only a + confirmed terminal's (the cold retry path leaves an orphaned + execution that pins a later-dead terminal), and Pick restarts the + deferral clock on reuse (Lifecycle Resource Cleanup, review + 6211060141). Gap: a time-free safety invariant cannot tell a cold + orphan from a running execution before the deferral fires, so the + polarity for the cold path is the sabotage-verified unit test + (Regression Evidence, review 6211060141). *) EXTENDS Naturals, FiniteSets @@ -91,8 +101,8 @@ VARIABLE registry \* set of entries, one per registered VS Code terminal confirmedBefore). stalled marks a terminal whose command observed a failure the report does not show. unread marks output of a completed command that no consumer read yet. exec marks a submitted execution that - can still run (Terminal.activeShellExecution is set). expired marks a - stalled execution whose bounded deferral passed without an end event. + can still run (Terminal.activeShellExecution is set). expired marks an + execution whose bounded deferral passed without an end event. busy mirrors RooTerminal.busy. A closed terminal leaves the registry (onDidCloseTerminal removes it). *) Entry(id) == @@ -117,8 +127,9 @@ Sweep(reg) == {e \in reg : ~IsDead(e) \/ e.busy \/ e.unread \/ (e.exec /\ ~e.exp MarkDead(e) == [e EXCEPT !.stalled = TRUE] (* The command starts on the terminal. confirmed captures whether the - terminal was proven before this command. *) -Pick(e) == [e EXCEPT !.busy = TRUE, !.confirmed = e.seen] + terminal was proven before this command. The deferral clock restarts: + the new command's stall is measured on its own. *) +Pick(e) == [e EXCEPT !.busy = TRUE, !.confirmed = e.seen, !.expired = FALSE] Init == registry = {} @@ -156,15 +167,17 @@ ExecEnd == /\ e.exec /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.exec = FALSE]} -(* The bounded deferral for a stalled execution expires (PR #2862 round 3, - Lifecycle Resource Cleanup): the stream start timed out, VS Code never - reported the execution's end, and one more shell-integration timeout - passed. The next sweep disposes the terminal. Only a stalled execution - expires; a running one never does. *) +(* The bounded deferral for a submitted execution expires (PR #2862 + rounds 3 and 5, Lifecycle Resource Cleanup): the stream start timed + out, VS Code never reported the execution's end, and one more + shell-integration timeout passed. The next sweep disposes the + terminal. Every stream-start timeout expires, on a cold terminal too; + a running execution never does. The deferral is consulted only for an + idle terminal (the sweep checks busy first). *) DeferralElapses == \E e \in registry : /\ e.exec - /\ e.stalled + /\ ~e.busy /\ ~e.expired /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.expired = TRUE]} @@ -259,13 +272,14 @@ UnreadOutputKept == RunningExecutionKept == [][ Selection => \A e \in registry : (e.exec /\ ~e.expired) => \E f \in registry' : f.id = e.id /\ f.exec /\ ~f.expired ]_registry -(* After a selection, no abandoned stalled execution pins its terminal in - the registry: the sweep disposed it. VS Code staying silent about the - execution's end pins nothing forever. Unread output still holds the - terminal for its reader (UnreadOutputKept); the next sweep after - ReadOutput disposes it. *) +(* After a selection, no abandoned execution pins a DEAD terminal in the + registry: the sweep disposed it. VS Code staying silent about the + execution's end pins nothing forever. An alive cold terminal whose + deferral expired stays on the retry path (MarkedOnlyIfConfirmed), and + unread output still holds the terminal for its reader + (UnreadOutputKept); the next sweep after ReadOutput disposes it. *) StalledNotPinnedForever == - [][ Selection => ~\E e \in registry' : e.exec /\ e.expired /\ ~e.unread ]_registry + [][ Selection => ~\E e \in registry' : IsDead(e) /\ e.exec /\ e.expired /\ ~e.unread ]_registry (* A failure marks only a terminal that was confirmed before its command. *) MarkedOnlyIfConfirmed == \A e \in registry : e.stalled => e.confirmed diff --git a/src/integrations/terminal/Terminal.ts b/src/integrations/terminal/Terminal.ts index 076d6ef8843..de5bf1a3726 100644 --- a/src/integrations/terminal/Terminal.ts +++ b/src/integrations/terminal/Terminal.ts @@ -160,8 +160,14 @@ export class Terminal extends BaseTerminal { // not replayed. if (confirmedBefore && !integrationImpossible) { this.shellIntegrationLost = true - // The submitted execution was never confirmed: start the - // bounded recycle deferral for it (#704). + } + + // Every submitted stream start that never confirmed starts the + // bounded recycle deferral — on a cold terminal too: its orphaned + // execution object must not pin the terminal once the shell later + // dies (PR #2862 round 5, Lifecycle Resource Cleanup). The loss + // mark stays gated on confirmation (the cold retry path). + if (details.commandSubmitted && !integrationImpossible) { this.stalledExecutionAt = Date.now() } diff --git a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts index d3b97fbfbfc..7ac21144cd4 100644 --- a/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts +++ b/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts @@ -973,6 +973,72 @@ describe("TerminalRegistry", () => { } }) + it("keeps a dead terminal holding unread live-process output until a consumer reads it", async () => { + const terminal = TerminalRegistry.createTerminal("/test/path", "vscode") as Terminal + terminal["shellIntegrationSeen"] = true + dropIntegrationReport(terminal) + // Unread output on the live process double, no completed entry: + // the process disjunct of hasUnreadOutput. + const hasOutput = vi.fn(() => true) + terminal.process = { + command: "tail -f log", + getUnretrievedOutput: vi.fn(() => "tail output"), + hasUnretrievedOutput: hasOutput, + trimRetrievedOutput: vi.fn(), + } as unknown as TerminalProcess + + const second = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + // The reader has not come: the terminal is deferred, not selected. + expect(second).not.toBe(terminal) + expect(terminal.terminal.dispose).not.toHaveBeenCalled() + expect(TerminalRegistry["terminals"]).toContain(terminal) + + // The consumer reads the output: the next selection recycles it. + hasOutput.mockReturnValue(false) + await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(terminal.terminal.dispose).toHaveBeenCalledTimes(1) + expect(TerminalRegistry["terminals"]).not.toContain(terminal) + }) + + it("recycles a cold terminal whose orphaned execution outlives the deferral", async () => { + vi.useFakeTimers() + try { + vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(false) + vi.spyOn(Terminal, "getShellIntegrationTimeout").mockReturnValue(1_000) + const vsce = makeVsceTerminal() + const terminal = new Terminal(101, vsce as unknown as vscode.Terminal, "/test/path") + TerminalRegistry["terminals"].push(terminal) + // The integration activates before the command but the terminal + // is cold: it was constructed without a report, so the wait + // passes INSIDE this command and confirmedBefore stays false. + setIntegrationReport(terminal, stalledIntegration()) + terminal.taskId = "task" + // Cold first command: the wait passes inside this call, the + // stream start times out, VS Code never fires the end event. + const run = terminal.runCommand("echo hi", makeCallbacks()) + await vi.advanceTimersByTimeAsync(1_000 + 100) + await run + expect(terminal.activeShellExecution).toBeDefined() + expect(terminal.hasLostShellIntegration()).toBe(false) + + // The shell dies afterwards: the integration report drops. + setIntegrationReport(terminal, undefined) + + // One shell-integration timeout after the stall the orphaned + // execution no longer protects the dead terminal. + await vi.advanceTimersByTimeAsync(1_000) + const after = await TerminalRegistry.getOrCreateTerminal("/test/path", "task", "vscode") + + expect(after).not.toBe(terminal) + expect(terminal.terminal.dispose).toHaveBeenCalledTimes(1) + expect(TerminalRegistry["terminals"]).not.toContain(terminal) + } finally { + vi.useRealTimers() + } + }) + it("never marks a cmd.exe terminal: the shortcut's failure is a platform property", async () => { vi.spyOn(Terminal, "isActiveShellCmdExe").mockReturnValue(true) const vsce = makeVsceTerminal()