Skip to content

Claude account profiles: dormant routing and consumers (Step 2 of 4) - #24351

Merged
Jinwoo-H merged 53 commits into
mainfrom
brennanb2025/claude-profile-routing
Oct 7, 2026
Merged

Jinwoo-H merged 53 commits into
mainfrom
brennanb2025/claude-profile-routing

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​691 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​662
Prod 51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​719 $\color{#cf222e}{\Huge{\mathbf{−}}}$​54 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​665

ELI5

Each Claude account now has its own folder (#24300). This PR teaches every place Orca starts Claude to use the selected account's folder. That includes the claude command typed in an Orca terminal, chat, the model list and usage checks. It stays switched off until #24434, so nothing changes for users yet.

What Changed

Step 2 of 4 for STA-3698. Builds on #24300.

  • One account router (claude-profile-router.ts).
    • When the selected account changes, it writes a small "which account" file.
    • It then starts that account's folder setup on a worker thread, so Electron's main thread never waits on it.
    • A launch waits only if the account's folder has never been set up.
  • A claude shell function (bash, zsh, fish, PowerShell) reads that file every time it runs, so already-open terminals follow an account switch.
  • No saved accounts: there's no file, and claude runs normally.
  • The user's own CLAUDE_CONFIG_DIR wins. If they export one in their shell setup, it's used. When an account is also selected, claude prints one line saying the Orca account isn't used in that terminal.
  • A missing or broken selected account refuses with a clear message rather than silently running another account.
  • Launch paths routed: terminal, structured chat, model list, usage, and Orca's session and usage readers. WSL comes in Claude account profiles: dormant WSL guest setup (Step 3 of 4) #24384; SSH is unchanged.

Why

Reading the selection on every launch, instead of once at shell start, is what lets already-open terminals follow a switch. It's also the common pattern for this. We refuse rather than fall back to the default account, because a silent fallback runs the wrong account, which is the class of bug this stack fixes.

Linked Issue

Part of STA-3698 (fixed by #24434). Refs #9582.

Visual Proof

N/A. Switched off until #24434; the generated shell setup is unchanged (snapshot tests).

Testing

  • Unit tests cover:

    • the router: publish, waiting only for a first setup, refusals;
    • the setup worker, built with esbuild and run for real;
    • the shell function in each shell;
    • the structured launch path.
  • The shell-setup snapshot fixtures are unchanged from main.

  • PowerShell is checked as text only.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Review round 1 of the dormant profile setup found that the pieces could
be called without their safety checks, that one failed write or an
unreadable bookkeeping file could silently stop sharing for good, and
that Windows prompt history could bring back history the user cleared.

- One entry, provisionClaudeAccountProfile: the profile gate (namespace,
  no linked components, outside ~/.claude and ~/.config/claude, and an
  ownership marker beside the home naming the account and target) runs
  first and refuses before creating anything; then history sharing,
  config provisioning, and the hook install after the settings merge.
  Results come back per surface with closed warning codes instead of
  message text.
- The sharing ledger is keyed by surface name, records a value only
  after its write succeeded, and an unreadable ledger starts empty and
  is rewritten instead of blocking every surface.
- The profile state file goes through the same locked writer as folder
  trust (Claude's <file>.lock plus the in-process queue), generalized as
  updateClaudeGlobalConfig. Onboarding and trust are still applied when
  the personal state file is unreadable.
- WSL descriptors build guest POSIX paths; the state-file path style
  follows the injected platform.
- Orca's managed statusLine has one owner in a profile: the settings
  merge never shares it, a user's own statusLine is shared over it, and
  the profile installer follows the default home's slot so a default
  opt-out reaches every profile. remove() takes the same destination;
  the remote installer cannot accept one.
- Prompt history compares file identity (bigint dev+ino) on every
  platform, never drains the shared file into itself, drains retained
  copies in generation order, never reuses a stale cursor, and on Windows
  keeps a replaced default's old copy aside instead of replaying it.
  Directory merges keep going past a failed entry.
A user's own Claude hooks in ~/.claude (notifications, formatters) did
not run under a managed account, because the whole hooks key stayed
private. They are now shared like any other settings key: Orca's own
hook entries and its managed statusLine are stripped from both the
personal value and the profile's current value before the per-key
ledger comparison, so they never travel through the merge and never make
the key look user-owned. Orca entries already in the profile are kept on
write, and the profile hook installer adds them on top as before.

Prompt history: merged bytes that lack a final newline are terminated,
so Claude's next record no longer fuses onto the last merged line. When
a CLI rewrote the profile's history file (old records plus new), only
the lines past the part it shares with the default history are added,
instead of the whole file again.
Hooks and statusLine sharing:
- When ~/.claude holds only Orca's hook entries, the user's shared hooks
  now read as an empty value instead of a missing key. Removing the
  user's last own hook in ~/.claude therefore reaches profiles that
  never edited it, and deleting the only shared hook inside a profile
  stays deleted.
- A custom statusLine Orca shared, and the profile never edited, goes
  away when the default home drops it. When a shared custom line
  replaced Orca's line in a profile, the profile's statusline marker is
  dropped so Orca's line comes back once the default returns to it; a
  profile that opted out stays opted out. No other key gains deletion.
- install/remove/getStatus with a profile directory refuse when it is
  the default home, or its settings.json resolves to the default one,
  instead of editing System Default's hooks and opt-out state.
- The profile statusline rule reads the default settings under the
  userHome passed to the setup entry, not os.homedir().

Profile state and ownership:
- A malformed `projects` value skips only folder trust (new warning
  code trust-refused); onboarding and shared keys still apply.
- The ownership marker stores only host-local facts (account, runtime,
  distro). The execution host id is the caller's view of the host, so
  it stays in the in-memory descriptor and is not compared.

Prompt history interruption paths:
- With no cursor yet, a retained copy starts past the bytes it shares
  with the default history, so an interrupted share no longer replays
  the whole history.
- A retained name for the shared file itself is removed with its cursor
  instead of lingering until a later scrub makes it look new.
- The Windows link record is read three-state: unreadable stops the
  share instead of reading as "no link". If the record cannot be
  written after linking, the fresh link is undone.
- An unreadable retained copy is reported and no longer blocks linking.
hook-service.ts and hook-settings.ts are compiled into the packaged CLI
project, which lists every file explicitly. The statusline policy and
profile destination modules they now import were missing, so the CLI
typecheck failed with TS6307. The CLI still loads hook-service through
the existing managed-agent-hook-controls build entry, which bundles
both modules; neither imports electron.
- A profile whose hooks hold only Orca's entries and that sharing never
  recorded is no longer treated as a user edit, so the user's first own
  hook in ~/.claude reaches it (for example when the profile was set up
  before ~/.claude had any hooks).
- A retained prompt-history file is removed as a second name for the
  shared file only when the default history does not itself link to it;
  otherwise it holds the only copy and is kept.
- Default-home checks compare file identity: the profile hook
  destination check uses device and inode, and the profile/default
  separation check resolves on-disk case, so a case-only alias of
  ~/.claude is refused on case-insensitive filesystems.
- A test pins that an unreadable leftover session tree no longer blocks
  linking.
QA found that removing a setting from ~/.claude never reached a managed
account: deleting the whole `hooks` block left the user's hook running
there. Only statusLine followed the default away.

Every shared key now follows the same rule through the existing per-key
ledger: when a key disappears from ~/.claude/settings.json (or
mcpServers/theme from the personal state file), it is removed from the
profile if the profile still holds exactly what Orca last shared. A
value changed inside the account is kept. Keys Orca never shared,
including denylisted ones, are never touched. Deleting the whole hooks
block removes the user's shared hooks and keeps Orca's own entries. A
missing source counts as empty; an unreadable source removes nothing.
…e by capability

Restores the inline mobile allowlist so its source-scan guard sees every
accounts.* method again, and the generated params catalog to generator order.
…ed config dir

The function is defined only in a routed pane where claude is a real
executable (the codex function's guard), re-reads the pointer only while
CLAUDE_CONFIG_DIR is unset or still Orca's injected twin, accepts Git Bash
drive paths, and starts on its own line after the fish/PowerShell codex text.
…lifecycle triggers

Round-1 review fixes for the dormant profile routing:
- Panes get the selected profile's CLAUDE_CONFIG_DIR plus an Orca twin at
  spawn, so nested shells and scripts inherit the account; System Default
  injects nothing and its home is the inherited CLAUDE_CONFIG_DIR.
- An absent routing owner is System Default, never a throw; AI Vault and
  session-search scans receive profile roots from their parent, and the
  capability is advertised only where an owner is installed.
- Account listing never throws: per-account readiness, a stale pointer is
  republished in the background and reported on the snapshot.
- Profiles are set up at select and startup; a launch only sets up one that
  never was, and a worker fault on a prepared profile is a warning. The
  Claude version probe is cached per binary identity.
- Pre-trust goes through the existing deadline- and realpath-guarded writer
  against the launch env's profile config.
- Skill discovery keeps a caller's Claude root and a broken Claude selection
  no longer fails other providers.
- The durable record carries a provider-neutral launchAccountHome, read
  through one helper by the launch fallback and the model catalog.
…published

A pointer left naming the previous account would launch it silently; a
missing pointer makes the claude function refuse visibly. A newer selection
that raced the failed one keeps its pointer.
…r than 3.4

Shell tests skip system config and abort unless claude resolves to the fake.
…fig dir lookup

- An overtaken publish that fails leaves the newer selection's pointer.
- The runtime config dir falls back to the legacy home for an unresolvable
  account or a WSL target, so skill roots never fail for other providers.
- WSL guest reader roots merge verbatim, never realpathed on this thread.
- History readers include ~/.claude, where step-1 setup pools profile history.
- System Default ignores a config dir an outer Orca injected (twin-marked).
…eate resolver

A Claude agent-env CLAUDE_CONFIG_DIR the create path stored is now the home
the launch pins and the model probe accepts.
A worker thread's os.homedir() ignores its own env, so the hook and
statusline scripts now go under the home the job names. The worker test pins
the process HOME to a sentinel, refuses to run unless the worker sees it, and
asserts nothing lands there.
…d of setting null

On .NET 9+ (pwsh 7.5+) SetEnvironmentVariable with $null creates an empty
variable, so stripped auth vars reached claude as empty strings and the
restore left CLAUDE_CONFIG_DIR empty in the user's session.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: Step 2 of 4 (dormant), head 221d84c

The problem: switching between managed Claude accounts in Orca can force users back to /login, because Orca copies login files into one shared Claude folder and a later copy can overwrite a login Claude has already refreshed. Step 4 fixes that by giving each account its own folder; this PR builds the routing that tells every Claude launch which folder to use.

User-facing change in this PR: none. A hard-coded switch keeps the new routing off. On a remote Mac, a dev build of main and of this PR behaved identically for account switching, terminal and split launches, Chat view chats and the model list (screenshots in the PR body).

Verdict: kept and fixed rather than rewritten; the core design (settings stay the single source, a re-derived pointer file, one shared launch description, setup in a background worker) held up under review. Left as a draft for the coordinator; not merged or marked ready.

Fixed during review (all dormant until Step 4 unless noted):

  • CI reds: the generated RPC parameter catalog was out of order, and the mobile allowlist test could no longer see account methods; the unused extra selection method was dropped and both files are back to their original shape.
  • CI red: shell tests ran zsh on Linux runners that don't have it.
  • A test wrote Orca's real hook script under the developer's home folder (worker threads ignore a test's HOME); setup now installs hooks under the home the setup job names. The script content is identical to main's.
  • Programs started inside a terminal (scripts, tmux, nested shells) would have silently used the personal Claude login; terminals now start with the selected account's folder in their environment, matching how Codex homes are delivered.
  • A CLAUDE_CONFIG_DIR the user sets was thrown away; System Default now adds nothing and a value the user exports in a shell wins.
  • Turning the switch on would have broken processes without account routing (terminal spawns on the headless host, AI Vault scans in their separate process); missing routing is now a normal state, not an error.
  • Listing accounts threw on a legacy or stale selection, which would have hidden the account picker; it now reports per-account readiness and never throws.
  • Account setup ran before every launch and could fail bursts of launches; it now runs at selection, startup and the first launch of an unprepared folder, and setup trouble on a prepared folder only warns.
  • The fish and PowerShell startup text was missing a line break (function never defined), the function replaced users' own claude wrappers, Git Bash rejected Windows paths, WSL panes refused even on System Default, and fish below 3.4 could not read the pointer.
  • A failed or overtaken selection could leave the pointer naming the previous account, or delete a newer account's pointer; the pointer is now withdrawn only by the newest publish.
  • Skills discovery, global skill installs and pre-trust failed or misbehaved for an unresolvable account; only Claude is affected now and pre-trust goes through the existing guarded writer.
  • PowerShell 7.5+ (found in Windows QA): removing an environment variable left it set to an empty string, so Claude got empty auth variables and the session kept CLAUDE_CONFIG_DIR=""; fixed and re-verified on PowerShell 5.1 and 7.6.6.

Deferred (P3, dormant, listed in the PR body):

  • PowerShell refuses with .NET's raw error text instead of Orca's message for a missing or locked pointer, drops a literal -- argument, and accepts a few pointer shapes Orca never writes.
  • fish reads a pointer containing a NUL byte up to the NUL instead of refusing; CI does not run fish.
  • Structured-chat refusals reach the user as a generic start failure (reason codes belong with Step 4's UI).
  • Running Orca inside another Orca's terminal leaves a few edge cases (commit-message runs, skills root and System Default panes can see the outer Orca's account folder).

Verified: gate-off behaviour identical to the base across every changed path (code audit plus byte-identical shell startup text for bash, zsh, fish and PowerShell); named suites green with each fix shown to fail when reverted; node, web and cli typechecks; CI 23/23 green at 221d84c; remote QA as above, with bash, zsh, Git Bash, PowerShell 5.1 and 7.6.6 driven directly, and fish 3.3.1 and 4.8.1 locally.

Not verified: packaged app startup, a paired host end to end, WSL guests (Step 3), fish on the QA Mac (not installed), and live switching with routing turned on (Step 4).

…aude-profile-routing

# Conflicts:
#	src/main/daemon/shell-ready.ts
#	src/main/providers/local-pty-shell-ready.ts
…ex hand-off

Main now gives a plain fish tab Orca's codex function through a vendor_conf.d
snippet instead of a -C init. The claude function only rode the -C path, so a
plain fish tab would not re-read the account selection per invocation once
profiles are on. Define it at the first prompt beside codex; it stays empty
while the profile gate is off.
publish() writes the pointer and starts setup in the background, so neither
startup nor an account switch blocks on a history merge. Each setup runs in a
one-shot worker (the profile-state backup worker's pattern); one setup per
account at a time, reused by later requests. A launch waits only for a folder
that was never set up, and refuses with a clear message if that setup fails.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review October 6, 2026 21:18
…p' into claude-profile-routing-lane

# Conflicts:
#	src/main/claude/claude-structured-launch-resolution.ts
#	src/main/fish-xdg-data-dirs-handoff.ts
…es, link setup folders by path

- Prompt-history drain appends only lines the shared file lacks, so a purge never re-adds lines.
- A set-aside history copy whose saved offset reaches its end is deleted on the next run.
- Setup folders link to the default home's own entry, not its resolved target.
- The profile gate and folder creation run once, in provisionClaudeAccountProfile.
- installHooks receives only configDir; drop a duplicate test key that fails CI.
…nother account; zsh claude function; setup timeout

- With account routing, a chat resume checks its transcript is in the launch folder; a missing one
  with a stored leaf refuses with historyInOtherAccount instead of starting fresh.
- The launch folder of a selected account comes from prepareLaunch(); the resolver stays for System default.
- zsh panes get the claude function like bash, fish and PowerShell (empty while routing is off).
- The setup worker is terminated after 60 s so a later launch can retry.
- Document that the setup marker means setup started, not finished.
Jinwoo-H added a commit that referenced this pull request Oct 6, 2026
… into claude-profile-activate-lane

Keeps the single unconditional zsh claude function from #24351 and drops this PR's
claudeAccountFunction flag; relay zsh wrappers now carry the inert function too.
Jinwoo-H and others added 7 commits October 6, 2026 19:39
… is found in another folder

A transcript found in no known folder keeps the old stored-leaf resume.
…link tests on Windows

After Orca installs its hooks into an account, record the account's hooks in
the settings ledger so a later run can still bring the user's own hooks in.
Tests that create real symlinks now skip on Windows.
@Jinwoo-H
Jinwoo-H changed the base branch from brennanb2025/claude-profile-setup to main October 7, 2026 03:47
…g-lane

# Conflicts:
#	src/main/claude/claude-structured-launch-resolution.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-failure-text.ts
#	src/main/native-chat/agent-session-wire/structured-agent-session-pre-spawn-first-answer.test.ts
#	src/renderer/src/components/native-chat/agent-session-failure-words-text.ts
#	src/renderer/src/i18n/en-runtime-required.json
#	src/renderer/src/i18n/locales/en.json
#	src/renderer/src/i18n/locales/es.json
#	src/renderer/src/i18n/locales/fr.json
#	src/renderer/src/i18n/locales/ja.json
#	src/renderer/src/i18n/locales/ko.json
#	src/renderer/src/i18n/locales/zh.json
#	src/shared/agent-session-failure-copy.ts
#	src/shared/agent-session-failure-words.ts
#	src/shared/agent-session-failure.ts
#	src/shared/agent-session-refusal-details.ts
#	src/shared/agent-session-refusal-reason-words.ts
#	src/shared/structured-agent-session-dispatch-rejection.ts
A WSL profile's data root is a POSIX path, so building one from a Windows
temp dir fails the absolute-path check there.
@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

The changes add worker-based Claude profile setup and a router that publishes the selected profile for host launches. Claude runtime and shell integrations can use the selected profile environment. Structured launches resolve profile homes and check transcript locations, including other managed accounts, before resuming. A typed refusal and localized messages cover history found in another account. AI-vault, usage, session-file, and worktree discovery now include Claude profile directories.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 60eef

These account-routing and discovery issues should be resolved before routing is enabled. The disabled routing switch limits immediate impact, but the PR is not ready to enable the feature as-is.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.52% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 46 functions across 50 files. 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 identifies Claude account-profile routing and consumers, and labels this as Step 2 of 4.
Description check ✅ Passed The description covers the ELI5 summary, changes, rationale, linked work, visual-proof status, testing, and checklist. It is mostly complete, but it does not provide a Fixes #... entry or report whe…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e578a2a7-2877-49e2-a0e1-207d5cfd0a3e
📥 Commits

Reviewing files that changed from the base of the PR and between dff65d5 and b779d4a.

📒 Files selected for processing (58)
  • config/build-plugins/plain-node-entry-guard.ts
  • electron.vite.config.ts
  • src/main/ai-vault/cached-session-list.ts
  • src/main/ai-vault/session-scanner-agent-sources.ts
  • src/main/ai-vault/session-scanner-roots.ts
  • src/main/ai-vault/session-scanner-types.ts
  • src/main/claude-accounts/claude-profile-installed-router.ts
  • src/main/claude-accounts/claude-profile-paths.test.ts
  • src/main/claude-accounts/claude-profile-router.test.ts
  • src/main/claude-accounts/claude-profile-router.ts
  • src/main/claude-accounts/claude-profile-setup-worker-entry.ts
  • src/main/claude-accounts/claude-profile-setup-worker.test.ts
  • src/main/claude-accounts/claude-profile-setup-worker.ts
  • src/main/claude-accounts/claude-profile-shell-composition.test.ts
  • src/main/claude-accounts/environment.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/main/claude-usage/scanner.ts
  • src/main/claude-usage/transcript-file-discovery.ts
  • src/main/claude/claude-structured-launch-account-routing.test.ts
  • src/main/claude/claude-structured-launch-home.ts
  • src/main/claude/claude-structured-launch-resolution.ts
  • src/main/daemon/daemon-bash-shell-ready-rcfile.ts
  • src/main/daemon/shell-ready.ts
  • src/main/fish-xdg-data-dirs-handoff.ts
  • src/main/ipc/pty/ipc/spawn-preflight.ts
  • src/main/ipc/pty/runtime/spawn-preflight.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-failure-text.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-pre-spawn-first-answer.test.ts
  • src/main/native-chat/session-file-resolver.ts
  • src/main/powershell-osc133-bootstrap.ts
  • src/main/providers/local-pty-shell-ready-bash-rcfile.ts
  • src/main/providers/local-pty-shell-ready.ts
  • src/main/runtime/structured-agent-account-home.ts
  • src/main/runtime/structured-agent-session-create-adoption.ts
  • src/main/usage/usage-scan-worker-entry.ts
  • src/main/usage/usage-scan-worker-protocol.ts
  • src/main/usage/usage-scan-worker-spawn.ts
  • src/main/worktree-retirement-discovery.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/renderer/src/components/native-chat/agent-session-failure-words-text.ts
  • src/renderer/src/i18n/en-runtime-required.json
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/shared/agent-session-failure-copy.ts
  • src/shared/agent-session-failure-words.ts
  • src/shared/agent-session-failure.ts
  • src/shared/agent-session-refusal-details.ts
  • src/shared/agent-session-refusal-reason-words.ts
  • src/shared/claude-profile-routing.ts
  • src/shared/claude-shell-function.test.ts
  • src/shared/claude-shell-function.ts
  • src/shared/setup-agent-sequencing.ts
  • src/shared/structured-agent-session-dispatch-rejection.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment on lines +110 to +120
/** Waits for setup only for a folder that was never set up; otherwise launches at once. */
async prepareLaunch(): Promise<ClaudeRuntimeAuthPreparation> {
const profile = this.selectedProfile()
if (profile && isDirectory(profile.home) && !existsSync(profileMarkerPath(profile))) {
const report = await this.setUp(profile).catch(() => null)
if (report?.outcome !== 'prepared') {
throw new Error(CLAUDE_PROFILE_SETUP_FAILED_MESSAGE)
}
}
return this.preparation()
}

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '35,155p' src/main/claude-accounts/claude-profile-router.ts
rg -n 'setupMarker|setup.marker|provisionClaudeAccountProfile|marker' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 10192


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- setup implementation ---'
sed -n '1,230p' src/main/claude-accounts/claude-profile-setup.ts
printf '%s\n' '--- ownership gate ---'
sed -n '90,165p' src/main/claude-accounts/claude-profile-paths.ts
printf '%s\n' '--- router complete relevant source ---'
sed -n '1,250p' src/main/claude-accounts/claude-profile-router.ts
printf '%s\n' '--- router tests ---'
sed -n '1,240p' src/main/claude-accounts/claude-profile-router.test.ts
printf '%s\n' '--- setup tests ---'
sed -n '1,210p' src/main/claude-accounts/claude-profile-setup.test.ts
printf '%s\n' '--- setup/provision calls and router launch calls ---'
rg -n 'prepareLaunch\\(|\\.publish\\(\\)|provisionClaudeAccountProfile|runClaudeProfileSetupInWorker|ensure.*Profile|write.*Marker' src/main src/renderer
printf '%s\n' '--- PR diff for implicated files ---'
git diff --no-ext-diff --unified=45 dff65d55a3eae91c64d791d2cb1265f8f9f2903e b779d4acdc758d42767ac0e5f3ce51fb4d27d16d -- src/main/claude-accounts/claude-profile-router.ts src/main/claude-accounts/claude-profile-setup.ts src/main/claude-accounts/claude-profile-paths.ts src/main/claude-accounts/claude-profile-router.test.ts src/main/claude-accounts/claude-profile-setup.test.ts

Repository: stablyai/orca

Length of output: 27507


🏁 Script executed:

#!/bin/bash
set -u

printf '%s\n' '--- router references ---'
rg -n -F 'prepareLaunch(' src/main src/renderer || test "$?" -eq 1
rg -n -F 'router.publish()' src/main src/renderer || test "$?" -eq 1
rg -n -F 'ClaudeProfileRouter' src/main src/renderer || test "$?" -eq 1
printf '%s\n' '--- worker implementation ---'
sed -n '1,180p' src/main/claude-accounts/claude-profile-setup-worker.ts
sed -n '1,100p' src/main/claude-accounts/claude-profile-setup-worker-entry.ts
printf '%s\n' '--- router integration files containing prepareLaunch ---'
rg -l -F 'prepareLaunch(' src/main src/renderer | while IFS= read -r file; do
  printf '%s\n' "--- $file ---"
  rg -n -C 8 -F 'prepareLaunch(' "$file"
done
printf '%s\n' '--- PR diff for router and tests ---'
git diff --no-ext-diff --unified=20 dff65d55a3eae91c64d791d2cb1265f8f9f2903e b779d4acdc758d42767ac0e5f3ce51fb4d27d16d -- src/main/claude-accounts/claude-profile-router.ts src/main/claude-accounts/claude-profile-router.test.ts

Repository: stablyai/orca

Length of output: 28065


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- runtime-auth service ---'
nl -ba src/main/claude-accounts/runtime-auth-service.ts | sed -n '1,125p'
printf '%s\n' '--- structured launch home ---'
nl -ba src/main/claude/claude-structured-launch-home.ts | sed -n '1,100p'
printf '%s\n' '--- structured launch resolution caller ---'
nl -ba src/main/claude/claude-structured-launch-resolution.ts | sed -n '210,270p'

Repository: stablyai/orca

Length of output: 12947


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- resolver and auth-preparation callsites ---'
rg -n -F 'resolveClaudeStructuredLaunchHome(' src/main src/renderer || test "$?" -eq 1
rg -n -F 'prepareForClaudeLaunch(' src/main src/renderer || test "$?" -eq 1
printf '%s\n' '--- structured launch home call context ---'
rg -n -F 'claudeStructuredLaunchArgs' src/main/claude/claude-structured-launch-resolution.ts || test "$?" -eq 1
nl -ba src/main/claude/claude-structured-launch-resolution.ts | sed -n '265,350p'

Repository: stablyai/orca

Length of output: 6544


Wait for an in-flight profile setup before preparing the launch.

When publish() starts setup for an existing profile, the ownership gate writes profile.json before setup finishes. If launch preparation runs after that write, prepareLaunch() skips the pending setup and can return the selected profile’s config directory before provisioning completes. Check for an in-flight setup as well as marker absence before skipping the wait.

Suggested fix
-    if (profile && isDirectory(profile.home) && !existsSync(profileMarkerPath(profile))) {
+    if (
+      profile &&
+      isDirectory(profile.home) &&
+      (this.setups.has(profile.accountId) || !existsSync(profileMarkerPath(profile)))
+    ) {
📝 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
/** Waits for setup only for a folder that was never set up; otherwise launches at once. */
async prepareLaunch(): Promise<ClaudeRuntimeAuthPreparation> {
const profile = this.selectedProfile()
if (profile && isDirectory(profile.home) && !existsSync(profileMarkerPath(profile))) {
const report = await this.setUp(profile).catch(() => null)
if (report?.outcome !== 'prepared') {
throw new Error(CLAUDE_PROFILE_SETUP_FAILED_MESSAGE)
}
}
return this.preparation()
}
/** Waits for setup only for a folder that was never set up; otherwise launches at once. */
async prepareLaunch(): Promise<ClaudeRuntimeAuthPreparation> {
const profile = this.selectedProfile()
if (
profile &&
isDirectory(profile.home) &&
(this.setups.has(profile.accountId) || !existsSync(profileMarkerPath(profile)))
) {
const report = await this.setUp(profile).catch(() => null)
if (report?.outcome !== 'prepared') {
throw new Error(CLAUDE_PROFILE_SETUP_FAILED_MESSAGE)
}
}
return this.preparation()
}

Comment on lines +64 to +65
if (input.leafUuid === null) {
return false

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

Check other accounts before starting a stored session ID fresh.

If a stored handle has no leaf UUID and its transcript exists only in another account, this return skips the other-home search. The launch then uses sessionId in the selected account instead of issuing historyInOtherAccount. Check the other homes before returning false; keep the null-leaf check for the final resume decision.

})
for (const projectsDir of [
getClaudeProjectsDir(args.home ?? homedir(), args.env ?? process.env),
...claudeProfileHistoryDirs('projects')

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -n -C 6 'function isDirectory|const isDirectory|function claudeProfileHistoryDirs|accountHomes\(' src/main/claude-accounts/claude-profile-installed-router.ts

Repository: stablyai/orca

Length of output: 1125


🏁 Script executed:

#!/bin/bash
set -e
git diff --unified=30 dff65d55a3eae91c64d791d2cb1265f8f9f2903e b779d4acdc758d42767ac0e5f3ce51fb4d27d16d -- src/main/worktree-retirement-discovery.ts
printf '\n--- discovery source ---\n'
sed -n '1,280p' src/main/worktree-retirement-discovery.ts
printf '\n--- bound listing helper references ---\n'
rg -n -F -- 'readDirectoryNames' src/main

Repository: stablyai/orca

Length of output: 16516


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- installed router module ---'
sed -n '1,150p' src/main/claude-accounts/claude-profile-installed-router.ts
printf '%s\n' '--- direct helper usages ---'
rg -n -F -- 'claudeProfileHistoryDirs(' src/main
rg -n -F -- 'isDirectory(' src/main/claude-accounts
printf '%s\n' '--- accountHomes declarations and bindings ---'
rg -n -F -- 'accountHomes' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 4986


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,125p' src/main/claude-accounts/claude-profile-router.ts
sed -n '160,195p' src/main/claude-accounts/claude-profile-router.ts

Repository: stablyai/orca

Length of output: 6130


Keep profile roots with failed type checks in retirement scans.

When lstatSync throws for a configured profile projects path, isDirectory returns false and claudeProfileHistoryDirs('projects') filters that path out. For scans with host parents, claudeProjectsSources then never submits it to readDirectoryNames, so an access or I/O error cannot mark the scan refused. If the other sources succeed, discovery can return complete: true without reading those buckets. Retain paths with failed type checks for this scan, while continuing to exclude confirmed symlinks, and let readDirectoryNames determine completeness.

…hen no router is installed

Keeps the switched-off path identical to main: the recheck stays the last await.

@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: Advanced
  • Run ID: 13e8292c-10b5-4646-903f-a6b9ba4a30bd
📥 Commits

Reviewing files that changed from the base of the PR and between b779d4a and 60eef11.

📒 Files selected for processing (1)
  • src/main/claude/claude-structured-launch-resolution.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

sources
)
const launchHome = await resolveClaudeStructuredLaunchHome(router, env, record.accountHome.path)
const resumesTranscript = resumedWithoutRouter ?? (await resumes(launchHome))

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Inspect the launch consumer and its account-switch checks without running repository code.
rg -n -C 6 'createClaudeStructuredLaunchResolver\(|assertClaudeAuthSwitchSettled\(|resolveClaudeStructuredLaunchHome\(' src/main

Repository: stablyai/orca

Length of output: 29419


🏁 Script executed:

#!/bin/bash
set -e
ast-grep outline src/main/claude/claude-structured-session-adapter.ts --view expanded
rg -n -C 5 'acquireClaudeSession|resolveLaunch\\(|spawn\\(|assertClaudeAuthSwitchSettled|whenClaudeAuthSwitchSettles|accountSwitchInProgress' src/main/claude src/main/runtime

Repository: stablyai/orca

Length of output: 4087


🏁 Script executed:

#!/bin/bash
set -e
sed -n '1,130p' src/main/claude/claude-structured-session-adapter.ts
rg -n -F -- 'resolveLaunch(' src/main/claude src/main/runtime
rg -n -F -- 'spawn(' src/main/claude src/main/runtime
rg -n -F -- 'assertClaudeAuthSwitchSettled' src/main/claude src/main/runtime

Repository: stablyai/orca

Length of output: 11488


🏁 Script executed:

#!/bin/bash
set -e
ast-grep outline src/main/claude/claude-structured-session-acquisition.ts --view expanded
sed -n '1,180p' src/main/claude/claude-structured-acquisition-launch.ts
rg -n -F -- 'acquireClaudeSession' src/main/claude

Repository: stablyai/orca

Length of output: 5206


🏁 Script executed:

#!/bin/bash
set -e
ast-grep outline src/main/claude/claude-structured-session-acquisition.ts --json=compact | python3 -c '
import json, pathlib, sys
for file in json.load(sys.stdin):
    lines = pathlib.Path(file["path"]).read_text().splitlines()
    for item in file["items"]:
        if item["name"] == "acquireClaudeSession":
            start, end = item["range"]["start"], item["range"]["end"]
            first = start["line"] + 1
            last = end["line"] + (end["column"] > 0)
            print(f"{file[\"path\"]}:{first}-{last}")
            for number in range(first, last + 1):
                print(f"{number:>5} {lines[number - 1]}")
'
rg -n -F -- 'spawner' src/main/claude/claude-structured-session-acquisition.ts
rg -n -F -- 'spawn' src/main/claude/claude-structured-session-acquisition.ts

Repository: stablyai/orca

Length of output: 335


🏁 Script executed:

#!/bin/bash
set -e
ast-grep outline src/main/claude/claude-structured-session-acquisition.ts --json=compact | python3 -c '
import json, pathlib, sys
for file in json.load(sys.stdin):
    lines = pathlib.Path(file["path"]).read_text().splitlines()
    for item in file["items"]:
        if item["name"] == "acquireClaudeSession":
            start, end = item["range"]["start"], item["range"]["end"]
            first = start["line"] + 1
            last = end["line"] + (end["column"] > 0)
            print("{}:{}-{}".format(file["path"], first, last))
            for number in range(first, last + 1):
                print("{:>5} {}".format(number, lines[number - 1]))
'
rg -n -F -- 'spawner' src/main/claude/claude-structured-session-acquisition.ts
rg -n -F -- 'spawn' src/main/claude/claude-structured-session-acquisition.ts

Repository: stablyai/orca

Length of output: 12750


🏁 Script executed:

#!/bin/bash
set -e
sed -n '130,335p' src/main/claude/claude-structured-launch-resolution.ts
cat src/main/claude/claude-structured-launch-home.ts
rg -n -F -- 'openClaudeStreamJsonConnection' src/main/claude
rg -n -F -- 'function openClaudeStreamJsonConnection' src/main/claude
rg -n -F -- 'isClaudeAuthSwitchInProgress' src/main/claude src/main/runtime

Repository: stablyai/orca

Length of output: 16407


🏁 Script executed:

#!/bin/bash
set -e
sed -n '110,205p' src/main/claude/claude-stream-json-connection.ts
cat src/main/claude-accounts/live-pty-gate.ts
rg -n -C 8 -F -- 'prepareLaunch' src/main/claude-accounts/claude-profile-router.ts
rg -n -C 5 -F -- 'whenClaudeAuthSwitchSettles' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 13781


Recheck the account switch after routed transcript lookup.

resolveClaudeStructuredInvocation checks the switch before the routed transcript lookup awaits. acquireClaudeSession then passes the launch to openClaudeStreamJsonConnection, which invokes the SDK without another switch check. If a switch starts during the lookup, Claude can spawn while account credentials are being rewritten. Recheck after the lookup and ensure the launch environment, home, and transcript decision match the settled account selection.

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.

2 participants