Repository navigation
Conversation
…ontent An authoritative host used to run whatever `orca.yaml` setup script it found on disk whenever a paired client asked for a create with setup enabled. The client's trust prompt and the host's execution were two independent reads, so nothing proved they saw the same bytes: a script that changed between the prompt and the create, a create replayed with a different `setupDecision`, or a client that never prompted at all all ended up executing unapproved content. The host now issues a short-lived, one-time approval challenge bound to `repoId` + paired `deviceId` + SHA-256 of its own canonical trust content, hands it to the client alongside the content it hashed, and refuses to run setup unless the presented approval matches the content it is about to execute. Every unverifiable state — malformed approval, expired or evicted challenge, host restart, unreadable `orca.yaml`, missing capability — fails closed: the hook is skipped, the workspace is kept, and the client is told why. - Canonical trust content is host-derived (`getSetupHookTrustContent`) and now honours `commandSourcePolicy`, so a `local-only` repo no longer hashes shared `defaultTabs` commands it would never run. - `runHook` accepts the verified bytes, so the no-runner branch executes what the approval covered instead of re-reading the file. - Challenges dedupe per binding and evict within the crowding device, so routine `repo.hooks` polling cannot evict a live approval and one paired device cannot starve another. - Folder workspaces never mint a token, matching `checkRepoHooks`. - Gated by the `worktree.setup-hook-approval.v1` runtime capability. Clients talking to an older host downgrade to `skip` and say so rather than silently losing the user's choice; desktop, mobile and the terminal session-fork path all carry the approval through. `issueCommand` keeps its own independent trust path and is unchanged.
📝 WalkthroughWalkthroughThe change adds setup-hook approval types, parsers, hashes, and runtime capabilities. Renderer and mobile flows resolve setup trust and pass approval metadata through workspace creation. Runtime services issue and consume device-bound, content-bound approval tokens. Local and remote worktree creation validates approvals, executes verified script content, reports rejection state, and shows warnings when approval is unavailable or rejected. Tests cover transport, replay protection, capability fallback, content mismatches, and creation flows. Merge Risk: 🟡 Moderate · up to The PR binds remote setup execution to per-operation approved content, but the current head still has create paths that can omit required approval data, reuse expired approvals, or hide refusal warnings, causing approved setup to be skipped or users to miss the reason. These integration issues should be corrected before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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 |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
mobile/src/components/NewWorktreeModal.tsx (1)
501-548: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftRefresh setup-hook approval before create and preserve downgrade warnings.
repo.hooksruns only when the repository changes, but approval tokens expire after 15 minutes and are single-use. ReusingsetupTrust.approvalTokencan skip the setup hook after expiry or replay. Re-resolve the trust data before the final create and bind it withresolveSetupHookCreateandbindSetupHookCreate.The current fallback to
skipis silent.WorktreeCreateResultalso discards the serverwarning, andonCreatedcannot pass it to the session route. Preserve the backend warning andsuppressedWarning, then pass the warning through the existing session warning query.
🧹 Nitpick comments (6)
src/renderer/src/lib/ensure-hooks-confirmed.test.ts (1)
651-699: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for a host response that omits
approvalToken.
setupHookApprovalFromTrustreturnsundefinedwhen the host sendssetupTrustwithoutapprovalToken.ensureSetupHookConfirmedthen resolves{ decision: 'run', approvalRequired: true }with noapproval. This older-host downgrade path is the one that decides whether setup runs unproven. A test pinning that shape prevents a silent regression.src/renderer/src/components/terminal-pane/terminal-agent-session-fork-workspace.ts (1)
36-58: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftThe trailing
setupHookApprovalpayload depends on a long positionalcreateWorktreesignature. Both create paths reach the final options parameter through a long run of positionalundefinedvalues. Any inserted parameter shifts the approval payload into a different slot, and the approval then never reaches the host while setup still reportsrun.
src/renderer/src/components/terminal-pane/terminal-agent-session-fork-workspace.ts#L36-L58: replace the 22 positionalundefinedplaceholders with an options-object call, or add a typed wrapper that names the approval parameter.src/renderer/src/lib/launch-work-item-direct.ts#L198-L199: confirm the options object sits at the exact index the store action declares, then migrate this call to the same named-parameter form.src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts (1)
15-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winType the mock with
ConfirmedSetupHookand remove theas nevercasts.The inferred return type of
mockEnsureSetupHookConfirmedis narrowed to{ decision: 'run'; approvalRequired: false }. The fixtures therefore needas never, which disables type checking of the mocked contract. A change toConfirmedSetupHookwould not fail these tests at compile time. Declare the mock against the real type instead.♻️ Proposed change
-const mockEnsureSetupHookConfirmed = vi.fn(async () => ({ - decision: 'run' as const, - approvalRequired: false -})) +const mockEnsureSetupHookConfirmed = vi.fn< + (...args: unknown[]) => Promise<ConfirmedSetupHook> +>(async () => ({ decision: 'run', approvalRequired: false }))Then drop
as neverat Lines 180 and 199, and import the type:import type { ConfirmedSetupHook } from '`@/lib/ensure-hooks-confirmed`'Also applies to: 176-180, 196-199
src/main/runtime/remote-setup-hook-approval-wire.integration.test.ts (2)
59-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueScope the test name to the wire contract.
The fake
createManagedWorktreedecides the marker itself, so line 110 confirms the fake's branch rather than host enforcement. The real evidence is line 109, which provesworktree.createforwardssetupHookApprovalunchanged. Rename the test to state the transport guarantee, so a future reader does not treat this file as coverage for host-side rejection. Host-side rejection is covered insrc/main/runtime/orca-runtime.test.ts.Also applies to: 107-110
114-120: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDo not assert inside
finally.If the request block fails first, the assertion at line 117 can throw during cleanup and mask the original failure. Line 110 already asserts the marker state, so keep
finallylimited to cleanup.♻️ Proposed cleanup-only `finally`
} finally { await server.stop() - if (existsSync(markerPath)) { - expect(readFileSync(markerPath, 'utf8')).toBe(hostContent) - } rmSync(userDataPath, { recursive: true, force: true }) }Drop the now-unused
readFileSyncimport.src/renderer/src/store/slices/worktrees-remote-runtime-create.test.ts (1)
454-460: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueBuild the argument tuple with a typed helper.
Index 25 is correct for the current
createWorktreesignature, but a future inserted parameter shiftsoptionswithout any type error. The second site also casts throughas unknown as, which drops type checking onsetupDecision. Add one local helper that builds the tuple from named fields and reuse it at both sites.Also applies to: 582-587
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3ae63c1e-a60c-40a9-b003-63c9a63f195e
📒 Files selected for processing (45)
mobile/app/h/[hostId]/tasks.tsxmobile/src/components/NewWorktreeModal.tsxmobile/src/tasks/blank-workspace-create.tsmobile/src/tasks/setup-hook-create-binding.test.tsmobile/src/tasks/setup-hook-create-binding.tsmobile/src/tasks/setup-hook-trust.test.tsmobile/src/tasks/setup-hook-trust.tsmobile/src/tasks/source-workspace-create.tsmobile/src/tasks/workspace-create-params.tsmobile/src/tasks/worktree-create-capability.test.tsmobile/src/tasks/worktree-create-capability.tssrc/main/effective-hook-config.tssrc/main/hooks-effective-hook-resolution.test.tssrc/main/hooks.tssrc/main/ipc/worktree-remote.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/remote-setup-hook-approval-wire.integration.test.tssrc/main/runtime/rpc/methods/repo.test.tssrc/main/runtime/rpc/methods/repo.tssrc/main/runtime/rpc/methods/worktree-create-args.tssrc/main/runtime/rpc/methods/worktree-schemas.test.tssrc/main/runtime/rpc/methods/worktree-schemas.tssrc/main/runtime/setup-hook-approval-challenges.test.tssrc/main/runtime/setup-hook-approval-challenges.tssrc/renderer/src/components/terminal-pane/terminal-agent-session-fork-workspace.tssrc/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.tssrc/renderer/src/components/terminal-pane/terminal-agent-session-fork.tssrc/renderer/src/hooks/useComposerState.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/lib/ensure-hooks-confirmed.test.tssrc/renderer/src/lib/ensure-hooks-confirmed.tssrc/renderer/src/lib/hook-trust-confirmation.tssrc/renderer/src/lib/launch-work-item-direct.test.tssrc/renderer/src/lib/launch-work-item-direct.tssrc/renderer/src/lib/pending-worktree-creation.tssrc/renderer/src/lib/worktree-creation-flow.tssrc/renderer/src/runtime/runtime-hooks-client.tssrc/renderer/src/store/slices/worktree-helpers.tssrc/renderer/src/store/slices/worktrees-remote-runtime-create.test.tssrc/renderer/src/store/slices/worktrees/create/create-worktree.tssrc/renderer/src/store/slices/worktrees/create/setup-hook-approval-notice.tssrc/shared/protocol-version.tssrc/shared/setup-hook-approval.tssrc/shared/worktree/create-types.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.
| getSetupHookTrustContent: vi.fn( | ||
| ( | ||
| repo: { hookSettings?: { commandSourcePolicy?: string; scripts?: { setup?: string } } }, | ||
| hooks: { scripts?: { setup?: string }; defaultTabs?: { command?: string }[] } | null | ||
| ) => { | ||
| const shared = hooks?.scripts?.setup?.trim() | ||
| const local = repo.hookSettings?.scripts?.setup?.trim() | ||
| const policy = | ||
| repo.hookSettings?.commandSourcePolicy ?? (local ? 'local-only' : 'shared-only') | ||
| if (policy === 'local-only') { | ||
| return local ?? '' | ||
| } | ||
| if (policy === 'run-both') { | ||
| return [shared, local].filter(Boolean).join('\n') | ||
| } | ||
| return shared ?? '' | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Compare the mocked trust-content policy default with the production implementation.
set -euo pipefail
fd -t f 'effective-hook-config.ts' -x ast-grep outline {} --items all
rg -n -C 15 'function getSetupHookTrustContent' --type=ts
rg -n -C 3 'commandSourcePolicy' --type=ts -g '!**/*.test.ts' | head -60Repository: stablyai/orca
Length of output: 1068
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- production resolver ---'
cat -n src/main/effective-hook-config.ts | sed -n '1,115p'
printf '%s\n' '--- policy resolver ---'
fd -t f -i '*hook*command*source*policy*' -x sh -c 'echo "--- $1"; cat -n "$1"' sh {}
printf '%s\n' '--- test mock and relevant assertions ---'
cat -n src/main/runtime/orca-runtime.test.ts | sed -n '485,520p;6685,6725p'
printf '%s\n' '--- resolver call sites ---'
rg -n -C 5 'resolveHookCommandSourcePolicy|getSetupHookTrustContent' src --glob '!**/*.test.ts'Repository: stablyai/orca
Length of output: 5153
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- policy resolver ---'
cat -n src/shared/hook-command-source-policy.ts
printf '%s\n' '--- test mock and hash assertion ---'
cat -n src/main/runtime/orca-runtime.test.ts | sed -n '485,520p;6685,6725p'
printf '%s\n' '--- resolver tests and uses ---'
rg -n -C 8 'resolveHookCommandSourcePolicy|commandSourcePolicy' src/shared src/main --glob '*.{ts,tsx}' | head -160Repository: stablyai/orca
Length of output: 18025
🏁 Script executed:
#!/bin/bash
set -euo pipefail
node - <<'JS'
function productionPolicy(policy, hasLocalScript) {
if (policy === 'local-only' || policy === 'run-both' || policy === 'shared-only') return policy
if (policy === undefined && hasLocalScript) return 'local-only'
return 'shared-only'
}
function mockPolicy(policy, local) {
return policy ?? (local ? 'local-only' : 'shared-only')
}
const cases = [
['undefined with local', undefined, 'echo local'],
['undefined without local', undefined, undefined],
['explicit local-only', 'local-only', 'echo local'],
['explicit run-both', 'run-both', 'echo local'],
['explicit shared-only', 'shared-only', 'echo local'],
['null with local', null, 'echo local'],
['unknown with local', 'shared-first', 'echo local'],
['whitespace local', undefined, ' ']
]
for (const [name, policy, local] of cases) {
const localTrimmed = typeof local === 'string' ? local.trim() : undefined
const production = productionPolicy(policy, Boolean(localTrimmed))
const mock = mockPolicy(policy, localTrimmed)
console.log(`${name}: production=${production}, mock=${mock}, ${production === mock ? 'same' : 'DIFF'}`)
}
JS
printf '%s\n' '--- all mocked trust-content calls and default-tab fixtures ---'
rg -n -C 4 'getSetupHookTrustContent|defaultTabs' src/main/runtime/orca-runtime.test.tsRepository: stablyai/orca
Length of output: 1580
Align the mock with production trust-content resolution.
Use resolveHookCommandSourcePolicy and include defaultTabs content. The mock diverges for persisted null or unknown policies, and production includes default-tab commands for every policy except local-only.
| private evictForCapacity(deviceId: string): void { | ||
| while (this.challenges.size >= this.maxChallenges) { | ||
| // Why: charge capacity pressure to the crowding device first, so one paired | ||
| // device cannot evict another device's pending approval and force a skip. | ||
| const victim = this.oldestTokenForDevice(deviceId) ?? this.challenges.keys().next().value | ||
| if (victim === undefined) { | ||
| return | ||
| } | ||
| this.delete(victim) | ||
| } | ||
| } | ||
|
|
||
| /** Insertion order is issue order, so the first match is that device's oldest. */ | ||
| private oldestTokenForDevice(deviceId: string): string | undefined { | ||
| for (const [token, challenge] of this.challenges) { | ||
| if (challenge.deviceId === deviceId) { | ||
| return token | ||
| } | ||
| } | ||
| return undefined | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Fallback eviction can still drop another device's pending approval.
If the issuing device owns no entry yet, oldestTokenForDevice returns undefined and line 81 evicts the globally oldest entry, which can belong to another device. A device that fills the map therefore takes one slot from an honest device on its first issue call. The result is a skipped setup hook for that device, so the failure is closed but user-visible.
Refuse the new challenge instead of evicting a foreign binding. The client then re-reads repo.hooks and gets a fresh token.
The existing device-isolation test covers only the case where the crowding device already owns an entry, so this path has no coverage.
🛡️ Proposed fix to keep eviction inside the issuing device
- private evictForCapacity(deviceId: string): void {
+ /** Returns false when capacity can only be freed by dropping another device's binding. */
+ private evictForCapacity(deviceId: string): boolean {
while (this.challenges.size >= this.maxChallenges) {
// Why: charge capacity pressure to the crowding device first, so one paired
// device cannot evict another device's pending approval and force a skip.
- const victim = this.oldestTokenForDevice(deviceId) ?? this.challenges.keys().next().value
+ const victim = this.oldestTokenForDevice(deviceId)
if (victim === undefined) {
- return
+ return false
}
this.delete(victim)
}
+ return true
}Then make issue fail closed when capacity belongs to other devices:
- this.evictForCapacity(args.deviceId)
+ if (!this.evictForCapacity(args.deviceId)) {
+ throw new Error('setup approval challenge capacity exhausted')
+ }📝 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.
| private evictForCapacity(deviceId: string): void { | |
| while (this.challenges.size >= this.maxChallenges) { | |
| // Why: charge capacity pressure to the crowding device first, so one paired | |
| // device cannot evict another device's pending approval and force a skip. | |
| const victim = this.oldestTokenForDevice(deviceId) ?? this.challenges.keys().next().value | |
| if (victim === undefined) { | |
| return | |
| } | |
| this.delete(victim) | |
| } | |
| } | |
| /** Insertion order is issue order, so the first match is that device's oldest. */ | |
| private oldestTokenForDevice(deviceId: string): string | undefined { | |
| for (const [token, challenge] of this.challenges) { | |
| if (challenge.deviceId === deviceId) { | |
| return token | |
| } | |
| } | |
| return undefined | |
| } | |
| /** Returns false when capacity can only be freed by dropping another device's binding. */ | |
| private evictForCapacity(deviceId: string): boolean { | |
| while (this.challenges.size >= this.maxChallenges) { | |
| // Why: charge capacity pressure to the crowding device first, so one paired | |
| // device cannot evict another device's pending approval and force a skip. | |
| const victim = this.oldestTokenForDevice(deviceId) | |
| if (victim === undefined) { | |
| return false | |
| } | |
| this.delete(victim) | |
| } | |
| return true | |
| } | |
| /** Insertion order is issue order, so the first match is that device's oldest. */ | |
| private oldestTokenForDevice(deviceId: string): string | undefined { | |
| for (const [token, challenge] of this.challenges) { | |
| if (challenge.deviceId === deviceId) { | |
| return token | |
| } | |
| } | |
| return undefined | |
| } |
| ? ensureSetupHookConfirmed( | ||
| useAppStore.getState(), | ||
| repoId, | ||
| 'setup', | ||
| selectedRepoExecutionHostId ?? undefined, | ||
| undefined, | ||
| isSubmissionCancelled | ||
| ) | ||
| : Promise.resolve<'skip'>('skip'), | ||
| : Promise.resolve({ decision: 'skip' as const, approvalRequired: false }), |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Pass the runtime owner environment ID to setup confirmation.
Both calls pass undefined as runtimeOwnerEnvironmentId. When a local repository runs in an active runtime environment, ensureSetupHookConfirmed can take a local trust shortcut and return run without an approval. The runtime then receives no setupHookApproval and skips setup.
Pass selectedRepoSettings?.activeRuntimeEnvironmentId in both calls. Add it to the full-submit callback dependencies. The direct launch path already passes this value.
Also applies to: 4280-4287
Problem
An authoritative Orca host would run whatever
orca.yamlsetup script it found on disk whenever a paired client asked for a create with setup enabled. The client's trust prompt and the host's execution were two independent reads of two different files at two different times, so nothing proved they saw the same bytes.Concretely, on
maintoday:orca.yamlthat changes between the client's prompt and the host's create runs unapproved content.setupDecisionruns setup the user never approved for that operation.'inherit') still got setup executed.defaultTabscommands even for alocal-onlyrepo that would never run them, so the hash did not describe what would execute.Invariant this defends
Approach
The host issues a short-lived (15 min), one-time approval challenge bound to
repoId+ paireddeviceId+ SHA-256 of its own canonical trust content + runtime generation, and hands the client both the token and the exact content it hashed. On create, the host recomputes the hash of the content it is about to execute and refuses to run setup unless the presented approval matches.Key properties:
getSetupHookTrustContent(repo, yamlHooks)on the host; the client hashes the host-suppliedsetupTrust.scriptContent, so platform newline divergence is impossible and the client cannot choose what gets hashed.deviceIdcomes fromcreatorProvenance, resolved host-side from the RPC context — not from the wire.consume()removes the token before checking it, so a failed validation cannot be retried.orca.yaml, or a host without the capability → skip the hook, keep the workspace, surface a warning. Never "run anyway", never route elsewhere.runHooktakes an optionalverifiedScript, so the no-runner branch runs what the approval covered rather than re-reading the file after validation.repo.hookson every prompt; identical bindings now reuse and refresh one token, and capacity eviction is charged to the crowding device, so one paired device cannot evict another's pending approval.checkRepoHooksrefusal — they never run setup hooks, so no token they could present as proof should exist.Wire compatibility
Gated by the new
worktree.setup-hook-approval.v1runtime capability. All wire additions are optional RPC fields — no new stream opcodes. Perdocs/reference/remote-wire-compatibility.md:skip, with a toast explaining why. It does not silently drop the user's choice.warning, which old clients already surface.Accepted consequence: old desktop clients that ignore
warningon this path won't render the refusal text. Capability-gating host enforcement instead would leave every old client fully vulnerable, which defeats the fix — so enforcement is unconditional and the legibility gap is accepted and documented here.issueCommandkeeps its own independent trust path (confirmIssueCommandReadResult), returns only'run' | 'skip', and never passes throughrunHook— verified unchanged, with its suites re-run.Coverage
setup-hook-approval-challenges.test.ts— replay by repo/device/content, expiry, hash disagreement, capacity eviction fails closed, binding reuse refreshes TTL, cross-device eviction isolation, cross-runtime-generation rejection.remote-setup-hook-approval-wire.integration.test.ts— end-to-end oracle over the real wire shapes.orca-runtime.test.ts— exact paired approval runs, old client without one is skipped, folder workspace mints no token, verified bytes reachrunHook.worktrees-remote-runtime-create.test.ts— old-host downgrade of an approvedinheritwarns and sendsskip.terminal-agent-session-fork.test.ts— the fork path forwards the approval, and declines toskip.setup-hook-create-binding.test.ts— host-canonical content, old/malformed hosts forced to skip, locally suppressed runs surface a warning.Gates
pnpm run typecheck,pnpm run lint,pnpm run check:code-quality:changed(0 new findings incl. React Doctor),pnpm run build:cli,pnpm run build:electron-vite, mobiletsc+oxlint, and all focused desktop + mobile suites — all green. Nomax-linesdisable or bump was added; the fork module was split intoterminal-agent-session-fork-workspace.tsinstead.Follow-ups
Filed as parented children of STA-4532 rather than expanded here, to keep this PR to one invariant:
orca.yamlchanges.orca.yaml(including over SSH) so branch-specific hooks are usable — today they hash the primary tree and fail closed.🤖 Generated with Claude Code