Repository navigation
fix: root monorepo subfolder imports at the git repo while keeping the first terminal in the subfolder (#6336) - #6574
Conversation
…e first terminal in the subfolder Add Project -> Browse folder on a monorepo subfolder (e.g. /tmp/monorepo/packages/web) stored the subfolder as Repo.path because isGitRepo() uses `git rev-parse --is-inside-work-tree`, which is true for any subdirectory. Authoritative worktree resolution then snapped activation back to the repo root, so the import identity mismatched and the first terminal landed at the repo root rather than the selected subfolder. Canonicalize local git imports to the actual repo root via a new getGitRepoRoot() (mirroring the SSH import path that already snaps to check.rootPath, including its post-resolution dedup), and preserve the user-selected subfolder as a one-shot initial terminal cwd consumed only by the first activation-created pane. Selecting the repo root applies no override, and re-importing a subfolder of an existing project dedupes. Fixes #6336 Co-authored-by: Rod Boev <[email protected]>
📝 WalkthroughWalkthroughThis PR adds end-to-end support for opening the terminal at the user-selected folder path when adding a project. On the main process, a new 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
EvidenceUnit tests (vitest) — 333 passedKey regression coverage:
Type + lint gatesLive Electron repro (dev build, CDP)Launched this branch's dev build and exercised the real 1. Subfolder import canonicalizes to the repo root The selected subfolder resolved to the canonical git repo root ( 2. Re-importing the subfolder dedupes (no duplicate) 3. Selecting the repo root itself dedupes to the same repo 4. One-shot initial-cwd store mechanism (drives the first-terminal cwd) Screenshot — project rooted at the git repo root after subfolder import Captured screenshot
|
# Conflicts: # src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts # src/renderer/src/lib/worktree-activation.ts
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/main/ipc/repos.ts (1)
197-208: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a short “why” comment for the second dedupe pass.
This extra lookup against
resolvedPathKeyis carrying the PR’s repo-root canonicalization rule, but next to the firstpathKeylookup it reads like redundant work. A one-line comment here would make that constraint much easier to preserve.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."
Suggested comment
const resolvedPathKey = normalizeRuntimePathForComparison(resolvedPath) if (resolvedPathKey !== pathKey) { + // Why: collapse subfolder imports onto an existing repo-root entry. const existingAfterRootResolve = store .getRepos() .find(Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 895da7f0-38e5-4e9d-bd18-c1c7f21f2cd5
📒 Files selected for processing (23)
src/main/git/repo-detection.test.tssrc/main/git/repo.tssrc/main/ipc/repos-remote.test.tssrc/main/ipc/repos.tssrc/renderer/src/components/native-chat/NativeChatInteractiveCard.tsxsrc/renderer/src/components/native-chat/native-chat-assembler-merge-parity.test.tssrc/renderer/src/components/native-chat/native-chat-incremental-assembler.test.tssrc/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsxsrc/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsxsrc/renderer/src/components/sidebar/project-added-default-checkout.test.tssrc/renderer/src/components/sidebar/project-added-default-checkout.tssrc/renderer/src/components/terminal-pane/terminal-link-handlers.test.tssrc/renderer/src/components/terminal-pane/terminal-link-handlers.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/lib/worktree-activation.test.tssrc/renderer/src/lib/worktree-activation.tssrc/renderer/src/runtime/web-session-tabs-sync.test.tssrc/renderer/src/runtime/web-session-tabs-sync.tssrc/renderer/src/store/slices/store-cascades.test.tssrc/renderer/src/store/slices/tabs.tssrc/renderer/src/store/slices/terminal-orphan-helpers.tssrc/renderer/src/store/slices/terminals.ts
| function resolveInitialCwdForDefaultCheckout( | ||
| defaultCheckout: Worktree, | ||
| selectedPath: string | undefined | ||
| ): string | undefined { | ||
| if (!selectedPath) { | ||
| return undefined | ||
| } | ||
| const relativePath = relativePathInsideRoot(defaultCheckout.path, selectedPath) | ||
| return relativePath && relativePath.length > 0 ? selectedPath : undefined |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Raw selectedPath can miss the canonical worktree root.
Local imports now canonicalize the repo to its real git toplevel, but this helper still checks lexical containment against the original picker path. If a user imports /tmp/monorepo/packages/web and the repo/worktree path is stored as /private/tmp/monorepo, relativePathInsideRoot() returns null, initialCwd is skipped, and the first terminal falls back to the repo root instead of the chosen subfolder. Please carry a canonicalized selected path—or a repo-relative suffix computed during import—through this handoff instead of re-validating the raw picker path here.
Also applies to: 152-156
| if (primaryTabId && opts?.initialCwd) { | ||
| useAppStore.getState().queueTabInitialCwd(primaryTabId, opts.initialCwd) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Only queue initialCwd for a newly created initial terminal.
The dedupe path can reach this with an already-imported worktree, so primaryTabId may belong to an already-mounted tab. In that case this one-shot queue does nothing for the current pane and can be consumed by a later remount instead, reopening the tab in an old subfolder. Gate queueTabInitialCwd on “tab created here” (or equivalent), not just any truthy primaryTabId.
| telemetry?: AgentStartedTelemetry | ||
| } | ||
| > | ||
| pendingInitialCwdByTabId: Record<string, string> |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Clear pendingInitialCwdByTabId in worktree shutdown paths too.
This new one-shot queue is cleaned on closeTab and orphan teardown, but shutdownWorktreeTerminals() still preserves it while clearing the sibling launch queues. If a worktree is slept or removed before its first pane mounts, a stale cwd can survive and seed a later wake/reopen with the wrong subfolder.
Also applies to: 504-505, 575-575, 2432-2452
…e first terminal in the subfolder (stablyai#6336) (stablyai#6574) Add Project → Browse folder on a monorepo subfolder (e.g. /tmp/monorepo/packages/web) stored the subfolder as Repo.path because isGitRepo() uses `git rev-parse --is-inside-work-tree`, which is true for any subdirectory. Authoritative worktree resolution then snapped activation back to the repo root, so the import identity mismatched and the first terminal landed at the repo root rather than the selected subfolder. Canonicalize local git imports to the actual repo root via getGitRepoRoot() (mirroring the SSH import path that snaps to check.rootPath, including its post-resolution dedup), and preserve the user-selected subfolder as a one-shot initial terminal cwd consumed only by the first activation-created pane. Selecting the repo root applies no override, and re-importing a subfolder of an existing project dedupes. Supersedes community PR stablyai#6362. Fixes stablyai#6336 Co-authored-by: Rod Boev <[email protected]>
🧑🤝🧑 Impact & ELI5
1) What's broken today (ELI5). If you use "Add Project → Browse folder" and pick a folder inside a git repository — for example one package inside a monorepo like
/tmp/monorepo/packages/web— Orca ignores the folder you actually chose. Both the file/source-control panel and the first terminal silently jump up to the top of the repo (/tmp/monorepo) instead of staying inpackages/web. The project even shows up under the wrong name (the repo's name, not the subfolder's). It's not a crash, but it's a confusing "I clicked X and got Y" surprise that hits anyone working in a monorepo or any nested project layout — a common setup. Notably, doing the same thing through the macOS Finder "New Orca Workspace Here" menu already worked correctly, so the two ways of opening the same folder behaved differently.2) What this PR does (ELI5). Two fixes working together. First, when you import a folder that lives inside a git repo, Orca now honestly records the project at the real top of the repo (because git operations only make sense from there) — and if you'd already imported that repo, it just reuses it instead of creating a confusing duplicate. Second, and this is the part that fixes the surprise: it remembers the exact subfolder you picked and opens your first terminal right there. So instead of "I picked
packages/weband landed at the repo root," it's now "I pickedpackages/weband my terminal opens inpackages/web," while the source-control view still tracks the whole repo (which is correct). The subfolder is used once, for that first terminal only; new split panes open at the repo root as before. If you pick the repo root itself, nothing special happens.3) Tradeoffs / regressions — honest answer. No regressions for existing behavior. Nothing is disabled, no flag is turned off, no setting changes, and you don't have to do anything new. A few honest nuances worth naming, none of them a downside for users:
rev-parse --show-toplevel) to find the repo root. This is negligible and only happens at import time, not during normal use.Summary
Fixes #6336.
Add Project → Browse folder on a monorepo subfolder (e.g.
/tmp/monorepo/packages/web) used to store the subfolder asRepo.path. BecauseisGitRepo()relies ongit rev-parse --is-inside-work-tree— which returnstruefor any subdirectory of a worktree — the subfolder was accepted as the repo path, but authoritative worktree resolution (git worktree list/--show-toplevel) then snapped activation back to the repo root. The result was a mismatched import identity and the first terminal opening at the repo root instead of the selected subfolder.This change:
getGitRepoRoot()insrc/main/git/repo.ts(rev-parse --show-toplevel, normalized withnormalizeRuntimePathSeparators).addLocalRepoFromPathresolves the root before storing, mirroring the existing SSH import path that already snaps tocheck.rootPath, including the same post-resolution dedup so re-importing a subfolder of an existing project returns the existing repo instead of adding a duplicate.selectedPath;openProjectDefaultCheckoutkeeps it only when it is genuinely inside the resolved worktree (relativePathInsideRoot), queues it viaqueueTabInitialCwd, and the terminal-pane lifecycle consumes it exactly once (cleared after the first pane and on orphan cleanup). Selecting the repo root itself applies no override.This supersedes community PR #6362 (original author credited via
Co-authored-by). I took over that PR, re-implemented/verified it against currentmain, and corrected one defect: thegetGitRepoRootworktree-root test asserted against a non-canonicalized tmp path, which fails on macOS where--show-toplevelresolves the/var → /private/varsymlink. The test now derives its expected root from git's own--show-toplevelso it is correct on macOS, Linux, and Windows.Screenshots
Live Electron repro (dev build over CDP) against this branch. The terminal PTY could not spawn in this validation environment because
node_modulesis symlinked from the primary checkout and node-pty's nativespawn-helperwas built for a now-deleted worktree path (DaemonProtocolError: ... spawn-helper ... ENOENT), so the live terminal-cwd half is proven by unit tests + the live store one-shot queue/consume round-trip rather than a rendered prompt.What the screenshot shows: importing the subfolder
/tmp/monorepo/packages/webcreated a project rooted at the git repo root — the source-control panel reports branchmaster/ "No changes on this branch … ahead of master" (git operations resolve against the repo root), and the project appears asmonorepo(the repo-root basename), notweb.Screenshots attached in a PR comment below.
Testing
pnpm lint—oxlintclean on changed files; fulloxlintshows only one pre-existing warning in an untouched file (useGitStatusPolling.ts). Nomax-linesregressions.pnpm typecheck—tsgo -p config/tsconfig.node.jsonandtsgo -p config/tsconfig.tc.web.jsonboth clean.pnpm test— ran the 8 targeted suites:repo-detection.test.ts,repos-remote.test.ts,AddProjectFromFolderDialog.test.tsx,project-added-default-checkout.test.ts,worktree-activation.test.ts,use-terminal-pane-lifecycle.test.ts,terminal-link-handlers.test.ts,store-cascades.test.ts→ 333 passed.pnpm build— not run (full desktop build out of scope for this environment; typecheck for both projects is green).AI Review Report
Reviewed for correctness, edge cases, cross-platform behavior, and elegance.
getGitRepoRootonly runs forkind === 'git'(folder imports keep their literal path). The post-resolution dedup fires only when the resolved key differs from the input key, exactly mirroring the SSH path. The one-shot cwd is consumed by the first pane, then reset to the default tab cwd so later splits land at the repo root; it is also deleted on orphan cleanup and tab teardown.normalizeRuntimePathSeparatorsandrelativePathInsideRoot; no hardcoded separators, nometaKey, no UI/shortcut changes.git rev-parse --show-toplevelreturns forward slashes on Windows, consistent with the normalizer.selectedPathforssh_remote_pathtoo; remote root canonicalization already existed viacheck.rootPath, andrelativePathInsideRootworks on remote-flavored paths.Security Audit
I re-audited the adopted code assuming the original author was hostile.
getGitRepoRootcallsgitExecFileSyncwith fixed argv (['rev-parse', '--is-inside-work-tree'],['rev-parse', '--show-toplevel']);gitExecFileSyncusesexecFileSync(no shell). User input is only thecwd. No injection vector. (On Windows/WSL the runner builds abash -cstring but escapes every token viaquotePosixShell, and these args are hardcoded.)relativePathInsideRootconfirms containment inside the resolved worktree.repos:addis unchanged in shape; it now returns the canonical root path, which is the intended fix.No follow-up required.
Notes
Co-authored-by. Their PR is left open per process.getGitRepoRootcanonicalization could be applied to other local import entry points (e.g. drag-and-drop / recent-folder reopen) if any bypassaddLocalRepoFromPath; worth a follow-up audit.Made with Orca 🐋