Skip to content

fix(terminal): fall back from stale local startup cwd - #7297

Closed
rodboev wants to merge 1 commit into
stablyai:mainfrom
rodboev:pr/stale-terminal-cwd-fallback
Closed

rodboev wants to merge 1 commit into
stablyai:mainfrom
rodboev:pr/stale-terminal-cwd-fallback

Conversation

@rodboev

@rodboev rodboev commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fall back to the selected worktree root when local UI terminal creation receives a stale startup cwd outside that worktree.
  • Keep the terminal cwd guard strict by default for remote, session, runtime, mobile, and API callers, with the fallback available only through an explicit local UI spawn opt-in.

Closes #7239.

Screenshots

No visual change

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused validation run in this session:

  • pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts - passed; covers strict default behavior, stale-path fallback, and nested-path preservation.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts -t "stale local renderer cwd values|renderer cwd values without the fallback flag|connectionId is present|sessionId is present" - passed; covers local fallback and strict no-flag, connection-backed, or session-reattach rejection.
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts -t "cwdFallback|explicitly local worktrees while a runtime is focused|owner runtime when focus differs" - passed; covers local-only transport routing and remote omission.
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts -t "startup cwd fallback|SSH-tagged|session reattach" - passed; covers preload spawn payload routing for local IPC versus SSH-tagged and session-reattach inputs.
  • pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts src/main/ipc/pty.test.ts -t "fallback|stale renderer cwd values|stale local UI cwd|raw worktree root|resolved folder workspace root|sessionId is present" - passed; covers the combined shared-helper and main-IPC fallback compatibility row.
  • pnpm run typecheck:node - passed; covers main, preload, and shared type plumbing.
  • pnpm run typecheck:web - passed; covers renderer and preload type plumbing.
  • Broader command run during validation: pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal-startup-cwd.test.ts src/main/ipc/pty.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts - failed in pre-existing src/main/ipc/pty.test.ts attribution-path assertions; the new cwd fallback tests passed.

AI Review Report

Reviewed against the implemented diff after two review passes and fixed a CodeRabbit finding about session reattach spawns. The change keeps the containment guard strict by default, scopes the fallback to new local IPC terminal creation, preserves SSH, session reattach, and remote-runtime rejection, and keeps the shared helper as the single owner of cwd policy. Cross-platform path normalization, macOS/Linux/Windows behavior, local versus remote routing, SSH-tagged payloads, IPC shape, performance, and UI quality were covered by source review and focused tests.

Security Audit

The change keeps the terminal cwd containment guard strict by default and never permits a shell outside the selected worktree. The only new fallback rewrites a stale local UI cwd to the already selected worktree root, and remote/session/API callers must remain unable to opt into it implicitly.

Notes

No UI or Electron rendering changes. The fallback is local-only, explicit, and opt-in through the renderer-to-main spawn payload. If PR #7184 lands first, rebase the helper changes so the deleted in-worktree directory fallback and this outside-worktree stale cwd fallback share the same terminal startup cwd authority without widening strict callers.

@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds an optional cwdFallback: 'worktree' path for terminal PTY spawn handling. Shared cwd resolution can now fall back to the worktree root for outside-worktree requests when configured. The main IPC pty:spawn path applies that fallback only for local, non-session, non-SSH spawns. Preload and renderer PTY types and wiring propagate the new option, and tests cover fallback, rejection, and omission cases.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes implement #7239’s local-only worktree-root fallback while keeping remote, session, runtime, mobile, and API callers strict.
Out of Scope Changes check ✅ Passed The diff stays focused on terminal cwd fallback plumbing and tests, with no obvious unrelated or out-of-scope additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly reflects the main change: adding a local startup cwd fallback for stale terminal creation.
Description check ✅ Passed The description includes all required sections and gives concrete testing, review, security, and notes details.

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

🧹 Nitpick comments (4)
src/shared/terminal-startup-cwd.ts (1)

5-25: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Export OutsideWorktreeCwdPolicy to avoid literal-union duplication.

src/main/ipc/pty.ts re-declares 'throw' | 'fallback-to-worktree' inline instead of importing this type, so any future change to the policy's members must be updated in two places.

♻️ Proposed fix
-type OutsideWorktreeCwdPolicy = 'throw' | 'fallback-to-worktree'
+export type OutsideWorktreeCwdPolicy = 'throw' | 'fallback-to-worktree'
src/main/ipc/pty.ts (1)

2540-2540: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a short "Why" comment for the SSH-exclusion gate.

Every sibling field in this args block (tabId/leafId, telemetry) carries a "Why:" comment, but cwdFallback and the !args.connectionId gate that keeps this fallback local-only don't. This is exactly the kind of non-obvious, security-relevant constraint (never let fallback apply to SSH/remote spawns) that's worth a one-line note so a future edit doesn't accidentally drop the !args.connectionId check.

📝 Proposed comment
+        // Why: opt-in for the local-UI new-terminal flow (see `#7239`) so a
+        // stale inherited/remembered cwd falls back to the worktree root
+        // instead of hard-failing. Never honored for SSH — see the
+        // `!args.connectionId` gate below.
         cwdFallback?: 'worktree'
       const cwd = resolveGuardedPtySpawnCwd(
         args.worktreeId,
         args.cwd,
+        // Why: fallback-to-worktree is a local-only convenience; SSH/remote
+        // spawns must keep the strict containment guard.
         !args.connectionId && args.cwdFallback === 'worktree' ? 'fallback-to-worktree' : undefined
       )

As per coding guidelines: "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Also applies to: 2568-2572

Source: Coding guidelines

src/renderer/src/components/terminal-pane/pty-connection.ts (1)

2561-2562: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add rationale comment and dedupe the repeated local/non-remote-runtime check.

The !connectionId && runtimeEnvironmentId === null condition (or its reordered form) now appears three times (projectRuntime, shouldSettleStartupGridBeforeConnect, and the new cwdFallback line). Extracting it to a single named constant would prevent the checks from silently diverging, and a short comment on the cwdFallback line would document why the fallback is scoped to local, non-remote-runtime panes only (per issue #7239).

♻️ Suggested consolidation
+  // Why: cwdFallback (and projectRuntime/grid-settle gating) must stay local-only —
+  // remote-runtime, SSH, and other non-local callers keep the strict cwd guard.
+  const isLocalNonRuntimeSpawn = !connectionId && runtimeEnvironmentId === null
   const projectRuntime =
-    !connectionId && runtimeEnvironmentId === null
+    isLocalNonRuntimeSpawn
       ? getLocalProjectExecutionRuntimeContext(state, deps.worktreeId, undefined, {
           wslAvailable: localWindowsTerminalCapabilities?.wslAvailable,
           availableWslDistros: localWindowsTerminalCapabilities?.wslDistros ?? null
         })
       : undefined
...
   const transportOptions = {
     cwd: deps.cwd,
-    ...(runtimeEnvironmentId === null && !connectionId ? { cwdFallback: 'worktree' as const } : {}),
+    ...(isLocalNonRuntimeSpawn ? { cwdFallback: 'worktree' as const } : {}),
...
   const shouldSettleStartupGridBeforeConnect = (): boolean =>
     Boolean(paneStartup?.command) &&
     deps.isVisibleRef.current &&
-    !connectionId &&
-    runtimeEnvironmentId === null
+    isLocalNonRuntimeSpawn

Also applies to: 2604-2604, 3057-3058

Source: Coding guidelines

src/renderer/src/components/terminal-pane/pty-transport.ts (1)

460-460: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a short rationale comment for the SSH exclusion.

shouldSendLocalCwdFallback and its spread into the spawn payload implement a security/scope-relevant containment rule (fallback must stay local-only), but there's no inline comment explaining why connectionId disables it.

📝 Suggested comment
+  // Why: cwdFallback must stay local-only — SSH-backed sessions keep the
+  // strict containment guard, so never forward the flag when connectionId is set.
   const shouldSendLocalCwdFallback = cwdFallback === 'worktree' && !connectionId

Also applies to: 609-609

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5b387618-fe3c-4bdb-813b-0ab5adf9cbc7

📥 Commits

Reviewing files that changed from the base of the PR and between 0d2d44b and 74c8c5ab65980ec73fda510621f3bc012b00fb98.

📒 Files selected for processing (11)
  • 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

@nwparker

nwparker commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Thanks @rodboev for digging into this and for the local-only opt-in shape — that design carried through to the final fix. Closing because the landscape changed under this PR: #7750 removed the startup-cwd containment guard entirely (out-of-worktree cwds now spawn as requested, shipped in v1.4.128), so the outside-worktree fallback this PR implements no longer has a guard to fall back from. The residual #7239 failure — a saved startup cwd whose directory was deleted — was just fixed in #7847 using the same fresh-local-only opt-in approach you proposed here (renderer flag + strict reattach/SSH/remote semantics), retargeted to a missing-directory probe.

@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

3 participants