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.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.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.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.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.NoRecycleSweep.cfg b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg new file mode 100644 index 00000000000..8daf718c563 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoRecycleSweep.cfg @@ -0,0 +1,10 @@ +\* Sabotage check. The recycle sweep is removed from the selection path. +\* 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 +PROPERTY NoDeadIdleAtSelection diff --git a/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg new file mode 100644 index 00000000000..4e8bcef710f --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.NoStallSweep.cfg @@ -0,0 +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. NoDeadIdleAtSelection must fail: the stalled idle terminal +\* stays in the registry after a selection. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Sweep <- SweepReportedOnly +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 new file mode 100644 index 00000000000..70049ddea07 --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK MarkedOnlyIfConfirmed +PROPERTY NoDeadSelection NoDeadIdleAtSelection BusyTerminalKept UnreadOutputKept RunningExecutionKept StalledNotPinnedForever diff --git a/docs/architecture/tla/TerminalReuse.tla b/docs/architecture/tla/TerminalReuse.tla new file mode 100644 index 00000000000..366dbc161ca --- /dev/null +++ b/docs/architecture/tla/TerminalReuse.tla @@ -0,0 +1,287 @@ +---- 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), 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. + 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 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. + 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). + Expected before the run: the base cfg passes. NoRecycleSweep and + NoStallSweep fail NoDeadIdleAtSelection. NoDeadGate fails + NoDeadSelection. NoBusyGuard fails BusyTerminalKept. NoUnreadGuard + fails UnreadOutputKept. NoExecutionGuard fails RunningExecutionKept. + 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 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 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 + (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. + 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. + 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. + 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. + 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 + +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. 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). 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) == + [id |-> id, integ |-> "off", seen |-> FALSE, confirmed |-> FALSE, busy |-> FALSE, stalled |-> FALSE, unread |-> FALSE, + exec |-> FALSE, expired |-> 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, unread output, or a running execution) + is not selected. *) +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 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). *) +MarkDead(e) == [e EXCEPT !.stalled = TRUE] + +(* The command starts on the terminal. confirmed captures whether the + 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 = {} + +(* 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 {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 {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]} + +(* 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]} + +(* 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]} + +(* 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.busy + /\ ~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. *) +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]} + +(* 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.seen + /\ ~e.stalled + /\ e.integ = "on" + /\ registry' = {f \in registry : f.id /= e.id} \cup {[e EXCEPT !.integ = "off"]} + +(* 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" + /\ \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 \/ ExecEnd \/ Activate \/ ShellDies \/ FailIntegration \/ CloseTerminal \/ DeferralElapses + +Spec == Init /\ [][Next]_registry + +TypeOK == + /\ \A e \in registry : + /\ 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.expired \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 and confirmed change (a fresh spawn + has another state, so it is not this terminal). *) +NoDeadSelection == + [][ Selection => \A e \in registry : (~e.busy /\ Pick(e) \in registry') => ~IsDead(e) ]_registry + +(* 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 /\ ~e.exec ]_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 + +(* The sweep never removes a terminal whose submitted execution can still + 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.expired) => \E f \in registry' : f.id = e.id /\ f.exec /\ ~f.expired ]_registry + +(* 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' : 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/docs/architecture/tla/TerminalReuseMC.tla b/docs/architecture/tla/TerminalReuseMC.tla new file mode 100644 index 00000000000..0751f26e730 --- /dev/null +++ b/docs/architecture/tla/TerminalReuseMC.tla @@ -0,0 +1,39 @@ +---- 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 \/ e.unread \/ e.exec} + +\* Sabotage: the sweep drops busy terminals with it (no busy guard). +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 \/ 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 + +\* 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/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..de5bf1a3726 100644 --- a/src/integrations/terminal/Terminal.ts +++ b/src/integrations/terminal/Terminal.ts @@ -16,6 +16,17 @@ 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 + + // 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()) @@ -59,6 +70,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,12 +94,53 @@ 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) + } + + /** + * 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. + 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 @@ -94,7 +152,27 @@ 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 + } + + // 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() + } + + callbacks.onNoShellIntegration?.(details, process) + }) const promise = new Promise((resolve, reject) => { // Set up event handlers @@ -104,7 +182,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 @@ -126,6 +204,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 +216,10 @@ 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 (#704): the no_shell_integration handler records the + // loss so the next selection recycles it instead of reusing it. + 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/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 da4b3dd16d0..c2f7d1c011c 100644 --- a/src/integrations/terminal/TerminalRegistry.ts +++ b/src/integrations/terminal/TerminalRegistry.ts @@ -220,6 +220,20 @@ 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. + // 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()) { + this.recycleTerminal(terminal.id) + } + } + const terminals = this.getAllTerminals() const reuseKey = provider === "vscode" ? Terminal.getReuseKey() : provider let terminal: RooTerminal | undefined @@ -228,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 } @@ -245,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 } @@ -359,6 +379,60 @@ 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. 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) + + if (!terminal || terminal.busy) { + 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 && + !terminal.hasExecutionStallOutlivedDeferral() + ) { + 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() + } 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..7ac21144cd4 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,579 @@ 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) + + // 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 + + // 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 + + // 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) + // 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) + 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) + // 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) + expect(terminal.hasLostShellIntegration()).toBe(false) + } finally { + 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) + // 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( + 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) + // 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) + 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. + const hasOutput = pushUnreadOutput(first) + + 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" }), + ) + }) + + 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()) + // 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. + 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("recycles a dead terminal once its stalled execution outlives the bounded deferral", async () => { + 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(1_000 + 100) + await run + // VS Code never fires onDidEndTerminalShellExecution here. + expect(terminal.activeShellExecution).toBeDefined() + + // 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) + + // 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) + 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("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() + // 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) + }) + }) }) 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