Skip to content

fix(agents): pre-accept Claude's workspace trust prompt - #18084

Closed
himichaelroberts wants to merge 9 commits into
stablyai:mainfrom
himichaelroberts:himichaelroberts/claude-preflight-trust
Closed

himichaelroberts wants to merge 9 commits into
stablyai:mainfrom
himichaelroberts:himichaelroberts/claude-preflight-trust

Conversation

@himichaelroberts

@himichaelroberts himichaelroberts commented Sep 2, 2026 •

Copy link
Copy Markdown

ELI5

Starting Claude in a folder it has never seen makes Claude ask "do you trust the files in this folder?" first. Orca already answers that question ahead of time for Cursor, Copilot, and Codex, but nobody had done it for Claude — so Claude just sat there. This teaches Orca to answer it for Claude too.

What Changed

preflightTrust: 'claude' on the claude agent, plus the preset that backs it:

  • markClaudeProjectTrusted writes projects["<realpath>"].hasTrustDialogAccepted into the config the runtime resolver picks — CLAUDE_CONFIG_DIR, else a colocated ~/.claude/.claude.json, else ~/.claude.json — so trust lands in the file the launched agent actually reads.
  • markRemoteClaudeProjectTrusted mirrors it against the remote user's home for SSH launches.
  • Only hasTrustDialogAccepted is set. The sibling hasClaudeMdExternalIncludesApproved is a separate consent about executing external CLAUDE.md includes, and granting it here would approve something the user never saw.

Three things fell out of wiring it up:

  • The IPC handler never awaited the Codex write. The renderer awaits the handler and then launches, so an unawaited write can land after the agent has already read trust. Both the local and remote arms are awaited now.
  • The local preset dispatch existed twice — once in registerAgentTrustHandlers, once in markLocalWorktreeTrusted — and a new preset lighting up in TUI_AGENT_CONFIG would have silently done nothing on the second. Consolidated into applyLocalAgentTrustPreset, with a test that pins an arm for every preset in the union.
  • The per-file mutation queue was Codex-named but keyed only by path. It moves to agent-config-mutation-queue.ts so Claude's read-modify-write shares the lane; Codex call sites keep their name through a one-line re-export. This matters more for Claude than for Codex: ~/.claude.json carries live per-session counters that every running Claude rewrites, so two concurrent worktree creations must not clobber each other's entry.

AgentTrustPreset moves to src/shared/agent-trust-preset.ts. The union had three copies — the main presets, the preload bridge, and TUI_AGENT_CONFIG.preflightTrust — and widening one broke the preload typecheck.

Why

Orca's launch flow injects the prompt or draft via bracketed paste once the TUI is foreground. Claude's trust dialog is already up at that point, so the paste becomes menu input. Same failure as #15859 (Devin) and #11765 (Cursor).

It gets worse when the tab opens in the Chat UI. #16729 removed the terminal↔chat toggle and unmounted its ⌘⇧J fallback, and Claude's folder-trust dialog produces no interactivePrompt — deriveInteractivePrompt emits one only for AskUserQuestion or a PermissionRequest carrying a tool name — so the chat view renders no card and no transcript, with no way back to the terminal to answer. The agent is unreachable. That is #18080; this PR fixes the trust half of it, and the missing toggle is left to that issue.

Why the artifact and not a flag. #15860 skips Devin's prompt with --respect-workspace-trust=false. Claude has no interactive equivalent: claude --help documents the workspace trust dialog as skipped only in non-interactive mode (-p, or non-TTY stdout), and --permission-mode / --dangerously-skip-permissions govern tool approvals, not workspace trust. The artifact route is what Cursor, Copilot, and Codex already use.

Distinct from #13086. That reports the background /usage PTY keystroking through the trust dialog in a session the user never initiated. This writes an artifact for a workspace the user explicitly created, before the agent starts — the existing preflightTrust contract.

openclaude is deliberately excluded. It is a distinct CLI and I have not verified it reads ~/.claude.json. Worth a follow-up.

Linked Issue

Fixes #18080

Related: #15859 / #15860 (Devin, same class), #11765 (Cursor), #10666 (Codex trust vs --inject)

Visual Proof

N/A — no UI surface changes. The observable difference is the absence of a TUI dialog at agent startup, which happens inside the agent's own terminal output.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Ran:

node config/scripts/run-typecheck-projects-in-parallel.mjs   # node + cli + web, clean
oxlint src/ config/                                          # no errors
vitest run --config config/vitest.config.ts <affected trees>  # 12438 passed, 0 failed

New coverage in src/main/agent-trust-presets.test.ts:

  • writes hasTrustDialogAccepted for the realpath
  • preserves unrelated top-level keys, sibling project entries, and the entry it edits
  • does not grant the external-includes consent
  • no-op when trust is already accepted
  • refuses to rewrite a config it cannot parse
  • writes the colocated ~/.claude/.claude.json when that is what Claude reads
  • honors CLAUDE_CONFIG_DIR over the home fallback
  • serializes concurrent writes so neither workspace entry is dropped
  • applyLocalAgentTrustPreset has an arm for every preset in the union

src/main/remote-agent-trust-presets.test.ts covers the SSH write, config preservation, the unparseable-config refusal, and the already-trusted skip. runtime-worktree-agent-startup.test.ts is retargeted onto the consolidated dispatch and adds the claude and no-preset cases.

Platforms actually exercised: macOS (local). Linux/Windows/SSH are covered by unit tests only — the local write goes through writeFileAtomically and node:path, and the remote write goes through the SSH filesystem provider with a path the provider itself resolved, so neither hardcodes a separator or a host.

I did not launch the app to watch the dialog get skipped. Verification is typecheck, lint, and tests.

pnpm build passes (exit 0 — full desktop build plus native macOS targets).

Note: pnpm on this machine ships a broken native-binary placeholder, so every script above was invoked through node .../pnpm/bin/pnpm.mjs or ./node_modules/.bin/* directly rather than the pnpm shim.

AI Disclosure

Written with Claude Code (Claude Opus 5).

Review

Agent code review (Claude Opus 5), against the dimensions CONTRIBUTING.md names.

Cross-platform. No new path assumptions: dirname/join throughout, and the remote arm uses the path its filesystem provider resolved. One knowingly uneven spot — the leaves a present-but-unreadable config untouched test is skipIf-gated to POSIX non-root, because chmod 000 leaves a file readable for root and on Windows Node's chmod only toggles the read-only flag, so the unreadable state cannot be constructed there. The production code is platform-neutral; the test for that branch does not run on Windows CI or in root containers.

SSH / remote / local. Both arms exist and diverge deliberately. The remote arm never consults this process's CLAUDE_CONFIG_DIR (it belongs to the desktop, not the host), probes the host for the colocated ~/.claude/.claude.json that resolveConfigPath honors, and uses isENOENT rather than isDefinitiveAbsence because an error raised on an SSH host crosses the relay rebuilt with the transport's numeric code — a code-only predicate would read a genuine remote ENOENT as indeterminate and the preset would never write over SSH at all. Both arms refuse to overwrite a config they could not read.

Supported agents and integrations. The preset is additive and keyed off TUI_AGENT_CONFIG.preflightTrust, so no other agent's launch path changes. applyLocalAgentTrustPreset dispatches through a map declared satisfies Record<AgentTrustPreset, …>, so a future agent gaining a preset fails to compile rather than silently writing nothing — which is how Claude went unsupported. openclaude is deliberately excluded: it is a distinct CLI and I did not verify it reads ~/.claude.json. No git-provider or integration surface is touched.

Performance. One read-modify-write per workspace creation for a supported agent, serialized per config path, skipped entirely when trust is already accepted. The local arm resolves the launch shell environment through resolveLoginShellEnvironment, which is cached and already warmed by agent detection; on a cold cache it costs one shell spawn on the launch path, and any failure falls back to the process-env resolver.

UI quality. Not applicable — no renderer surface. The observable difference is the absence of a TUI dialog inside the agent's own terminal output.

Security. The write grants folder trust for a workspace the user explicitly created, before the agent starts. It does not touch tool-permission or sandbox policy, and it deliberately does not set the sibling hasClaudeMdExternalIncludesApproved, which is a separate consent about executing external CLAUDE.md includes. A config that fails to parse, reads as binary, or cannot be read is left untouched rather than replaced — that file holds the user's Claude auth and history. Distinct from #13086: this writes an artifact, it does not keystroke through a dialog in a session nobody asked for.

Known and accepted: the read-modify-write is not transactional against the agent's own process, so a write landing between this read and this write is lost. That predates this PR and affects all five trust writers; it is tracked in #18092 rather than patched here, because a single-writer fix would be an inconsistent concurrency mechanism. Reviewers who would rather see it fixed in this PR should say so — the compare-and-abort variant applies to all five writers in about 25 lines.

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.

Notes

  • Security. The write grants folder trust for a workspace the user explicitly created, before the agent starts. It does not touch tool-permission or sandbox policy, and it deliberately does not set hasClaudeMdExternalIncludesApproved. A config that fails to parse is left untouched rather than overwritten, because that file holds the user's Claude auth and history.
  • Cross-platform. No new path assumptions; dirname/join throughout, and the remote arm uses the path the SSH provider resolved.
  • Remote SSH. Covered by the remote arm; the local CLAUDE_CONFIG_DIR is deliberately not consulted for remote hosts, since it belongs to the desktop process.
  • Mobile. No mobile surface touched.
  • Backwards compatibility. No wire or RPC change. The preload markTrusted param widens from three preset values to four, which is additive; an older preload paired with a newer main simply never sends 'claude'.
  • Performance. One read-modify-write per workspace creation for a supported agent, serialized per config path, skipped entirely when trust is already accepted.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

himichaelroberts and others added 2 commits September 2, 2026 00:42
Launching Claude in a directory Claude Code has not seen leaves the agent
sitting on its "Do you trust the files in this folder?" dialog. Orca already
pre-writes trust artifacts for Cursor, Copilot, and Codex via `preflightTrust`,
but `claude` and `openclaude` had no preset, so the dialog eats Orca's first
keystrokes the same way stablyai#15859 (Devin) and stablyai#11765 (Cursor) describe.

It is worse than a stalled paste when the tab opens in the Chat UI. stablyai#16729
removed the terminal-chat toggle and unmounted its Cmd+Shift+J fallback, and
Claude's folder-trust dialog produces no `interactivePrompt` —
`deriveInteractivePrompt` only emits one for `AskUserQuestion` or a
`PermissionRequest` carrying a tool name — so the chat view renders no card and
no transcript, with no way back to the terminal to answer. Reported as stablyai#18080.

Adds `preflightTrust: 'claude'`, writing
`projects["<realpath>"].hasTrustDialogAccepted` in the config the runtime
resolver picks (CLAUDE_CONFIG_DIR, else a colocated ~/.claude/.claude.json,
else ~/.claude.json), plus the SSH mirror against the remote user's home. Only
that one flag is set: the sibling `hasClaudeMdExternalIncludesApproved` is a
separate consent about executing external CLAUDE.md includes.

The Devin flag pattern does not transfer — `claude --help` documents the
workspace trust dialog as skipped only in non-interactive mode, and
`--permission-mode` / `--dangerously-skip-permissions` govern tool approvals,
not workspace trust. Distinct from stablyai#13086: this writes an artifact for a
workspace the user explicitly created, before the agent starts, rather than
keystroking through a dialog in a session nobody asked for.

Three things fell out of wiring it up:

- The IPC handler never awaited the Codex write, so the renderer could launch
  before trust landed. Both local and remote arms are awaited now.
- The local preset dispatch existed twice — once in the IPC handler, once in
  `markLocalWorktreeTrusted` — and Claude would have silently done nothing on
  the second. Consolidated into `applyLocalAgentTrustPreset`, with a test that
  pins an arm for every preset in the union.
- The per-file mutation queue was Codex-named but keyed only by path, so it
  moves to `agent-config-mutation-queue.ts` and Claude's read-modify-write of a
  config every running Claude rewrites shares the lane. Codex call sites keep
  their name through a one-line re-export.

`AgentTrustPreset` moves to `src/shared/` so the presets, the preload bridge,
and `TUI_AGENT_CONFIG.preflightTrust` stop keeping three copies of the union.

`openclaude` is deliberately left out: it is a distinct CLI and I have not
verified it reads `~/.claude.json`.

Also fixes a latent leak in worktree-creation-flow.test.ts, where one test's
never-resolving `markTrusted` outlived it and hung every later launch whose
agent gained a preset.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds Claude as an agent trust preset. Local handling resolves Claude’s active configuration file, preserves valid data, and serializes concurrent writes. Remote handling selects and updates the remote Claude configuration defensively. IPC and worktree startup use centralized preset dispatch. Shared types now include Claude across main, preload, and agent configuration code. Tests cover local, remote, startup, queue, runtime mocks, and renderer behavior.

Merge Risk: 🔵 Low · up to 1259d

The PR pre-accepts Claude workspace trust before launch, but one startup path can still show the trust prompt and configured directories with leading or trailing whitespace can update the wrong file; an unexpected configuration shape may also be replaced. The change is mergeable with explicit owner awareness and follow-up on these bounded cases.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.62% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 18 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy the trust-preacceptance objective in #18080 by adding Claude preflight trust, resolving the correct local and remote configuration, awaiting writes, and adding coverage. Terminal/c…
Out of Scope Changes check ✅ Passed The changes remain focused on Claude workspace trust pre-acceptance and its supporting dispatch, typing, serialization, remote handling, and tests. No unrelated code changes are evident.
Description check ✅ Passed The description is complete and relevant. It includes the required ELI5, change summary, rationale, linked issue, visual-proof explanation, testing details, AI disclosure, review considerations, bound…
Title check ✅ Passed The title clearly and concisely identifies the primary change: pre-accepting Claude's workspace trust prompt.
Full details: Linked Issues check

Explanation

The changes satisfy the trust-preacceptance objective in #18080 by adding Claude preflight trust, resolving the correct local and remote configuration, awaiting writes, and adding coverage. Terminal/chat switching remains explicitly separate work.

Full details: Description check

Explanation

The description is complete and relevant. It includes the required ELI5, change summary, rationale, linked issue, visual-proof explanation, testing details, AI disclosure, review considerations, boundary checklist, notes, and completion checklist.


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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 395bdfd1-299d-43bc-89f8-f306c65176e9

📥 Commits

Reviewing files that changed from the base of the PR and between 266b2ea and cdd7e78.

📒 Files selected for processing (16)
  • config/tsconfig.cli.json
  • src/main/agent-config-mutation-queue.test.ts
  • src/main/agent-config-mutation-queue.ts
  • src/main/agent-trust-presets.test.ts
  • src/main/agent-trust-presets.ts
  • src/main/codex/codex-trust-config-mutation-queue.ts
  • src/main/ipc/agent-trust.ts
  • src/main/remote-agent-trust-presets.test.ts
  • src/main/remote-agent-trust-presets.ts
  • src/main/runtime/runtime-worktree-agent-startup.test.ts
  • src/main/runtime/runtime-worktree-agent-startup.ts
  • src/preload/api/agent-status-api.ts
  • src/preload/api/agent-trust-bridge.ts
  • src/renderer/src/lib/worktree-creation-flow.test.ts
  • src/shared/agent-trust-preset.ts
  • src/shared/tui-agent-config.ts

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

Comment thread src/main/remote-agent-trust-presets.ts Resolved
Comment thread src/main/remote-agent-trust-presets.ts Resolved

@pullfrog pullfrog 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.

Important

The SSH arm of the Claude trust preset hardcodes ~/.claude.json and does not mirror the local resolver's colocated ~/.claude/.claude.json fallback, so on remote hosts where Claude reads the colocated config the trust write is a silent no-op.

Reviewed changes

This PR pre-accepts Claude Code's first-launch "do you trust this folder?" dialog by writing projects["<realpath>"].hasTrustDialogAccepted into the config the launched agent reads, and consolidates the trust-preset plumbing.

  • Shared AgentTrustPreset union — 'cursor' | 'copilot' | 'codex' | 'claude' moved to src/shared/agent-trust-preset.ts, now referenced by the main presets, the preload bridge, and TUI_AGENT_CONFIG.preflightTrust.
  • markClaudeProjectTrusted / markRemoteClaudeProjectTrusted — local and remote arms set only hasTrustDialogAccepted, preserving unrelated keys and refusing to rewrite unparseable config.
  • Consolidated dispatch (applyLocalAgentTrustPreset) — replaces the duplicated preset branching in registerAgentTrustHandlers and markLocalWorktreeTrusted.
  • Generalized mutation queue — runExclusivelyForCodexTrustConfig becomes runExclusivelyForAgentConfigFile, now shared by Claude's .claude.json writes (Codex keeps its name via a re-export).
  • IPC handler awaits the Codex/Claude writes — the renderer awaits the handler then launches, so an unawaited write can no longer land after the agent reads trust.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/remote-agent-trust-presets.ts Resolved
Comment thread src/main/agent-trust-presets.test.ts Resolved
@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@pullfrog pullfrog 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.

ℹ️ No new issues in this delta.

Reviewed changes

This delta adds a satisfies PreloadApi['agentTrust'] assertion (plus its type-only import) to agent-trust-bridge.ts, pinning the bridge's markTrusted shape to the declared AgentTrustApi contract — consistent with the satisfies PreloadApi[...] pattern used across the other preload bridges.

  • Type-level pin on the trust bridge — no behavioral change; ipcRenderer.invoke already satisfied the Promise<void> return type.

The two findings from the prior review are unchanged by this commit and remain open: the SSH arm's colocated ~/.claude/.claude.json fallback gap, and the hardcoded preset list in the exhaustiveness test. I did not approve because those threads are still unresolved.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Four findings from CodeRabbit and pullfrog, all real:

- The remote arm could destroy a live config. `readRemoteTextFile` flattens a
  transport error, a permission denial, and a binary read all into `''`, which
  is indistinguishable from an absent file — so an unreadable `.claude.json`
  looked empty and got replaced, discarding the remote user's Claude
  credentials, history, and MCP servers. `readRemoteClaudeConfig` now probes
  existence with `stat` first and refuses to write over anything it cannot
  parse.
- The remote arm had no serialization. The local write takes the per-file lane
  precisely because `.claude.json` carries counters every running Claude
  rewrites; the remote one did not, so two workspace creations on one host
  could write stale snapshots and drop each other's entry — leaving that launch
  still facing the dialog this preset exists to skip. It now takes the same
  lane, keyed by host so separate connections don't serialize against each
  other.
- The remote arm hardcoded `~/.claude.json` and ignored the colocated
  `~/.claude/.claude.json` that `resolveConfigPath` honors. That fallback is a
  filesystem condition on the host, so on any SSH host whose Claude reads the
  colocated file the write was a silent no-op. Probed on the remote now.
- The exhaustiveness test asserted a guarantee it did not provide: the preset
  list was hardcoded, so a fifth preset would have left it green with no
  dispatch arm, and `readdirSync(...).length > 0` passed on any file landing in
  home. The guard moves into production code as a
  `satisfies Record<AgentTrustPreset, …>` writer map — a new preset now fails to
  compile (TS2741). The test derives from the same union and asserts the
  specific artifact per preset.

Worth recording: the first attempt at that guard was a bare `switch` on the
strength of `typescript/switch-exhaustiveness-check`. Widening the union to
prove it fired showed oxlint is not type-aware across modules and the rule said
nothing, so the comment claiming compile-time safety would have been false.
`satisfies Record` is verified to fail — the comment says so and names why the
switch does not.

Also closes a gap neither bot flagged inline but CodeRabbit's merge-risk note
did: the local preset resolved the config through this process's
`CLAUDE_CONFIG_DIR`, but agents run in a PTY whose profile-loading shell may
export a different one — a GUI-launched Electron never sourced those rc files.
Trust would land in a file the session never opens and the dialog would still
fire, silently. It now resolves through `resolveLoginShellEnvironment`, the same
primitive the structured session runtime uses for boot env, falling back to the
process-env resolver on any failure.

The runtime test harness mocked the three per-preset writers but not the
consolidated dispatch, so `markLocalWorktreeTrusted` was calling `undefined`
and the swallowing catch hid it. The mock delegates through the dispatch now,
preserving the existing artifact and call-order assertions, and registers a
Claude writer so a Claude launch is asserted at that layer too.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@himichaelroberts

Copy link
Copy Markdown
Author

Pushed 7ba5ace611, closing all four inline findings — dispositions are in each thread. Two notes on the non-inline items.

CodeRabbit's merge-risk note flagged that "some launch and account paths may still ... write to a different configuration than the launched session reads." That was real and I've fixed it. markClaudeProjectTrusted resolved the config through this process's CLAUDE_CONFIG_DIR, but agents run in a PTY whose profile-loading shell may export a different one, and a GUI-launched Electron never sourced those rc files — so for anyone who sets it in their shell rc, trust landed in a file the session never opens and the dialog still fired. It now resolves through resolveLoginShellEnvironment (the primitive structured-agent-session-runtime already uses for boot env), falling back to the process-env resolver on any failure, so the worst case is the pre-existing behavior. Covered by a test that asserts the launch-shell dir wins and the home fallback is left untouched.

I checked the account paths too: Orca deliberately does not swap CLAUDE_CONFIG_DIR per account (global-settings-types.ts:287 — it persists only per-account auth so switching doesn't fork Claude's session context), and applyClaudeEnvPatch is only used by the rate-limit PTY and commit-message generation, not interactive launches. So there's no managed-home mirror needed here, unlike Codex.

Docstring Coverage (40% vs 80%) — declining. Every exported function and non-obvious branch in this diff carries a JSDoc block explaining why. The shortfall is inline arrow functions in the writer map and per-preset test helpers, where this repo's AGENTS.md is explicit: "Concise/Brief Non-obvious Comments ONLY — DO NOT: be verbose, explain the obvious ... BE CONCISE. 1 LINE if possible." Adding docstrings to cursor: async (workspacePath) => markCursorWorkspaceTrusted(workspacePath) to reach a percentage would violate the repo's stated convention, so I'd rather leave the threshold unmet than add noise a reviewer has to skim past. Happy to reconsider if a maintainer wants the threshold honored over the style guide.

Still blocked on CI. PR Checks and PR test LoC are both action_required — the fork-PR gate — and approving needs admin (403 Must have admin rights to Repository). No substantive CI has run on any head of this PR yet; the only green check is track-community-pr, which runs on the base. A maintainer needs to click Approve and run workflows. Note that as a first-time contributor every push re-gates it, so it's worth approving once the review threads settle.

Local verification on 7ba5ace611: full typecheck clean across node/cli/web, oxlint src/ config/ no errors, 7,357 tests passing in the affected trees. One pre-existing failure on main is unrelated — src/main/rate-limits/codex-fetcher-pty-settle.test.ts fails identically with this branch's changes stashed.

@pullfrog pullfrog 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.

Important

The remote read-modify-write has a data-loss path when stat fails for a non-ENOENT reason.

Reviewed changes

This delta closes the two findings from the prior review and hardens the Claude trust write.

  • Local config path now resolved from the login shell's environment — resolveClaudeLaunchConfigPath consults resolveLoginShellEnvironment for CLAUDE_CONFIG_DIR (the env the launched PTY actually inherits) and falls back to ClaudeRuntimePathResolver, so the write lands in the file the launched agent reads.
  • Compile-time exhaustive local dispatch — applyLocalAgentTrustPreset routes through LOCAL_TRUST_PRESET_WRITERS, declared satisfies Record<AgentTrustPreset, …>, so widening the union fails at compile time (a bare switch was probed and found not to catch it under oxlint).
  • Remote arm mirrors the colocated fallback and takes the mutation-queue lane — resolveRemoteClaudeConfigPath probes ~/.claude/.claude.json on the host, and the read-modify-write serializes under runExclusivelyForAgentConfigFile keyed ${connectionId}\0${configPath}.
  • Remote read separates "unreadable" from "absent" — readRemoteClaudeConfig probes existence before reading so a transport/permission/binary failure is not silently treated as an empty config.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/remote-agent-trust-presets.ts Resolved
The existence probe added in 7ba5ace reintroduced the very defect it closed.
`stat` rejects on absence *and* on transport resets and permission denials, and
a bare `catch` mapped all of them to `exists = false`, which returns `{}` and
writes a fresh config over a live remote `~/.claude.json` — discarding the
remote user's Claude auth, history, and MCP servers. The function's own comment
claimed to prevent exactly that.

Both conflation sites now use `isENOENT`, the repo's helper for this, which
also matches on message text because an error raised on an SSH host crosses the
relay and is rebuilt with the transport's numeric code:

- `readRemoteClaudeConfig` returns `{}` only on a confirmed ENOENT and
  `'unreadable'` otherwise, so the write aborts.
- `resolveRemoteClaudeConfigPath` falls back to `~/.claude.json` only on a
  confirmed ENOENT. A non-ENOENT probe failure returns null and the caller
  bails, because guessing there could merge trust into a file the session never
  reads — a silent no-op that leaves the dialog firing.

The test helper had the same bug in miniature: `statOnly` threw a bare
`Error('missing')` to model absence, which under `isENOENT` is a transport
failure, so the existing coverage would have exercised the wrong branch. It
throws an ENOENT-coded error now, and two tests pin the new arms — a
non-absence failure on the config path, and one on the colocated probe.

Reported by pullfrog on stablyai#18084. Its check-run read `conclusion=success` with
the summary "The Pullfrog run finished successfully", which means the run
completed, not that it found nothing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/remote-agent-trust-presets.ts (1)

174-174: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Protect the remote Claude config from external writers.

runExclusivelyForAgentConfigFile serializes Orca calls only. markRemoteClaudeProjectTrusted reads the remote config at line 175 and writes the stale snapshot at line 195. A running remote Claude process may update the same file between these operations, so this write can discard its changes. Use a remote conditional update that detects file changes and retries or aborts.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: ad3cf1d1-3870-4528-abc7-80a78cdcde7f

📥 Commits

Reviewing files that changed from the base of the PR and between 7ba5ace and 462c56d.

📒 Files selected for processing (2)
  • src/main/remote-agent-trust-presets.test.ts
  • src/main/remote-agent-trust-presets.ts

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

@himichaelroberts

Copy link
Copy Markdown
Author

@coderabbitai on the outside-diff finding at remote-agent-trust-presets.ts:174 ("Protect the remote Claude config from external writers") — deferring this one, tracked as #18092.

You're right about the mechanism, and you're right that the lane doesn't cover it: runExclusivelyForAgentConfigFile is an in-process lane keyed by path, so it stops two Orca worktree creations from racing each other and is blind to an external writer. writeFileAtomically makes the local write atomic but not transactional, so a lost update still happens there too.

Deferring rather than patching, for two reasons.

It predates this PR and affects every preset, not just the new arm. I checked all of them:

writer read write
markRemoteCodexProjectTrusted remote-agent-trust-presets.ts:89 :99
markRemoteCopilotFolderTrusted :133 :151
markRemoteClaudeProjectTrusted :175 :195
markCopilotFolderTrusted agent-trust-presets.ts:84 :108
markClaudeProjectTrusted :183 :211

Fixing only the Claude remote arm would leave four writers exposed and introduce a concurrency mechanism that one of five call sites uses — worse for a reader than the uniform gap.

Every remedy is a contract change. I considered shipping the cheap one — re-read immediately before writing and abort on change — and decided against doing it unilaterally: it narrows the window without closing it, and it should be decided for all five writers at once rather than smuggled in on a Claude PR. A properly preconditioned write needs IFilesystemProvider to grow a conditional write, which is a maintainer's call.

#18092 has the affected-writer table, why the existing guards don't cover it, the impact ranked by file (.claude.json is the worst case — hot, large, and holds oauthAccount), and three remedies with the tradeoffs.

Happy to be overruled: if a maintainer would rather have the compare-and-retry applied to all five writers as part of this PR, say so and I'll do it here.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta closes the one open finding from the prior review: the remote Claude trust write now distinguishes a missing config from an unreadable one, so a transient transport or permission failure aborts the write instead of overwriting a live remote ~/.claude.json.

  • isENOENT-gated config probe — readRemoteClaudeConfig returns {} only on a confirmed ENOENT and 'unreadable' otherwise, and resolveRemoteClaudeConfigPath now returns null (bailing in the caller) when the colocated probe fails for a non-absence reason rather than guessing the home path.
  • Test helpers model absence faithfully — makeFsProvider/statOnly now throw an ENOENT-coded error (matching how the SSH relay rebuilds remote errors), and two new tests pin the non-absence abort arms for both the config path and the colocated probe.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@himichaelroberts Thanks for the detailed analysis. The deferral to #18092 is reasonable.

The lost-update risk remains valid, but it affects the listed trust-config writers consistently. A Claude-only mitigation would create inconsistent concurrency behavior. A shared solution should define the required IFilesystemProvider conditional-write contract and apply it across all affected writers.


✏️ Learnings added
Learnt from: himichaelroberts
URL: https://github.com/stablyai/orca/pull/18084

Timestamp: 2026-09-02T06:42:49.534Z
Learning: The trust-config mutation queue in `src/main/agent-config-mutation-queue.ts` serializes only in-process mutations and cannot prevent lost updates from external writers. GitHub issue `#18092` tracks a cross-cutting solution for the affected local and remote Codex, Copilot, and Claude trust-config writers; a robust fix may require a conditional-write contract in `IFilesystemProvider`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

…rimitive

The Codex trust path already had the distinction the last commit hand-rolled.
`codex-path-observation.ts` returns present/absent/indeterminate, backed by
`shared/definitive-filesystem-absence.ts`, whose docstring names this exact
caller: "Callers that act on absence -- deleting a mirror, overwriting a
config, clearing a credential -- must be able to tell the two apart, and they
must all agree on where the line is, so this lives in one place rather than
being re-derived per lane."

462c56d re-derived it per lane with `isENOENT`. The local arm now reads through
`observe()`, which also collapses the `existsSync` + `readFileSync` pair into
one call and closes the TOCTOU window between them.

Scope note, stated plainly because the previous commit message would imply
more: this is a robustness and reuse change, not a fix for a demonstrated
destructive path. `existsSync` uses access(F_OK), so it answers true for a
file it cannot read, and the old try/catch already aborted there. Producing
data loss locally needs `stat` to fail non-ENOENT while the following write
succeeds, and on a local filesystem the same permissions govern both -- no
portable repro. It is still the right shape: `observe` also treats EIO and
unrecognised errnos as indeterminate, which is reachable on a network home
directory, and ENOTDIR as absence, which `isENOENT` misses.

The remote arm deliberately keeps `isENOENT` rather than switching to
`isDefinitiveAbsence`. An error raised on an SSH host crosses the relay and is
rebuilt with the transport's numeric code, so a code-only predicate would read
a genuine remote ENOENT as indeterminate and the preset would silently never
write on SSH -- failing safe but useless. Comment added at both sites so the
asymmetry is not read as drift.

A regression test was written for the local path and then removed: it passed
with the fix reverted, so it pinned nothing. Better no test than one that
reports coverage it does not have.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/agent-trust-presets.ts (1)

151-151: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not trim the configured directory path.

Line 151 changes valid directory names that contain leading or trailing whitespace. Claude still uses the original CLAUDE_CONFIG_DIR value, so Orca writes hasTrustDialogAccepted to a different file and the trust dialog remains.

Proposed fix
-    const launchConfigDir = launchEnv.CLAUDE_CONFIG_DIR?.trim()
-    if (launchConfigDir) {
+    const launchConfigDir = launchEnv.CLAUDE_CONFIG_DIR
+    if (launchConfigDir?.trim()) {
       return join(launchConfigDir, '.claude.json')
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: cb6883ac-bd2c-49fc-9b19-6e4b8c319679

📥 Commits

Reviewing files that changed from the base of the PR and between 462c56d and 1259d06.

📒 Files selected for processing (2)
  • src/main/agent-trust-presets.ts
  • src/main/remote-agent-trust-presets.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/remote-agent-trust-presets.ts

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

A directory name may legally carry leading or trailing spaces, and Claude reads
the raw env value, so trimming the value sent the trust write to a file the
session never opens — the dialog fires anyway, with no error. Trim only the
emptiness test, so a whitespace-only setting still falls through to the
resolver while a padded real path is used as given.

Reported by CodeRabbit on stablyai#18084 as an outside-diff comment, so it existed only
in the review body — the inline listing was empty.

Note `ClaudeRuntimePathResolver.getRuntimePaths` trims the value it uses
(`runtime-paths.ts:15`), so the two disagree on a padded directory. This commit
does not change that: the resolver is on the pre-existing local-launch path and
several other callers depend on it. Left as a separate question.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@himichaelroberts

Copy link
Copy Markdown
Author

@coderabbitai on the outside-diff finding at agent-trust-presets.ts:151 ("Do not trim the configured directory path") — fixed in b3cb471cfd, taking your diff as proposed.

Agreed, and it's worth more than its Minor label: a directory name may legally carry leading or trailing spaces, Claude reads the raw env value, and the failure mode is silent — the write succeeds against a path nothing reads, the dialog fires anyway, and nothing errors. Trimming only the emptiness test keeps a whitespace-only setting falling through to the resolver while a padded real path is used as given. The test uses a mkdtemp directory with a trailing space and fails against the trimmed version.

Two notes.

ClaudeRuntimePathResolver.getRuntimePaths trims the value it uses (runtime-paths.ts:15), so it and this path now disagree on a padded directory. I did not change it here: it is pre-existing, on the local-launch path, and has other callers. Flagging it rather than fixing it blind — if a maintainer wants them aligned, the resolver is the one that should move.

Also: this is the second finding of yours that could only be reached through the review body, because the platform would not post it inline. Anyone triaging this PR by listing /pulls/{n}/comments would have seen an empty result both times — the earlier external-writer finding that became #18092 arrived the same way. Not a complaint about your report; just noting where the signal lives, since a green inline listing is not evidence of a clean review here.

While I'm correcting the record: I told you earlier that "every remedy is a contract change" for #18092. That was wrong. FileStat already exposes size, mtime, mtimeMs and ino on both the local and SSH providers, so detecting a concurrent write needs no contract change at all — only a genuinely atomic compare-and-swap would, and that is not reachable against a non-cooperating writer. I have corrected #18092's suggested-direction section accordingly.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Candidate files =='
fd -a '^(agent-trust-presets|runtime-paths)\.(ts|test\.ts)$' src || true
fd -a -i 'filesystem.*\.(ts|tsx)$' src || true

echo '== Outlines =='
ast-grep outline src/main/agent-trust-presets.ts --items all --match 'Claude|resolveClaude|markClaude' || true
ast-grep outline src/main/runtime-paths.ts --items all --match 'ClaudeRuntimePathResolver|getRuntimePaths' || true

echo '== CLAUDE_CONFIG_DIR handling =='
rg -n -C 8 'CLAUDE_CONFIG_DIR|resolveClaudeLaunchConfigPath|markClaudeProjectTrusted' \
  src/main/agent-trust-presets.ts src/main/runtime-paths.ts

echo '== FileStat declarations and usages =='
rg -n -C 5 '\b(interface|type)\s+FileStat\b|\b(size|mtime|mtimeMs|ino)\b' src

Length of output: 18425


🏁 Script executed:

#!/bin/bash
set -u

echo '== Targeted test coverage =='
rg -n -C 10 'trailing space|trailing.*space|CLAUDE_CONFIG_DIR|resolveLoginShellEnvironment' \
  src/main/agent-trust-presets.test.ts || true

echo '== Existing runtime resolver =='
ast-grep outline src/main/claude-accounts/runtime-paths.ts --items all --match 'ClaudeRuntimePathResolver|getRuntimePaths' || true
rg -n -C 10 'CLAUDE_CONFIG_DIR|getRuntimePaths|configPath' \
  src/main/claude-accounts/runtime-paths.ts || true

echo '== FileStat contract =='
rg -n -C 8 '\b(interface|type)\s+FileStat\b|\bFileStat\b' \
  src/main/providers src/shared || true

echo '== FileStat metadata in provider implementations =='
rg -n -C 5 '\b(size|mtime|mtimeMs|ino)\b' \
  src/main/providers/ssh-filesystem-provider.ts \
  src/main/providers/filesystem-provider-contract.ts \
  src/main/local-worktree-filesystem.ts 2>/dev/null || true

Length of output: 24763


@himichaelroberts Confirmed. The fix preserves a non-empty padded CLAUDE_CONFIG_DIR value. It trims only for the emptiness check. The regression test creates a directory with a trailing space and verifies that Orca writes .claude.json in that exact directory.

ClaudeRuntimePathResolver.getRuntimePaths() still trims the process environment value. That is a real pre-existing inconsistency. Keeping that change outside this PR is appropriate.

Your correction for #18092 is also correct with one limit. FileStat provides size and mtime, so a best-effort concurrent-change check needs no new contract. mtimeMs and ino are optional, and the SSH SFTP fallback does not provide them. The metadata cannot provide an atomic compare-and-swap against external writers.

Thanks for the platform visibility detail.

🐇 ✓


✏️ Learnings added
Learnt from: himichaelroberts
URL: https://github.com/stablyai/orca/pull/18084

Timestamp: 2026-09-02T07:02:59.576Z
Learning: `src/main/claude-accounts/runtime-paths.ts` currently trims `process.env.CLAUDE_CONFIG_DIR` in `ClaudeRuntimePathResolver.getRuntimePaths()`. In contrast, `src/main/agent-trust-presets.ts` must preserve a non-empty `CLAUDE_CONFIG_DIR` value from the launched shell verbatim because leading and trailing spaces are valid directory-name characters and Claude reads the raw environment value.

Learnt from: himichaelroberts
URL: https://github.com/stablyai/orca/pull/18084

Timestamp: 2026-09-02T07:02:59.576Z
Learning: For GitHub issue `#18092`, `IFilesystemProvider` already exposes `FileStat.size` and `FileStat.mtime`, so trust-config writers can implement best-effort external-change detection without a contract change. `FileStat.mtimeMs` and `FileStat.ino` are optional, and the SSH SFTP fallback does not provide them. This metadata cannot provide an atomic compare-and-swap against non-cooperating external writers.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: himichaelroberts
URL: https://github.com/stablyai/orca/pull/18084

Timestamp: 2026-09-02T06:42:49.545Z
Learning: The trust-config mutation queue in `src/main/agent-config-mutation-queue.ts` serializes only in-process mutations and cannot prevent lost updates from external writers. GitHub issue `#18092` tracks a cross-cutting solution for the affected local and remote Codex, Copilot, and Claude trust-config writers; a robust fix may require a conditional-write contract in `IFilesystemProvider`.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta brings the local Claude trust write in line with the already-reviewed remote arm by reading the config through the repo's observe() absence primitive, and adds a clarifying comment to the remote arm.

  • Local config read uses observe() — the existsSync + readFileSync pair is replaced so an unreadable config (EACCES/EPERM/EIO) now aborts the write instead of being misread as "no config yet", closing the same data-loss class fixed on the SSH arm in the prior delta.
  • Remote arm comment — documents why isENOENT (message-aware) rather than isDefinitiveAbsence (code-only) is used, since a remote error is rebuilt with the transport's numeric code and a code-only predicate would read a genuine ENOENT as indeterminate.

One informational note, not blocking: the local arm's new indeterminate early-return has no dedicated test, whereas the remote arm's equivalent (readRemoteClaudeConfig → 'unreadable') got two. That's understandable — the local path hits real readFileSync, so simulating EACCES reliably in CI is awkward — but a future refactor could silently re-open the overwrite bug without a test pinning the branch.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta fixes resolveClaudeLaunchConfigPath to use CLAUDE_CONFIG_DIR verbatim.

  • Trim only for the emptiness check — the raw CLAUDE_CONFIG_DIR value is now joined as-is, so a directory name with legitimate leading/trailing spaces no longer routes the trust write to a different path than the session opens. The .trim() call now gates only the "is it empty" test, and a new test pins the padded-directory case.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

pullfrog noted, non-blocking, that the local arm's `indeterminate` early-return
had no test while the remote equivalent had two, so a refactor could silently
re-open the overwrite bug. That gap is real and self-inflicted: an earlier
version of this test was deleted for claiming to prove the fix when it passed
against the pre-`observe()` code too.

It is back with the accurate claim. It does not discriminate `observe()` from
the previous try/catch — both abort — it pins the branch: deleting the
`indeterminate` return makes the run seed an empty config and overwrite the
file, and the test fails. Verified by making exactly that mutation.

Gated to POSIX non-root, because chmod 000 leaves a file readable for root and
on Windows Node's chmod only toggles the read-only flag, so the unreadable
state cannot be constructed there. A test that fails on a Docker CI runner is
worse than none.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@himichaelroberts

Copy link
Copy Markdown
Author

@pullfrog your non-blocking note on the untested local indeterminate branch — addressed in 146b0743fc.

The gap was self-inflicted and worth naming. An earlier version of that test existed and I deleted it, because it passed with the fix reverted and so pinned nothing. You're right that deleting it left the branch unguarded, which is a different problem from the one I was avoiding.

It's back with an accurate claim rather than the one I originally made for it. It does not discriminate observe() from the previous try/catch — both abort, which is why the old test was worthless as a proof of the fix — but it does pin the branch: deleting the indeterminate early-return makes the run seed an empty config and overwrite the file, and the test fails. I verified by making exactly that mutation before committing.

On your point that simulating EACCES in CI is awkward — it is, and the fix is a gate rather than a mock. chmod 000 leaves a file readable for root, and on Windows Node's chmod only toggles the read-only flag, so the unreadable state cannot be constructed on either. The test is skipIf-gated to POSIX non-root; it would otherwise fail on a Docker runner, which is worse than having no test. That does mean the branch is unpinned on Windows CI and in root containers, which I'd rather state than paper over.

For completeness on the earlier coverage question: this head is the first that both you and CodeRabbit have reviewed clean without me pushing over an in-flight run. I did that twice — killing your 1259d06a run mid-flight before it re-dispatched — and I'm holding pushes now rather than starting a ninth round.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta adds the missing test for the local arm's indeterminate early-return, closing the non-blocking note from the prior review.

  • Test pins the unreadable-config branch — leaves a present-but-unreadable config untouched chmods a live ~/.claude.json to 000, asserts the trust write leaves it byte-identical, and is gated to POSIX non-root where the unreadable state is actually constructible. The Why comment is accurate: the test does not discriminate observe() from the old try/catch, but it pins the branch, and I confirmed the code path (EACCES → indeterminate → early return; without it, a seed-empty write would overwrite the file and fail the assertion).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta adds one test to src/main/agent-trust-presets.test.ts.

  • Pinned the local unreadable-config branch — leaves a present-but-unreadable config untouched chmods the config to 000, calls markClaudeProjectTrusted, then asserts the file bytes are unchanged, closing the coverage gap noted in the prior review (the local observe()-based indeterminate early-return had no dedicated test). The test is skipped on Windows (where chmod only toggles read-only) and as root (where chmod 000 still reads), and the comment honestly scopes what it pins: the branch against a seed-empty-on-failed-read regression, not the observe() vs try/catch distinction.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Conflict in runtime-worktree-agent-startup.test.ts: main added host-resolution
and draft-detection suites (stablyai#18294) while this branch rewrote the
markLocalWorktreeTrusted describe onto the consolidated dispatch. Took main's
file whole and re-applied only the dispatch change — the module mock now
provides applyLocalAgentTrustPreset delegating to the per-preset mocks, so
main's await and rejection tests keep asserting through markCodexProjectTrusted
unchanged, plus the claude and no-preset cases from this branch.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta is a merge of origin/main into the branch; no production logic changed since the prior review, and both earlier findings remain resolved.

  • runtime-worktree-agent-startup.test.ts mock rework — the trust-preset mock now delegates applyLocalAgentTrustPreset to the per-preset writers (markClaudeProjectTrusted, markCodexProjectTrusted, etc.), so the claude and no-preset cases assert the concrete writer invoked rather than the consolidated dispatch. The added agent-detection mock models the module the startup file imports.
  • agent-status-api.ts type reconciliation — a main-side AgentStatusIpcPayload → AgentStatusCacheIdentity rename merging in; the PR's AgentTrustPreset typing on AgentTrustApi.markTrusted is unchanged.

I ran the reworked test file directly: 10 tests pass.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

`spawnLocalStartupAndSetupTerminals` in ipc/worktree-remote.ts had its own
per-preset chain with cursor/copilot/codex arms and no default, so a preset
added later — `claude` — resolved from TUI_AGENT_CONFIG, matched nothing, and
silently wrote no trust artifact on that launch path. The `satisfies
Record<AgentTrustPreset, …>` guard added earlier cannot catch this: it proves
the map is complete, not that no hand-rolled chain exists elsewhere.

Found while reading stablyai#15291, which adds a `qoder` arm to this same chain.

Also awaits the write. The old chain called `markCodexProjectTrusted` without
awaiting inside a sync `if`, so `runtime.createTerminal` immediately below
could boot the agent before trust landed — the same race fixed in the IPC
handler earlier in this branch.

Exhaustively checked for other chains: the six renderer call sites all go
through the IPC bridge, `runtime-worktree-agent-startup` has the two already
consolidated, and the direct `markCodexProjectTrusted` calls in
codex-launch-preparation.ts and codex-session-resume-launch.ts are
Codex-specific launch paths that never read `preflightTrust`. This was the last
one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This delta routes the third (and last) hand-rolled trust-preset dispatch — the one in spawnLocalStartupAndSetupTerminals — through the shared applyLocalAgentTrustPreset, closing the silent no-op for Claude on the worktree-create startup path.

  • Worktree-create startup trusts via the shared dispatch — spawnLocalStartupAndSetupTerminals now calls applyLocalAgentTrustPreset(preset, worktree.path) instead of its own cursor/copilot/codex if chain, so the claude preset (and any future preset) writes its trust artifact on this launch path rather than silently writing nothing.
  • Write awaited before the agent boots — the Codex and Claude writes are now awaited before runtime.createTerminal, closing the race the earlier IPC-handler fix addressed but this local path still had.

I confirmed spawnLocalStartupAndSetupTerminals is reached only from createLocalWorktree (the native, non-SSH path), so the local applyLocalAgentTrustPreset dispatch is correct here — the per-preset local writers it replaces were already local-only.

ℹ️ Nitpicks

  • applyLocalAgentTrustPreset's satisfies Record<AgentTrustPreset, …> guard proves the dispatch map is complete, but it cannot catch a future hand-rolled preset chain like the one this commit replaced (this is the third one found). Nothing to change here — flagging only that the guard does not eliminate this failure class.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: #16729 removed the terminal↔chat toggle for all agents; Claude sessions wedge on the folder-trust prompt

1 participant