Skip to content

fix: root monorepo subfolder imports at the git repo while keeping the first terminal in the subfolder (#6336) - #6574

Merged
nwparker merged 2 commits into
mainfrom
nwparker/fix-6336
Jun 28, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/fix-6336

Conversation

@nwparker

@nwparker nwparker commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

🧑‍🤝‍🧑 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 in packages/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/web and landed at the repo root," it's now "I picked packages/web and my terminal opens in packages/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:

  • The project's stored path and display name for a subfolder import now change from the subfolder to the repo root. That's the intended correction (the old behavior was the bug), and it matches what already happened in practice — git always snapped to the repo root anyway; now the project name and identity finally agree with that instead of mismatching.
  • Importing a subfolder of an already-imported repo now correctly returns the existing project instead of silently making a duplicate — strictly better.
  • The "open my first terminal in the picked subfolder" behavior is one-shot by design: only the first terminal created during activation lands in the subfolder; later split panes open at the repo root. This is a deliberate scope choice, not a bug, and matches the existing Finder-menu behavior.
  • Each git import now runs one extra quick local git command (rev-parse --show-toplevel) to find the repo root. This is negligible and only happens at import time, not during normal use.
  • The fix is cross-platform (macOS/Linux/Windows) and also covers the SSH/remote import path, so no platform is left behind.

Summary

Fixes #6336.

Add Project → Browse folder on a monorepo subfolder (e.g. /tmp/monorepo/packages/web) used to store the subfolder as Repo.path. Because isGitRepo() relies on git rev-parse --is-inside-work-tree — which returns true for 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:

  1. Canonicalizes local git imports to the real repo root via a new getGitRepoRoot() in src/main/git/repo.ts (rev-parse --show-toplevel, normalized with normalizeRuntimePathSeparators). addLocalRepoFromPath resolves the root before storing, mirroring the existing SSH import path that already snaps to check.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.
  2. Preserves the user-selected subfolder as a one-shot initial terminal cwd for only the first activation-created pane. The dialog now forwards selectedPath; openProjectDefaultCheckout keeps it only when it is genuinely inside the resolved worktree (relativePathInsideRoot), queues it via queueTabInitialCwd, 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 current main, and corrected one defect: the getGitRepoRoot worktree-root test asserted against a non-canonicalized tmp path, which fails on macOS where --show-toplevel resolves the /var → /private/var symlink. The test now derives its expected root from git's own --show-toplevel so 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_modules is symlinked from the primary checkout and node-pty's native spawn-helper was 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/web created a project rooted at the git repo root — the source-control panel reports branch master / "No changes on this branch … ahead of master" (git operations resolve against the repo root), and the project appears as monorepo (the repo-root basename), not web.

Screenshots attached in a PR comment below.

Testing

  • pnpm lint — oxlint clean on changed files; full oxlint shows only one pre-existing warning in an untouched file (useGitStatusPolling.ts). No max-lines regressions.
  • pnpm typecheck — tsgo -p config/tsconfig.node.json and tsgo -p config/tsconfig.tc.web.json both 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).
  • Added/updated tests that catch this regression (worktree-root canonicalization + dedup, root-pick no-override, one-shot cwd queue/consume + orphan cleanup, pane-link cwd).

AI Review Report

Reviewed for correctness, edge cases, cross-platform behavior, and elegance.

  • Correctness: getGitRepoRoot only runs for kind === '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.
  • Cross-platform (macOS / Linux / Windows): path handling goes through the existing Windows-aware helpers normalizeRuntimePathSeparators and relativePathInsideRoot; no hardcoded separators, no metaKey, no UI/shortcut changes. git rev-parse --show-toplevel returns forward slashes on Windows, consistent with the normalizer.
  • SSH / remote: the dialog passes selectedPath for ssh_remote_path too; remote root canonicalization already existed via check.rootPath, and relativePathInsideRoot works on remote-flavored paths.
  • Provider-agnostic: no GitHub-specific assumptions; only git plumbing and renderer state.
  • Flagged & fixed: the adopted test's worktree-root assertion was macOS-symlink-fragile; rewritten to derive the expected root from git.

Security Audit

I re-audited the adopted code assuming the original author was hostile.

  • Command execution: getGitRepoRoot calls gitExecFileSync with fixed argv (['rev-parse', '--is-inside-work-tree'], ['rev-parse', '--show-toplevel']); gitExecFileSync uses execFileSync (no shell). User input is only the cwd. No injection vector. (On Windows/WSL the runner builds a bash -c string but escapes every token via quotePosixShell, and these args are hardcoded.)
  • Path handling: no traversal — the subfolder cwd override only applies when relativePathInsideRoot confirms containment inside the resolved worktree.
  • Secrets / network / eval / deps: none touched. No new dependencies.
  • IPC: repos:add is unchanged in shape; it now returns the canonical root path, which is the intended fix.

No follow-up required.

Notes

  • Supersedes community PR Preserve selected subfolder when Add Project imports a monorepo path #6362; original author credited via Co-authored-by. Their PR is left open per process.
  • Future suggestions (out of scope, not in this diff): the same getGitRepoRoot canonicalization could be applied to other local import entry points (e.g. drag-and-drop / recent-folder reopen) if any bypass addLocalRepoFromPath; worth a follow-up audit.

Made with Orca 🐋

…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]>
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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 getGitRepoRoot function resolves nested git directory paths to their worktree root before repo deduplication and metadata initialization. On the renderer side, a pendingInitialCwdByTabId store map and queueTabInitialCwd/consumeTabInitialCwd actions are added; activateAndRevealWorktree enqueues an initialCwd on the primary terminal tab; the Add Project dialog passes selectedPath through finishProjectAddWithDefaultCheckout and openProjectDefaultCheckout, which resolves it to an initialCwd for activateAndRevealWorktree. The terminal pane lifecycle consumes the queued CWD on first pane mount via new helpers (resolveQueuedInitialCwd, clearQueuedInitialCwdAfterFirstPane, resolvePaneLinkCwd, resolvePaneSeedCwd) and exposes per-pane CWD to link handlers via getPaneLinkCwd.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: repo-root canonicalization for nested git imports plus keeping the first terminal in the chosen subfolder.
Description check ✅ Passed The description includes all required template sections and provides detailed summary, testing, review, security, and notes content.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

@nwparker

nwparker commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Evidence

Unit tests (vitest) — 333 passed

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/main/git/repo-detection.test.ts \
    src/main/ipc/repos-remote.test.ts \
    src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx \
    src/renderer/src/components/sidebar/project-added-default-checkout.test.ts \
    src/renderer/src/lib/worktree-activation.test.ts \
    src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts \
    src/renderer/src/components/terminal-pane/terminal-link-handlers.test.ts \
    src/renderer/src/store/slices/store-cascades.test.ts

 Test Files  8 passed (8)
      Tests  333 passed (333)

Key regression coverage:

  • repo-detection.test.ts: getGitRepoRoot resolves a contained path to the worktree root; preserves bare-repo paths.
  • repos-remote.test.ts: repos:add canonicalizes a local git path to the detected root, and dedupes after root resolution.
  • project-added-default-checkout.test.ts: a contained selected path becomes the initial terminal cwd; a repo-root selection applies no override.
  • use-terminal-pane-lifecycle.test.ts: one-shot initial cwd is consumed once and cleared after the first pane.
  • store-cascades.test.ts / terminal-orphan-helpers.ts: pendingInitialCwdByTabId is cleaned up on orphan teardown.

Type + lint gates

$ ./node_modules/.bin/tsgo --noEmit -p config/tsconfig.node.json      # clean
$ ./node_modules/.bin/tsgo --noEmit -p config/tsconfig.tc.web.json    # clean
$ ./node_modules/.bin/oxlint <17 changed files>                       # clean
$ ./node_modules/.bin/oxlint                                          # only 1 pre-existing
#   warning in untouched useGitStatusPolling.ts; no max-lines regressions

Live Electron repro (dev build, CDP)

Launched this branch's dev build and exercised the real window.api.repos.add IPC and store actions:

1. Subfolder import canonicalizes to the repo root

repos.add({ path: '/tmp/monorepo/packages/web', kind: 'git' })
→ { repo: { path: "/private/tmp/monorepo", displayName: "monorepo", ... } }

The selected subfolder resolved to the canonical git repo root (/private/tmp/monorepo), and the project name is the repo-root basename monorepo — not web. (/tmp is a symlink to /private/tmp on macOS; --show-toplevel returns the canonical real path, which is exactly the canonicalization this PR relies on.)

2. Re-importing the subfolder dedupes (no duplicate)

repos.add({ path: '/tmp/monorepo/packages/web', kind: 'git' })
→ returnedId = 743cb5b9-...  (same repo), monorepoCount = 1

3. Selecting the repo root itself dedupes to the same repo

repos.add({ path: '/tmp/monorepo', kind: 'git' })
→ returnedId = 743cb5b9-...  (same repo), monorepoCount = 1

4. One-shot initial-cwd store mechanism (drives the first-terminal cwd)

queueTabInitialCwd('probe-tab', '/private/tmp/monorepo/packages/web')
consumeTabInitialCwd('probe-tab') → '/private/tmp/monorepo/packages/web'   (1st)
consumeTabInitialCwd('probe-tab') → null                                    (2nd — one-shot)

Screenshot — project rooted at the git repo root after subfolder import

Captured screenshot 02-project-rooted.png (1920x1170) shows, after importing /tmp/monorepo/packages/web:

  • The source-control panel (right): vs master, header "No changes on this branch — This workspace is clean and this branch has no changes ahead of master" — i.e. git operations resolve against the repo root, confirming correct rooting.
  • The sidebar "Add a setup script" card names the imported project monorepo (the repo-root basename), not web.
  • A Terminal 1 tab was created for the activated worktree.

(Image could not be uploaded to the PR via CLI in this environment: gh image needs a logged-in browser session token, which is unavailable headlessly, and gh-attach is disallowed by process. The visual facts above are transcribed from the captured PNG.)

Note: the live terminal prompt cwd could not be screenshotted because this validation environment's node_modules is symlinked from the primary checkout and node-pty's native spawn-helper was built for a now-deleted worktree path (DaemonProtocolError: ... spawn-helper ... ENOENT), so no PTY could spawn. The terminal-cwd half of the fix is therefore proven by the unit tests above and the live one-shot queue/consume round-trip (#4), not by a rendered prompt.

# Conflicts:
#	src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
#	src/renderer/src/lib/worktree-activation.ts
@nwparker
nwparker merged commit adcf74a into main Jun 28, 2026
1 check failed

@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: 3

🧹 Nitpick comments (1)
src/main/ipc/repos.ts (1)

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

Add a short “why” comment for the second dedupe pass.

This extra lookup against resolvedPathKey is carrying the PR’s repo-root canonicalization rule, but next to the first pathKey lookup 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

📥 Commits

Reviewing files that changed from the base of the PR and between c906405 and 67425fc.

📒 Files selected for processing (23)
  • src/main/git/repo-detection.test.ts
  • src/main/git/repo.ts
  • src/main/ipc/repos-remote.test.ts
  • src/main/ipc/repos.ts
  • src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx
  • src/renderer/src/components/native-chat/native-chat-assembler-merge-parity.test.ts
  • src/renderer/src/components/native-chat/native-chat-incremental-assembler.test.ts
  • src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx
  • src/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsx
  • src/renderer/src/components/sidebar/project-added-default-checkout.test.ts
  • src/renderer/src/components/sidebar/project-added-default-checkout.ts
  • src/renderer/src/components/terminal-pane/terminal-link-handlers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-link-handlers.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/lib/worktree-activation.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/store/slices/store-cascades.test.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/terminal-orphan-helpers.ts
  • src/renderer/src/store/slices/terminals.ts

Comment on lines +98 to +106
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

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.

🎯 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

Comment on lines +364 to +366
if (primaryTabId && opts?.initialCwd) {
useAppStore.getState().queueTabInitialCwd(primaryTabId, opts.initialCwd)
}

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.

🎯 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>

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.

🎯 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

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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] Add Project → Browse folder imports a monorepo subfolder but opens the Git repository root

1 participant