Skip to content

fix(remote): bind remote setup-hook execution to the exact approved content - #15087

Open
Jinwoo-H wants to merge 1 commit into
mainfrom
aug17-sta4532-remote-hook-trust-binding
Open

Jinwoo-H wants to merge 1 commit into
mainfrom
aug17-sta4532-remote-hook-trust-binding

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1091 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1070
Prod 32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​917 $\color{#cf222e}{\Huge{\mathbf{−}}}$​220 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​697

Problem

An authoritative Orca host would 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 of two different files at two different times, so nothing proved they saw the same bytes.

Concretely, on main today:

  • A shared orca.yaml that changes between the client's prompt and the host's create runs unapproved content.
  • A create replayed or re-issued with a different setupDecision runs setup the user never approved for that operation.
  • A client that never prompts at all (the terminal session-fork path passed a hardcoded 'inherit') still got setup executed.
  • The host's own trust payload hashed shared defaultTabs commands even for a local-only repo that would never run them, so the hash did not describe what would execute.

Invariant this defends

For every remotely executed setup hook, the authoritative host must prove that the exact canonical host-derived trust content it is about to execute matches the exact content the user approved for this operation. A mismatch, stale commitment, malformed value, or unverifiable state must never silently run different content or route execution elsewhere.

Approach

The host issues a short-lived (15 min), one-time approval challenge bound to repoId + paired deviceId + 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:

  • Host-derived only. The canonical content comes from getSetupHookTrustContent(repo, yamlHooks) on the host; the client hashes the host-supplied setupTrust.scriptContent, so platform newline divergence is impossible and the client cannot choose what gets hashed.
  • Unspoofable owner. deviceId comes from creatorProvenance, resolved host-side from the RPC context — not from the wire.
  • One-time use, delete-before-validate. consume() removes the token before checking it, so a failed validation cannot be retried.
  • Fail closed, everywhere. Malformed approval, expired/evicted challenge, host restart (new runtime generation), unreadable orca.yaml, or a host without the capability → skip the hook, keep the workspace, surface a warning. Never "run anyway", never route elsewhere.
  • Executes the verified bytes. runHook takes an optional verifiedScript, so the no-runner branch runs what the approval covered rather than re-reading the file after validation.
  • Polling can't starve an approval. Clients re-read repo.hooks on 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.
  • Folder workspaces never mint a token, matching the existing checkRepoHooks refusal — 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.v1 runtime capability. All wire additions are optional RPC fields — no new stream opcodes. Per docs/reference/remote-wire-compatibility.md:

Direction Behavior
New client → old host Client detects the missing capability and downgrades to skip, with a toast explaining why. It does not silently drop the user's choice.
Old client → new host Host enforces. A create with no approval is refused and the refusal is folded into warning, which old clients already surface.
New client → new host Full binding.

Accepted consequence: old desktop clients that ignore warning on 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.

issueCommand keeps its own independent trust path (confirmIssueCommandReadResult), returns only 'run' | 'skip', and never passes through runHook — 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 reach runHook.
  • worktrees-remote-runtime-create.test.ts — old-host downgrade of an approved inherit warns and sends skip.
  • terminal-agent-session-fork.test.ts — the fork path forwards the approval, and declines to skip.
  • Mobile 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, mobile tsc + oxlint, and all focused desktop + mobile suites — all green. No max-lines disable or bump was added; the fork module was split into terminal-agent-session-fork-workspace.ts instead.

Follow-ups

Filed as parented children of STA-4532 rather than expanded here, to keep this PR to one invariant:

  1. Archive hooks still take boolean consent and re-read from the host.
  2. Automations persist a save-time decision across later orca.yaml changes.
  3. Orchestration-created worktrees have no per-operation approval flow (threading provenance without one would make their setup hooks never run).
  4. Mint the challenge against the base-ref committed orca.yaml (including over SSH) so branch-specific hooks are usable — today they hash the primary tree and fail closed.

🤖 Generated with Claude Code

…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.
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 17, 2026 18:37
@Jinwoo-H
Jinwoo-H requested a review from brennanb2025 as a code owner August 17, 2026 18:37
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 8be42

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives strong technical detail, but it omits required template sections and does not provide a Linked Issue, Visual Proof/N/A, checklist, or review notes. Add the required template sections, include a concrete Fixes #... issue link, provide Visual Proof or N/A with a reason, and complete testing, review, checklist, and author fields.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: binding remote setup-hook execution to the exact approved 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 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • 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.

@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

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 lift

Refresh setup-hook approval before create and preserve downgrade warnings.

repo.hooks runs only when the repository changes, but approval tokens expire after 15 minutes and are single-use. Reusing setupTrust.approvalToken can skip the setup hook after expiry or replay. Re-resolve the trust data before the final create and bind it with resolveSetupHookCreate and bindSetupHookCreate.

The current fallback to skip is silent. WorktreeCreateResult also discards the server warning, and onCreated cannot pass it to the session route. Preserve the backend warning and suppressedWarning, 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 win

Add coverage for a host response that omits approvalToken.

setupHookApprovalFromTrust returns undefined when the host sends setupTrust without approvalToken. ensureSetupHookConfirmed then resolves { decision: 'run', approvalRequired: true } with no approval. 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 lift

The trailing setupHookApproval payload depends on a long positional createWorktree signature. Both create paths reach the final options parameter through a long run of positional undefined values. Any inserted parameter shifts the approval payload into a different slot, and the approval then never reaches the host while setup still reports run.

  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork-workspace.ts#L36-L58: replace the 22 positional undefined placeholders 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 win

Type the mock with ConfirmedSetupHook and remove the as never casts.

The inferred return type of mockEnsureSetupHookConfirmed is narrowed to { decision: 'run'; approvalRequired: false }. The fixtures therefore need as never, which disables type checking of the mocked contract. A change to ConfirmedSetupHook would 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 never at 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 value

Scope the test name to the wire contract.

The fake createManagedWorktree decides the marker itself, so line 110 confirms the fake's branch rather than host enforcement. The real evidence is line 109, which proves worktree.create forwards setupHookApproval unchanged. 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 in src/main/runtime/orca-runtime.test.ts.

Also applies to: 107-110


114-120: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Do 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 finally limited 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 readFileSync import.

src/renderer/src/store/slices/worktrees-remote-runtime-create.test.ts (1)

454-460: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Build the argument tuple with a typed helper.

Index 25 is correct for the current createWorktree signature, but a future inserted parameter shifts options without any type error. The second site also casts through as unknown as, which drops type checking on setupDecision. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae6aed and 8be4219.

📒 Files selected for processing (45)
  • mobile/app/h/[hostId]/tasks.tsx
  • mobile/src/components/NewWorktreeModal.tsx
  • mobile/src/tasks/blank-workspace-create.ts
  • mobile/src/tasks/setup-hook-create-binding.test.ts
  • mobile/src/tasks/setup-hook-create-binding.ts
  • mobile/src/tasks/setup-hook-trust.test.ts
  • mobile/src/tasks/setup-hook-trust.ts
  • mobile/src/tasks/source-workspace-create.ts
  • mobile/src/tasks/workspace-create-params.ts
  • mobile/src/tasks/worktree-create-capability.test.ts
  • mobile/src/tasks/worktree-create-capability.ts
  • src/main/effective-hook-config.ts
  • src/main/hooks-effective-hook-resolution.test.ts
  • src/main/hooks.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/remote-setup-hook-approval-wire.integration.test.ts
  • src/main/runtime/rpc/methods/repo.test.ts
  • src/main/runtime/rpc/methods/repo.ts
  • src/main/runtime/rpc/methods/worktree-create-args.ts
  • src/main/runtime/rpc/methods/worktree-schemas.test.ts
  • src/main/runtime/rpc/methods/worktree-schemas.ts
  • src/main/runtime/setup-hook-approval-challenges.test.ts
  • src/main/runtime/setup-hook-approval-challenges.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork-workspace.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts
  • src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/lib/ensure-hooks-confirmed.test.ts
  • src/renderer/src/lib/ensure-hooks-confirmed.ts
  • src/renderer/src/lib/hook-trust-confirmation.ts
  • src/renderer/src/lib/launch-work-item-direct.test.ts
  • src/renderer/src/lib/launch-work-item-direct.ts
  • src/renderer/src/lib/pending-worktree-creation.ts
  • src/renderer/src/lib/worktree-creation-flow.ts
  • src/renderer/src/runtime/runtime-hooks-client.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees-remote-runtime-create.test.ts
  • src/renderer/src/store/slices/worktrees/create/create-worktree.ts
  • src/renderer/src/store/slices/worktrees/create/setup-hook-approval-notice.ts
  • src/shared/protocol-version.ts
  • src/shared/setup-hook-approval.ts
  • src/shared/worktree/create-types.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 9 remain after this review.

Comment on lines +495 to +511
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 ?? ''
}

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.

📐 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 -60

Repository: 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 -160

Repository: 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.ts

Repository: 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.

Comment on lines +77 to +97
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
}

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 | 🟡 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.

Suggested change
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
}

Comment on lines +3744 to +3751
? ensureSetupHookConfirmed(
useAppStore.getState(),
repoId,
'setup',
selectedRepoExecutionHostId ?? undefined,
undefined,
isSubmissionCancelled
)
: Promise.resolve<'skip'>('skip'),
: Promise.resolve({ decision: 'skip' as const, approvalRequired: 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

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

This branch has not been deployed

No deployments
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.

1 participant