Skip to content

fix: keep macOS daemon terminals working after TCC attribution is severed - #20452

Closed
AmethystLiang wants to merge 2 commits into
mainfrom
AmethystLiang/fix-agent-icon-eperm-error
Closed

AmethystLiang wants to merge 2 commits into
mainfrom
AmethystLiang/fix-agent-icon-eperm-error

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​842 $\color{#cf222e}{\Huge{\mathbf{−}}}$​37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​805
Prod 36 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​636 $\color{#cf222e}{\Huge{\mathbf{−}}}$​87 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​549

ELI5

On macOS, when Orca auto-updates, its background helper (the daemon that hosts your terminals) can lose permission to your Documents/Desktop/Downloads folders and start throwing EPERM on everything there — even though Full Disk Access is still granted and a fresh terminal works fine. This PR detects that situation and keeps your terminals working instead of silently breaking.

What Changed

Adds detection for a "severed" TCC attribution on the macOS daemon (a measured folder-access divergence), persists the denial evidence beside the PID record so it survives app relaunch, and changes admission so a severed daemon is either replaced at launch (zero live sessions) or adopted in a degraded in-process PTY fallback mode (live sessions) — never killed out from under running terminals. Also adds the missing NSDesktopFolderUsageDescription usage string, and documents the mechanism and structural fix in docs/reference/macos-daemon-tcc-attribution.md.

Why

Squirrel updates move /Applications/Orca.app out and the new bundle in, leaving the path unresolvable for a moment. A daemon that outlives enough updates eventually has a TCC evaluation land in that window; the denial is cached against the daemon's lineage for its entire lifetime, so every terminal it hosts gets EPERM while the daemon still passes every health probe. Killing the daemon would fix it but drop every live session, so the right behavior is to degrade fresh terminals to in-process attribution and reserve replacement for when nothing is running.

Linked Issue

Fixes #17696 (STA-3491)

Visual Proof

N/A — no visual change. The behavior is process/permission routing; the only user-visible surface is the existing TCC attribution notice string.

Testing

  • Automated tests added/updated: severed-attribution degrade, cwd denial, denial-record persistence, degraded fresh-spawn routing, degraded-fallback lifecycle, local-configure, and updated daemon-init/tcc-attribution suites.
  • Manual macOS validation of the full update-window reproduction pending (requires the launchd harness described in the reference doc).

Platforms: logic is macOS-specific and gated behind runtime checks; other platforms unaffected.

AI Disclosure

Internal contributor — section not applicable.

Review

Agent skill upstream boundary

  • Not applicable — no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation copied or translated.

Notes

Security: no new permissions beyond the required Desktop usage string. Cross-platform: macOS-only behavior behind runtime checks. Remote SSH: execution-host attribution unchanged. Backwards compatibility: denial evidence is additive beside the existing PID record; a replacement daemon starts clean.

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)

…ered

On macOS every access from a daemon-hosted terminal is attributed to the
app that forked the daemon. If an evaluation lands during the updater's
bundle swap the resolution fails and the denial is cached against the
daemon's lineage for its lifetime, so every terminal starts getting EPERM
under Documents/Desktop/Downloads while the daemon still passes health
probes.

Detect the severed attribution via measured folder-access divergence,
persist denial evidence beside the PID record (matched by PID, start time,
and launch nonce) so relaunch does not forget it, and keep live sessions
alive: replace the daemon at launch when idle, otherwise adopt it in
degraded in-process PTY fallback mode. Add the missing Desktop usage
string and document the mechanism and structural fix.

Co-authored-by: den-sj <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c2a4c17e-5644-4d6a-ba54-69369ce43226

📥 Commits

Reviewing files that changed from the base of the PR and between 2d15e561a70dc94b5d09483cffd8096cc2c5b02c and a74171f.

📒 Files selected for processing (9)
  • src/main/daemon/daemon-init-dependency-mocks.ts
  • src/main/daemon/daemon-init-endpoint-adoption.test.ts
  • src/main/daemon/daemon-init-mock-types.ts
  • src/main/daemon/daemon-init-provider-installation.test.ts
  • src/main/daemon/daemon-severed-attribution-degrade.test.ts
  • src/main/daemon/degraded-daemon-fresh-spawn-routing.test.ts
  • src/main/ipc/pty-degraded-fallback-lifecycle.test.ts
  • src/main/ipc/pty/provider/local-configure.test.ts
  • src/main/providers/pty-provider-test-double.ts

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


📝 Walkthrough

Walkthrough

The PR adds TCC attribution states, process identity checks, persisted denial evidence, and ShipIt staging-path classification. It routes fresh PTY spawns through an in-process provider when daemon attribution is severed while preserving live sessions. It adds guarded degradation and recovery callbacks, runtime event tracking, provider lifecycle cleanup, macOS usage metadata, documentation, tests, and updated permission messages.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to a7417

French users can receive obsolete recovery guidance, and some macOS terminal launches can be delayed while preserving live sessions. Resolve these before merge unless the startup delay and untranslated guidance are explicitly accepted.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.90% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 41 functions across 45 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description includes all required sections, explains the macOS TCC attribution problem and solution, links issue #17696, documents testing and platform scope, and marks visual proof as not applica…
Title check ✅ Passed The title clearly and concisely describes the primary change: keeping macOS daemon terminals working after TCC attribution is severed.
Linked Issues check ✅ Passed Issue #17696 requires macOS terminals to start with a readable working directory and allow commands such as ls ... The spawn path detects a diverged daemon CWD, verifies the daemon incarnation, reco…
Out of Scope Changes check ✅ Passed The changes remain within issue #17696. TCC attribution checks, persisted denial evidence, daemon replacement, degraded PTY routing, provider lifecycle changes, configuration, user messages, documenta…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Run ID: cc09523e-667e-4e4b-bf4e-3192e4510cdb

📥 Commits

Reviewing files that changed from the base of the PR and between f2b6434 and 2d15e561a70dc94b5d09483cffd8096cc2c5b02c.

📒 Files selected for processing (48)
  • .gitignore
  • AGENTS.md
  • config/electron-builder.config.cjs
  • docs/reference/macos-daemon-tcc-attribution.md
  • src/main/daemon/daemon-adoption-telemetry-event.ts
  • src/main/daemon/daemon-init-dependency-mocks.ts
  • src/main/daemon/daemon-init-endpoint-adoption.test.ts
  • src/main/daemon/daemon-init-fresh-import.ts
  • src/main/daemon/daemon-init-mock-types.ts
  • src/main/daemon/daemon-init-provider-installation.test.ts
  • src/main/daemon/daemon-init-test-harness.ts
  • src/main/daemon/daemon-provider-init.ts
  • src/main/daemon/daemon-provider-restart.ts
  • src/main/daemon/daemon-provider-state.ts
  • src/main/daemon/daemon-pty-adapter-daemon-recovery.test.ts
  • src/main/daemon/daemon-pty-cwd-denial.test.ts
  • src/main/daemon/daemon-pty-cwd-denial.ts
  • src/main/daemon/daemon-pty-daemon-recovery.ts
  • src/main/daemon/daemon-pty-runtime-state.ts
  • src/main/daemon/daemon-pty-session-spawn.ts
  • src/main/daemon/daemon-replacement-preflight.ts
  • src/main/daemon/daemon-severed-attribution-degrade.test.ts
  • src/main/daemon/daemon-severed-attribution-degrade.ts
  • src/main/daemon/daemon-tcc-attribution-main-thread.test.ts
  • src/main/daemon/daemon-tcc-attribution.test.ts
  • src/main/daemon/daemon-tcc-attribution.ts
  • src/main/daemon/daemon-tcc-denial-record.test.ts
  • src/main/daemon/daemon-tcc-denial-record.ts
  • src/main/daemon/degraded-daemon-fresh-spawn-routing.test.ts
  • src/main/daemon/degraded-daemon-fresh-spawn-routing.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/ipc/pty-degraded-fallback-lifecycle.test.ts
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/pty/kill-all.ts
  • src/main/ipc/pty/provider/bind-listeners.ts
  • src/main/ipc/pty/provider/local-configure.test.ts
  • src/main/ipc/pty/provider/local-configure.ts
  • src/main/ipc/pty/provider/registry.ts
  • src/main/ipc/pty/register-handlers.ts
  • src/main/providers/local-pty-runtime-events.ts
  • src/main/providers/local-pty-session-activation.ts
  • src/preload/api/pty-management-api.ts
  • src/renderer/src/components/settings/TerminalTccAttributionNotice.tsx
  • src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/daemon-adoption-telemetry.test.ts
  • src/shared/daemon-adoption-telemetry.ts

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

@@ -56,6 +56,10 @@ export async function prepareDaemonReplacement(
| undefined
let confirmedReplacement = false
const health = await checkDaemonHealth(socketPath, tokenPath)
const preserveWithAttribution: PreserveDaemon = async (mode) => {
const attribution = await getMacDaemonTccAttributionHealth(runtimeDir, socketPath, tokenPath)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Use evidence-only attribution checks during replacement preflight.

This call can run the two-second codesign diagnostic after recoveryDeadlineMs has expired. A healthy daemon with an unhealthy resolver or stale bundle can therefore delay terminal startup beyond the absolute recovery budget.

This function only acts on severed. Denial evidence establishes that state before diagnostics. Pass evidenceOnly: true here and at Lines 124-128.

Proposed fix
-    const attribution = await getMacDaemonTccAttributionHealth(runtimeDir, socketPath, tokenPath)
+    const attribution = await getMacDaemonTccAttributionHealth(
+      runtimeDir,
+      socketPath,
+      tokenPath,
+      PROTOCOL_VERSION,
+      undefined,
+      true
+    )

Apply the same arguments to the attribution query at Lines 124-128.

📝 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
const attribution = await getMacDaemonTccAttributionHealth(runtimeDir, socketPath, tokenPath)
const attribution = await getMacDaemonTccAttributionHealth(
runtimeDir,
socketPath,
tokenPath,
PROTOCOL_VERSION,
undefined,
true
)

@@ -81,7 +81,7 @@ export function TerminalTccAttributionNotice(props: {
<p className="text-xs leading-snug">
{translate(
'auto.components.settings.TerminalTccAttributionNotice.body',
'The terminal daemon was started by an Orca install that no longer exists, so macOS can’t attribute its commands to Orca — Accessibility and Automation grants are silently ignored (osascript fails with error -25211). Restarting the daemon fixes this; running terminal sessions will close.'
'The terminal daemon reported a folder-access denial for a folder Orca can read. This can happen when macOS stops applying Orca’s permissions to an older daemon. Restarting the daemon may restore access; it will close running local terminal sessions. Save your work first.'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- affected component ---'
sed -n '1,125p' src/renderer/src/components/settings/TerminalTccAttributionNotice.tsx
printf '%s\n' '--- affected hook ---'
sed -n '1,115p' src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts
printf '%s\n' '--- locale files ---'
git ls-files 'src/renderer/src/i18n/locales/*'
printf '%s\n' '--- matching translation keys and values ---'
rg -n -C 2 'folder|daemon|Tcc|tcc|terminal' src/renderer/src/i18n/locales/en.json src/renderer/src/i18n/locales

Repository: stablyai/orca

Length of output: 50370


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 33395


🏁 Script executed:

set -eu
printf '%s\n' '--- translation calls ---'
rg -n -C 3 'translate|folder-access|folder|daemon|Restarting' \
  src/renderer/src/components/settings/TerminalTccAttributionNotice.tsx \
  src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts
printf '%s\n' '--- matching locale values ---'
python3 - <<'PY'
import json
from pathlib import Path

needles = ("folder-access denial", "folder Orca can read", "older daemon", "Restarting the daemon", "Save your work first")
for path in sorted(Path("src/renderer/src/i18n/locales").glob("*.json")):
    data = json.loads(path.read_text())
    hits = []
    def walk(value, parts=()):
        if isinstance(value, dict):
            for key, child in value.items():
                walk(child, parts + (key,))
        elif isinstance(value, str) and any(needle in value for needle in needles):
            hits.append((".".join(parts), value))
    walk(data)
    if hits:
        print(path)
        for key, value in hits:
            print(f"  {key}: {value}")
PY
printf '%s\n' '--- locale inventory ---'
git ls-files 'src/renderer/src/i18n/locales/*.json' | sort

Repository: stablyai/orca

Length of output: 11683


🏁 Script executed:

set -eu
printf '%s\n' '--- translate implementation ---'
rg -n -C 5 'export function translate|function translate|const translate' src/renderer/src/i18n/i18n.ts
printf '%s\n' '--- exact catalog entries ---'
python3 - <<'PY'
import json
from pathlib import Path

paths = [
    ("auto", "components", "settings", "TerminalTccAttributionNotice", "body"),
    ("auto", "hooks", "useMacTccAttributionSeveredNotice", "description"),
]
for path in sorted(Path("src/renderer/src/i18n/locales").glob("*.json")):
    data = json.loads(path.read_text())
    print(path)
    for parts in paths:
        value = data
        present = True
        for part in parts:
            if not isinstance(value, dict) or part not in value:
                present = False
                break
            value = value[part]
        print("  " + ".".join(parts) + ": " + (repr(value) if present else "<missing>"))
PY

Repository: stablyai/orca

Length of output: 2928


Update the French TCC notice translations.

translate uses the catalog value when the key exists. fr.json still contains the previous text for both affected keys, so French users do not receive the new folder-denial and daemon-restart wording. The keys are absent from es.json, ja.json, ko.json, and zh.json, so those locales use the inline fallback as intended.

📍 Affects 2 files
  • src/renderer/src/components/settings/TerminalTccAttributionNotice.tsx#L84-L84 (this comment)
  • src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts#L75-L75

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

Caution

This PR fails its own unit tests on Linux CI. src/main/daemon/daemon-tcc-attribution-main-thread.test.ts has three failing tests because the new inspectMacProcessCodeIdentity probe returns 'unknown' when /usr/bin/codesign is absent — always true on the ubuntu-latest runners that unit-tests.yml uses.

Reviewed changes

  • Severed-attribution detection (daemon-tcc-attribution.ts): verdict type gains at-risk; severed is now only a measured cwd-access divergence, persisted beside the pid record and matched by pid/start/nonce. Missing spawner binary or unresolvable image is at-risk and fails open.
  • Degrade on severed (daemon-severed-attribution-degrade.ts): wraps the installed adapter in DegradedDaemonPtyProvider (fallback = getInProcessPtyProvider()), discovers routes before the swap, and re-checks provider/restart after async discovery.
  • Admission wiring (daemon-pty-session-spawn.ts, daemon-pty-cwd-denial.ts, daemon-pty-daemon-recovery.ts, daemon-replacement-preflight.ts): severed + live sessions preserves and degrades; severed + zero sessions replaces. onSeveredWithLiveSessions fires once.
  • In-process fallback plumbing (registry.ts, kill-all.ts, local-configure.ts, register-handlers.ts, local-pty-runtime-events.ts): a distinct immutable in-process provider, plus a WeakSet so the runtime does not double-deliver events through the degraded wrapper.
  • Docs/packaging: NSDesktopFolderUsageDescription, new TCC reference doc, AGENTS.md section, notice copy, and SHIPIT_STAGING_PATH matching $TMPDIR/*.ShipIt.*.

Verified codesign --verify +<pid> against the codesign(1) man page. Focused suites pass except the one noted above.

ℹ️ Nitpicks

  • daemon-replacement-preflight.ts:139 — the log string for the zero-session severed branch still says spawning app binary no longer exists, but that condition is now at-risk, not severed.
  • pty-listener-teardown-and-orphans.test.ts:325 — the comment says the non-local second window keeps orphan cleanup off (only the renderer-gate reset listener remains), but the assertion was changed to toHaveLength(2) and the in-process sweep is now registered there. Update the comment to match the new behavior.

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

// #17696: the symptom itself outranks a cached intact verdict and every proxy.
writePidRecord('1.2.3', true, 'launch-denied')
await expect(getMacDaemonTccAttributionHealth(dir, socketPath, tokenPath)).resolves.toBe(
'intact'

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.

This test — and the pre-existing 'intact' expectations in 'deduplicates identity inspection by daemon generation…' (line 144) and 'retries an indeterminate identity inspection' (line 179) — fail on Linux CI. beforeAll only fakes process.platform = 'darwin'; it does not provide /usr/bin/codesign, so the default inspectMacProcessCodeIdentity returns 'unknown' and the result is 'unknown', not 'intact'. unit-tests.yml runs on ubuntu-latest and does not exclude this file, so all three tests are red.

Technical details
# Linux CI fails when the default codesign probe is not stubbed

## Affected sites
- `src/main/daemon/daemon-tcc-attribution-main-thread.test.ts:144` — `resolves.toEqual(['intact','intact'])`, but `inspectMacProcessCodeIdentity` returns `unknown` off macOS.
- `src/main/daemon/daemon-tcc-attribution-main-thread.test.ts:179` — existing test, same cause; after `psError.value = null` the health is `unknown`.
- `src/main/daemon/daemon-tcc-attribution-main-thread.test.ts:191` — new test, same cause at the first `intact` assertion.

## Root cause
- `getMacDaemonTccAttributionHealth` now ends with `inspectCodeIdentity(parsedPid.pid)` and the default is `inspectMacProcessCodeIdentity`, whose first guard is `!existsSync('/usr/bin/codesign') => 'unknown'`.
- `existsSync` is a real filesystem call, so faking `process.platform` is not enough on `ubuntu-latest`.
- Confirmed locally: `pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-tcc-attribution-main-thread.test.ts` -> 3 failed / 5 passed.

## Required outcome
- These three tests must assert `intact` deterministically on any host while still exercising the codesign-probe branch that distinguishes `intact`/`at-risk`.

## Suggested approach (optional)
- Pass the injectable probe explicitly, e.g. `const inspect = async () => 'valid' as const` into the calls that expect `intact` (the parameter already exists for exactly this). `at-risk` assertions after `rmSync(spawnerExecPath)` do not reach the probe.

@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 the incremental commit. The Linux-CI test failure flagged in the prior review is unchanged, so the PR is still not mergeable until that is fixed.

Reviewed changes since 2d15e561a7

  • Test-only type-assertion cleanup (a74171feca): adds a typed createPtyProviderTestDouble helper in src/main/providers/pty-provider-test-double.ts and MockSpawner/MockAdapter constructor types, then replaces as unknown as/as never casts across the degraded-fallback, fresh-spawn-routing, local-configure, and daemon-init tests. No production behavior changed; tc:node and the changed-code quality gate are clean, and all touched test suites pass.

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

@RainofTerra

Copy link
Copy Markdown

I am still being hit by this every other upgrade, do you think you will be able to update this soon?

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

Closing as stale: the code it changes no longer exists on main.

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.

macOS terminal cwd becomes unreadable when app and daemon versions are mismatched

2 participants