Skip to content

fix: recover local terminal spawn from stale cwd - #7678

Closed
nwparker wants to merge 2 commits into
stablyai:mainfrom
nwparker:nwparker/bug-new-terminal-creation-persistently-fails-wit
Closed

nwparker wants to merge 2 commits into
stablyai:mainfrom
nwparker:nwparker/bug-new-terminal-creation-persistently-fails-wit

Conversation

@nwparker

@nwparker nwparker commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Recover fresh local UI terminal creation when a persisted/inherited startupCwd is stale or outside the selected worktree by falling back to that worktree root.
  • Print a generic in-terminal notice when that fallback happens, without exposing the rejected/stale cwd path.
  • Keep the cwd containment guard strict by default: SSH, remote-runtime, session reattach, runtime/API, mobile, and no-flag callers still reject outside cwd values.
  • Add the experimental terminal-session.startup-cwd-containment reliability gate with shared, main IPC, renderer transport, connection-layer, and notice coverage.

Closes #7239.
Refs community PR #7297; I reproduced independently first, then adapted the same local-only fallback idea to the current branch and added issue-shaped non-ASCII path coverage plus the reliability gate.

Repro Evidence

Red before the fix:

  • pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts -t "falls back" failed with Terminal cwd must be inside the selected worktree. for stale outside cwd fallback cases.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts -t "falls back to the worktree root for stale local renderer cwd values" failed with the same error in the actual pty:spawn path.

That reproduces the issue shape: a local renderer-backed new terminal sends worktreeId plus a stale outside cwd; main rejects before provider spawn, which is what produces the persistent terminal error toast.

ELI5

Orca remembered a folder to start the next terminal in. In the bad state, that remembered folder was no longer inside the workspace, so the terminal guard stopped every new terminal from opening. Now, for a normal local "new terminal" click, Orca says: "that remembered folder is stale, so start at the workspace root instead," and it prints a short note in that terminal so the recovery is visible. It still refuses unsafe cwd requests from remote/session/API paths.

Tradeoffs

  • A stale local UI cwd now opens at the worktree root instead of the user's previously intended subfolder. That is less precise, but it restores terminal creation without allowing a shell outside the selected workspace.
  • The fallback is explicit and fresh-local-only. This avoids weakening SSH, remote runtime, mobile/API, and session reattach containment where silently remapping cwd could hide a real caller bug or provider mismatch.
  • The visible notice deliberately does not include the rejected cwd. Full paths can contain private repo/user names, so the terminal message says what happened without printing the stale path.
  • No live Electron fixture seeds the exact production persisted session from [Bug]: New terminal creation persistently fails with "Terminal cwd must be inside the selected worktree." toast #7239 yet; the gate records that as a promotion gap.

Reliability Proof

Reliability invariant: terminal-session.startup-cwd-containment for #7239. A fresh local renderer terminal spawn may recover from a stale outside cwd only by spawning in the selected worktree root and printing a generic in-terminal notice; remote, SSH, reattach, runtime, mobile, and API callers must not silently weaken cwd containment.

Material impact: This turns the persistent "new terminal never opens" failure into a recoverable local UI spawn while preserving the safety guard that prevents shells from starting outside the selected worktree. The recovery is no longer silent because the affected terminal shows a scoped note.

Product change type: mixed runtime hardening + reliability gate/test coverage.

Performance risk inventory: touches terminal creation, pty:spawn preflight, startup cwd resolution, renderer transport option routing, and one terminal foreground write after a successful fallback. It does not touch typing, output delivery, focus loops, resize, render scheduling, provider listing, hidden-pane wakeups, git/worktree scans, or subprocess creation.

No-regression evidence: The runtime path adds constant-time option checks, uses the existing single cwd resolver during spawn, and performs one bounded terminal write only when fallback actually occurs. No polling, fanout, provider list, renderer loop, startup await, or subprocess work was added.

Correctness evidence:

  • pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts passed: 19 tests.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts passed: 221 tests.
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts passed: 57 tests.
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts passed: 335 tests.
  • pnpm run typecheck passed.
  • pnpm run check:reliability-gates passed.
  • pnpm run check:max-lines-ratchet passed.
  • pnpm exec oxlint <changed TS files> passed.
  • git diff --check passed.

Provider/platform coverage: local macOS covered, including a Japanese/non-ASCII worktree-root test matching #7239. SSH strictness is covered via connectionId; remote-runtime omission is covered in the connection tests. Daemon shares the same pre-provider main cwd decision but does not have a live daemon spawn run here. WSL/mobile/API and Linux/Windows live behavior are recorded as gate gaps.

Residual gaps: no live Electron persisted-session fixture for the exact production state; no live daemon-provider run; no direct WSL/mobile/API provider-contract run.

Promotion status: partial experimental gate. It should not be promoted until CI/soak evidence, live Electron reproduction, and the provider/platform gaps above are addressed.

Rollback or demotion rule: demote/quarantine if the gate flakes without a product bug, or if any remote/session/API path can silently fall back instead of rejecting an outside cwd.

Additional Validation Notes

pnpm run lint was attempted and failed in unrelated existing code: src/renderer/src/components/right-sidebar/source-control-manual-review-url.ts:164 is missing the null case for the switch-exhaustiveness lint. I kept that source-control fix out of this terminal PR; targeted oxlint on the changed files passed.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a cwdFallback: 'worktree' path for fresh local PTY spawns when the renderer startup cwd is outside the selected worktree. Shared startup-cwd resolution now supports outsideWorktreeCwd: 'throw' | 'fallback-to-worktree' plus a fallback callback. The main IPC pty:spawn handler forwards the new option and returns startupCwdFallback metadata when used. Renderer PTY transport forwards the option only for local non-SSH, non-reattach spawns and prints a startup fallback notice. Tests cover fallback and rejection cases, and a new reliability gate records the invariant and coverage.

Related PRs: None specified.

Suggested labels: terminal, pty, reliability

Suggested reviewers: None specified.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR implements the requested local-only fallback, preserves strict remote/session containment, and adds non-ASCII/local coverage for #7239.
Out of Scope Changes check ✅ Passed The changes stay focused on cwd containment recovery, terminal notice surfacing, and related tests/gate updates with no unrelated feature work.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely summarizes the main change: recovering local terminal spawns from stale cwd values.
Description check ✅ Passed The description covers summary, repro evidence, tradeoffs, and testing, but omits Screenshots, AI Review Report, Security Audit, and Notes sections.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4034f3d1-4b00-489d-96bd-6c76e066a13b

📥 Commits

Reviewing files that changed from the base of the PR and between eed0058 and b7200ac.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/shared/terminal-startup-cwd.test.ts
  • src/shared/terminal-startup-cwd.ts

Comment on lines +122 to +134
"platforms": [
"macos",
"linux",
"windows"
],
"providers": [
"local",
"daemon",
"ssh",
"wsl",
"remote-runtime",
"mobile"
],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

mobile is categorized as a provider here but as a platform elsewhere.

This gate lists mobile under providers, while the terminal-runtime.mobile-stream-budget gate (lines 2115-2126) lists mobile under platforms with remote-runtime as the provider. Mobile is a client/caller that reaches terminals via the remote-runtime provider, so any tooling that filters gates by provider vs. platform will mis-aggregate this entry. Align with the existing convention.

🔧 Align mobile with the platform/provider convention
       "platforms": [
         "macos",
         "linux",
-        "windows"
+        "windows",
+        "mobile"
       ],
       "providers": [
         "local",
         "daemon",
         "ssh",
         "wsl",
-        "remote-runtime",
-        "mobile"
+        "remote-runtime"
       ],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"platforms": [
"macos",
"linux",
"windows"
],
"providers": [
"local",
"daemon",
"ssh",
"wsl",
"remote-runtime",
"mobile"
],
"platforms": [
"macos",
"linux",
"windows",
"mobile"
],
"providers": [
"local",
"daemon",
"ssh",
"wsl",
"remote-runtime"
],

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c24ce8f2-2164-4dd3-9409-158afcd3c5b3

📥 Commits

Reviewing files that changed from the base of the PR and between b7200ac and e2f62d9.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/shared/terminal-startup-cwd.test.ts
  • src/shared/terminal-startup-cwd.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/shared/terminal-startup-cwd.ts
  • src/main/ipc/pty.ts
  • config/reliability-gates.jsonc
  • src/shared/terminal-startup-cwd.test.ts
  • src/main/ipc/pty.test.ts

Comment on lines +3768 to +3776
if (
spawnedPtyId &&
typeof spawnedPtyId === 'object' &&
spawnedPtyId.startupCwdFallback?.kind === 'worktree'
) {
writeTerminalOutput(pane.terminal, STARTUP_CWD_FALLBACK_NOTICE, {
foreground: true
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Guard the fallback notice write with the visibility check used elsewhere.

Every other one-off foreground write in this file (writeRestoreUnavailableWarning, queueAgentIdleTerminalModeReset) gates foreground: true behind shouldWritePtyOutputForeground(deps.isVisibleRef.current). This new write forces foreground: true unconditionally, even for a hidden/background pane (e.g. a terminal created without focus), bypassing the background throttling path.

💡 Suggested fix
-            if (
-              spawnedPtyId &&
-              typeof spawnedPtyId === 'object' &&
-              spawnedPtyId.startupCwdFallback?.kind === 'worktree'
-            ) {
-              writeTerminalOutput(pane.terminal, STARTUP_CWD_FALLBACK_NOTICE, {
-                foreground: true
-              })
-            }
+            if (
+              spawnedPtyId &&
+              typeof spawnedPtyId === 'object' &&
+              spawnedPtyId.startupCwdFallback?.kind === 'worktree'
+            ) {
+              writeTerminalOutput(pane.terminal, STARTUP_CWD_FALLBACK_NOTICE, {
+                foreground: shouldWritePtyOutputForeground(deps.isVisibleRef.current),
+                beforeWrite: beforeTerminalOutputWrite
+              })
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (
spawnedPtyId &&
typeof spawnedPtyId === 'object' &&
spawnedPtyId.startupCwdFallback?.kind === 'worktree'
) {
writeTerminalOutput(pane.terminal, STARTUP_CWD_FALLBACK_NOTICE, {
foreground: true
})
}
if (
spawnedPtyId &&
typeof spawnedPtyId === 'object' &&
spawnedPtyId.startupCwdFallback?.kind === 'worktree'
) {
writeTerminalOutput(pane.terminal, STARTUP_CWD_FALLBACK_NOTICE, {
foreground: shouldWritePtyOutputForeground(deps.isVisibleRef.current),
beforeWrite: beforeTerminalOutputWrite
})
}

@nwparker

nwparker commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #7847. This PR's head branch got detached on GitHub's side (branch delete/re-create), so it stopped tracking pushes. The fix was also reworked on top of current main: #7750 removed the containment guard this PR was originally built around, so #7847 targets the residual #7239 failure mode — a persisted startup cwd whose directory no longer exists.

@nwparker nwparker closed this Jul 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: New terminal creation persistently fails with "Terminal cwd must be inside the selected worktree." toast

1 participant