Skip to content

[BUG] Shell Integration Error persists after long sessions — dead terminal reuse in getOrCreateTerminal() #704

Open

Description

@myk1yt

A Note from the User

This is a message from me, a human user. I asked AI to handle the rest of the issue report.

I tried to patch the problems I encountered while using Zoo Code myself. The patches may be incomplete or may not work correctly. Please, the bug fix team, judge them directly. I hope Zoo Code continues to grow and mature.


Problem

After long sessions (30+ minutes), execute_command repeatedly returns "Command failed to execute in terminal due to a shell integration error." The failure rate increases dramatically as the session progresses.

Context

  • OS: Windows 11, PowerShell 5.1
  • Zoo Code Version: v3.63.100188
  • API Provider: OpenAI Compatible
  • Model: mimo-v2.5-pro
  • Affected: Multiple projects (ZooChat, Emebala, myownsettings)

Reproduction Steps

  1. Open Zoo Code and execute multiple commands (works normally)
  2. Maintain session for 30+ minutes with repeated command execution
  3. Create multiple terminal instances
  4. Subsequent commands trigger "shell integration error"

Expected Result

Commands should execute successfully.

Actual Result

"Command failed to execute in terminal due to a shell integration error" is returned. Retrying the same command does not help.

Relevant Logs

[PATCH] execa fallback attempted. Original message: Command failed to execute in terminal due to a shell integration error.

Root Cause Analysis

The getOrCreateTerminal() method at byte offset 14,562,575 in extension.js reuses dead terminals:

static async getOrCreateTerminal(e, r, a="vscode") {
  let o = this.getAllTerminals(),
      s = a === "vscode" ? Pn.getReuseKey() : a,
      n;
  return r && (n = o.find(u =>
    u.busy || u.taskId !== r || u.provider !== a || u.reuseKey !== s ? !1 : ...
  ));
  // If busy=false and taskId/reuseKey match, dead terminals are also reused
}

When a terminal loses its internal state (PID gone, shell integration timeout), Zoo Code still reuses it because taskId + reuseKey match.

Minified Alias Mapping (extension.js)

Original Minified Byte Offset
selectTerminalProvider MZs 14,717,666
canRetryShellIntegrationError BZs 14,717,646
ShellIntegrationError JM 14,717,640
executeCommandInTerminal zyi 14,720,177
vscodeTerminal Pn 12,889,514
TerminalRegistry h0 14,560,517

Applied Patch

We applied a community patch that adds a forceNewTerminal option:

Change 1: MZs() — add forceNewTerminal parameter

function MZs(t, e) {
  let r = !t && Pn.isActiveShellCmdExe();
  return { terminalProvider: t || r || e ? "execa" : "vscode", isCmdExeFallback: r }
}

Change 2: zyi() — add forceNewTerminal to destructure

async function zyi(t, {executionId: e, command: r, customCwd: a,
                       terminalShellIntegrationDisabled: o = !0,
                       forceNewTerminal: __fn = !1,
                       commandExecutionTimeout: s = 0, agentTimeout: n = 0}) {

Change 3-6: Pass forceNewTerminal through the call chain

let Y = await h0.getOrCreateTerminal(c, t.taskId, E, __fn);
// In catch/retry branches:
await zyi(r, {...y, terminalShellIntegrationDisabled: !0, forceNewTerminal: !0})

Change 7: Pn constructor — explicit PowerShell shellPath fallback

let explicitShell = process.platform === "win32"
  ? (process.env.SystemRoot || "C:\\Windows") + "\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
  : (process.env.SHELL || "/bin/bash");
n.shellPath = explicitShell;

Patch Verification

Check Result
Node.js --check ✅ PASSED
Size change +365 bytes

Recommended Official Fix

Add terminal validity check in getOrCreateTerminal():

static async getOrCreateTerminal(e, r, a="vscode", forceNew=false) {
  if (forceNew) return this.createTerminal(e, a);
  let o = this.getAllTerminals(),
      s = a === "vscode" ? Pn.getReuseKey() : a, n;
  if (r) {
    n = o.find(u => {
      if (u.busy || u.taskId !== r || u.provider !== a || u.reuseKey !== s) return false;
      if (u.terminal?.exitStatus !== undefined) return false;
      return true;
    });
  }
  return n || this.createTerminal(e, a);
}

Activity

  1. myk1yt commented on Jun 24, 2026

    @myk1yt
    ContributorAuthor

    Likely Resolved via Inline Terminal PowerShell Fix (#705)

    Whether this is a fundamental fix needs to be confirmed by the Zoo Code bug fix team.

    Analysis

    This issue reports that after long sessions (30+ minutes), execute_command repeatedly returns "shell integration error" because getOrCreateTerminal() reuses dead terminals whose internal state (PID, shell integration) has expired.

    The original problem code (extension.js offset ~14,562,575):

    static async getOrCreateTerminal(e, r, a="vscode") {
      let o = this.getAllTerminals(),
          s = a === "vscode" ? Pn.getReuseKey() : a,
          n;
      return r && (n = o.find(u =>
        u.busy || u.taskId !== r || u.provider !== a || u.reuseKey !== s ? !1 : ...
      ));
      // Dead terminals are reused when busy=false and taskId/reuseKey match
    }

    Why Inline Terminal ON resolves this:

    When "Use Inline Terminal (recommended)" is ON, the execa provider is used instead of the VS Code integrated terminal:

    Mode Terminal Reuse Shell Integration #704 Risk
    Inline Terminal OFF Reuses VS Code terminals Depends on shell integration Dead terminal reuse causes errors
    Inline Terminal ON Creates new process per command Bypassed entirely No terminal reuse, no shell integration dependency

    With Inline Terminal ON:

    1. Each command runs as a fresh background process via execa — no terminal reuse at all
    2. Shell integration is completely bypassed — the "shell integration error" cannot occur
    3. Dead terminal accumulation is impossible — there are no persistent terminals to die

    Related Fix

    Issue #705 was resolved by making the Inline Terminal use PowerShell on Windows instead of cmd.exe:

    // Fixed execa shell selection (offset 14,556,931 in extension.js)
    shell: sW.getExecaShellPath() || (process.platform === "win32" ? "powershell.exe" : !0)

    With both Inline Terminal ON and PowerShell working correctly, the conditions that trigger #704 (dead terminal reuse + shell integration dependency) are eliminated.

    Recommendation

    We recommend using Inline Terminal ON with the PowerShell fix from #705. This sidesteps the getOrCreateTerminal() dead-reuse issue entirely. However, if the VS Code terminal mode is still needed, the exitStatus check in getOrCreateTerminal() should be added as described in the original issue.

  2. gh311 commented on Dec 5, 2026

    @gh311
    Contributor

    Reproduced at the logic level and fixed in PR #2862.

    Root cause: TerminalRegistry.getOrCreateTerminal() filtered candidates only through isClosed(), which reads exitStatus !== undefined — a value VS Code sets only when the close event fires. A terminal whose shell died in a long session (integration probe dead/stale) keeps exitStatus === undefined, so it passed every check (busy=false, matching taskId/reuseKey) and was re-selected for every following command; each command replayed the 5 s shell-integration timeout and failed. A unit-level repro on the pre-fix tree selects the identical dead terminal object back: expected Terminal{...} not to be Terminal{...} — Compared values have no visual difference.

    Fix (selection/revalidation scope only): terminals now track whether their integration was ever confirmed; getOrCreateTerminal() revalidates idle candidates before reuse and recycles failures (dispose + remove via TerminalRegistry.recycleTerminal()), so the freed selection spawns a replacement. Cold terminals (never integrated) and busy terminals are never recycled, so slow-starting shells and in-flight commands are unaffected.

    Evidence:

    • TLA+ module docs/architecture/tla/TerminalReuse.tla: TerminalReuse.cfg passes (121 distinct states); sabotage cfgs NoRecycleSweep / NoStallSweep each fail NoDeadSelection (the model-level form of this repro: spawn → activate → die → reuse).
    • 7 new tests in src/integrations/terminal/__tests__/TerminalRegistry.spec.ts; 5 verified RED on the pre-fix tree, then green after the fix; the 2 guard tests sabotage-verified (seen-guard removal → 3 failures; busy-guard removal → busy test fails).
    • Gates (node v22.23.4): test:core 5316 passed, test:api 6417 passed, scoped vitest 26 passed, tsc --noEmit clean, eslint --max-warnings=0 clean, prettier --check clean.

    The fix is designed independently of the forceNewTerminal patch quoted in the issue body: that patch required a caller opt-in per command and its exitStatus check already exists on this tree via isClosed(); the registry now carries its own liveness signal, so recovery needs no per-call flag.

  3. gh311 commented on Dec 5, 2026

    @gh311
    Contributor
  4. coderabbitai commented on Dec 5, 2026

    @coderabbitai
    Contributor
    Analysis chain

    Script executed:

    #!/bin/bash
    set -o pipefail
    echo '=== Issue 704 ==='
    gh issue view 704 --repo Zoo-Code-Org/Zoo-Code --json title,body,state,url 2>&1
    echo '=== Pull request 2862 ==='
    gh pr view 2862 --repo Zoo-Code-Org/Zoo-Code --json title,body,state,url,baseRefName,headRefName,headRefOid,baseRefOid,files 2>&1
    echo '=== Pull request diff ==='
    gh pr diff 2862 --repo Zoo-Code-Org/Zoo-Code --patch 2>&1
    echo '=== Writing guidance ==='
    fd -HI -t f '^(CONTRIBUTING|AGENTS)\.md$' -E node_modules -E .git | head -50

    Length of output: 37592


    Script executed:

    #!/bin/bash
    set -u
    head=7ff5d481b3ce7c4f75ca731bc8c7d71ee1d208e3
    tmp=$(mktemp -d)
    for path in src/integrations/terminal/Terminal.ts src/integrations/terminal/TerminalRegistry.ts src/integrations/terminal/TerminalProcess.ts src/integrations/terminal/BaseTerminal.ts src/integrations/terminal/ExecaTerminal.ts src/integrations/terminal/types.ts src/integrations/terminal/__tests__/TerminalRegistry.spec.ts src/core/tools/ExecuteCommandTool.ts; do
      mkdir -p "$tmp/$(dirname "$path")"
      if ! gh api -H 'Accept: application/vnd.github.raw+json' "repos/Zoo-Code-Org/Zoo-Code/contents/$path?ref=$head" > "$tmp/$path"; then echo "FETCH FAILED $path"; fi
    done
    echo '=== Head file outlines ==='
    for path in src/integrations/terminal/Terminal.ts src/integrations/terminal/TerminalRegistry.ts src/integrations/terminal/TerminalProcess.ts src/integrations/terminal/BaseTerminal.ts src/integrations/terminal/ExecaTerminal.ts src/core/tools/ExecuteCommandTool.ts; do
      echo "--- $path ---"
      ast-grep outline "$tmp/$path" --items all 2>&1
    done
    echo '=== Terminal.ts ==='
    cat -n "$tmp/src/integrations/terminal/Terminal.ts" | sed -n '1,245p'
    echo '=== TerminalRegistry.ts ==='
    cat -n "$tmp/src/integrations/terminal/TerminalRegistry.ts" | sed -n '1,435p'
    echo '=== TerminalProcess.ts ==='
    cat -n "$tmp/src/integrations/terminal/TerminalProcess.ts" | sed -n '1,280p'
    echo '=== Repository guidance ==='
    cat AGENTS.md
    rg -n -C 3 -i 'writing style|writing|review' CONTRIBUTING.md | head -100

    Length of output: 66900


    Script executed:

    #!/bin/bash
    set -u
    head=7ff5d481b3ce7c4f75ca731bc8c7d71ee1d208e3
    tmp=$(mktemp -d)
    for path in src/integrations/terminal/BaseTerminal.ts src/integrations/terminal/TerminalProcess.ts src/integrations/terminal/TerminalRegistry.ts src/core/tools/ExecuteCommandTool.ts src/integrations/terminal/__tests__/TerminalRegistry.spec.ts; do
      mkdir -p "$tmp/$(dirname "$path")"
      gh api -H 'Accept: application/vnd.github.raw+json' "repos/Zoo-Code-Org/Zoo-Code/contents/$path?ref=$head" > "$tmp/$path" || echo "FETCH FAILED $path"
    done
    echo '=== BaseTerminal outline and output state ==='
    ast-grep outline "$tmp/src/integrations/terminal/BaseTerminal.ts" --items all
    cat -n "$tmp/src/integrations/terminal/BaseTerminal.ts" | sed -n '1,230p'
    echo '=== TerminalRegistry removal ==='
    cat -n "$tmp/src/integrations/terminal/TerminalRegistry.ts" | sed -n '420,490p'
    echo '=== Execution error and selection paths ==='
    rg -n -C 5 'onNoShellIntegration|ShellIntegrationError|getOrCreateTerminal|getUnretrievedOutput|commandSubmitted' "$tmp/src/core/tools/ExecuteCommandTool.ts"
    echo '=== Output consumers in repository ==='
    rg -n -C 3 'getBackgroundTerminals\(|getProcessesWithOutput\(|getUnretrievedOutput\(' src/core src/integrations/terminal -g '*.ts' -g '!**/__tests__/**' | head -220
    echo '=== Terminal test setup and relevant tests ==='
    cat -n "$tmp/src/integrations/terminal/__tests__/TerminalRegistry.spec.ts" | sed -n '1,150p;480,640p'
    echo '=== Writing style ==='
    cat -n CONTRIBUTING.md | sed -n '218,255p'

    Length of output: 41583


    @gh311 I found two issues in PR #2862:

    1. A stale integration object can still cause repeated failures. Terminal.ts, Line 167 marks integration as lost only when the initial wait times out. If shellIntegration remains present but the execution stream never starts, TerminalProcess.ts, Line 94 emits no_shell_integration without setting that flag. The registry can then select the same terminal again. Handle this failure signal and add a regression test. Do not automatically retry a command that was submitted.

    2. Recycling can discard unread output. TerminalRegistry.ts, Line 228 sweeps every idle terminal, including terminals from other tasks. Removing one also removes access to its completedProcesses output before getEnvironmentDetails() can read it. Preserve unread output when recycling, and test a terminal with pending output.

    I reviewed the code at commit 7ff5d481. I did not run the tests or reproduce the failure in VS Code.


    Learnings used

    Learnt from: CR
    Repo: Zoo-Code-Org/Zoo-Code PR: 0
    File: coderabbit-custom-pre-merge-checks-unique-id-file-non-traceable-F7F2B60C-1728-4C9A-8889-4F2235E186CA.txt:0-0
    Timestamp: 2026-11-28T02:20:02.382Z
    Learning: Source excerpt:
    Regression evidence: Fail only when changed behavior has a concrete test gap at the lowest valid test layer. Examples include tests that copy the implementation and missing relevant negative, error, or unset cases. Also check for missing required snapshots for visible UI changes. Do not demand tests for unchanged behavior or mechanical configuration changes. Do not demand coverage of a branch without a plausible regression case. Cite the changed behavior and the missing evidence.
    
    Learnt from: CR
    Repo: Zoo-Code-Org/Zoo-Code PR: 0
    File: AGENTS.md:0-0
    Timestamp: 2026-10-20T22:54:54.079Z
    Learning: Source excerpt:
    # AGENTS.md
    
    ## Test Placement Guidance
    
    - When fixing a regression, add the regression test at the lowest layer that would have failed for the bug. Add an e2e test only if lower-level tests cannot represent the failure mode.
    

    You are interacting with an AI system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions