Skip to content

fix(runtime): write mobile dismissal state without blocking the main thread - #24029

Closed
LDH1103 wants to merge 4 commits into
stablyai:mainfrom
LDH1103:fix/async-dismissal-store-write
Closed

LDH1103 wants to merge 4 commits into
stablyai:mainfrom
LDH1103:fix/async-dismissal-store-write

Conversation

@LDH1103

@LDH1103 LDH1103 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

ELI5

Every time an agent sends a notification, Orca saves a small "which mobile alerts were dismissed" file. On Windows that save ran a permission tool (icacls) and made the whole window wait for it. On a slow or busy machine the window froze, and a few times it never came back. This PR does that save in the background instead.

What Changed

Before: MobileNotificationDismissalStore.record() runs on every notification dispatch and dismiss, on the main process. It called writeSecureJsonFile, which on Windows spawns icacls synchronously at least twice per save (verify the staged file, verify the published file), and up to eight times when the ACL has to be rewritten. While those spawns ran, every pending IPC reply waited, so the window stopped responding (the mechanism described in #20497).

After:

  • record() updates the in-memory entries immediately and schedules the write. It no longer blocks on disk or on icacls.
  • Writes are serialized and coalesced: at most one write is in flight, and records that arrive meanwhile are folded into one follow-up write of the latest entries.
  • A failed write logs the same warning as before and is retried by the next record().
  • New writeSecureJsonFileAsync (src/shared/secure-file-async-write.ts) keeps the existing order of writeSecureFile — write a temp file, restrict it, rename, then restrict the published path — but awaits icacls through the existing async lane (bestEffortRestrictWindowsPath) instead of runProcessSync. POSIX keeps chmod 0600.
  • secure-file.ts only exports two existing internals (hardenSecurePathOnce, rememberHardenedPath) so the async writer shares the same directory and file hardening caches.

Why

  • This store is the hottest sync-spawn caller I found in practice: it writes on every agent notification, and the file holds only notification ids, sequence numbers, and expiry times, not credentials.
  • Making the one hot caller async is small and low risk. Converting writeSecureJsonFile itself would touch every credential store and their callers at once.
  • Alternative considered: keep the sync write and run icacls without stdio pipes, on the theory that a pipe held open by another process kept spawnSync waiting past its 5s timeout (see Evidence). I could not prove that theory, so this PR only removes the blocking call from the hot path.

Evidence (Windows 11, Orca 1.4.211, antivirus + DLP agent installed): the window stopped responding three times in one day (11:18, 12:03, 14:27). Each time, %APPDATA%\Orca held a leftover mobile-notification-dismissals.json.<pid>.<ts>.tmp and %TEMP% held a matching orca-acl-<same pid>-*.sddl, written within a second of each other. The main thread sat idle at ~0% CPU, and no icacls.exe process remained, so verifySync → runProcessSync never returned, even past ACL_TIMEOUT_MS. Only killing the main process recovered. On the same machine, the unmodified store's unit tests spend ~3.5s inside three synchronous record() calls.

Tradeoff: a dismissal recorded in the last moment before quit may not reach disk. The store already treats missing history as "not dismissed", so the worst case is that a mobile alert the user already dismissed shows once more after a restart. flush() is available if a shutdown path should await it.

Linked Issue

Part of #20497. This fixes one sync-spawn call site. The other sites listed there are unchanged, and getCurrentWindowsUserSid still runs whoami synchronously once per process.

Related symptom reports: #11363, #7175

Visual Proof

N/A: no UI change. The difference is that the window keeps responding while notifications are recorded.

Testing

  • vitest run on the changed suites (mobile-notification-dismissal-store, mobile-notification-dismissal-read-failure, secure-file): 41 passed, 3 POSIX-only skipped on Windows

  • New tests:

    • record() returns before anything reaches disk, three records during an in-flight write produce exactly two writes, and the latest state is persisted
    • a failed write is retried with the latest entries on the next record
    • the async secure write never calls runProcessSync for ACLs, restricts the staged .tmp before the published path, returns false when the ACL apply fails, removes the staged file when the rename fails, and publishes 0600 on POSIX
  • Regression check: with the store change reverted, the new "records without waiting on disk" test fails (the file is written synchronously).

  • pnpm run typecheck, oxlint, oxfmt --check, and pnpm run check:code-quality:changed pass.

  • Platforms: Windows 11 locally. The POSIX-only test is skipped on Windows and will run in CI. This machine has no Visual Studio build tools, so native modules could not be rebuilt: pnpm build and the pnpm test wrapper are left to CI, and I ran vitest directly.

  • I manually tested these changes locally

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

Not manually tested in a packaged build: the freeze depends on host timing (antivirus/EDR holding the spawn), and I could not reproduce it on demand. The unit tests cover the mechanism instead.

AI Disclosure

Investigation, implementation, and tests were done with Claude Code (Claude Opus 5.5) and reviewed by me before submitting.

Review

AI self-review summary:

  • Cross-platform: Windows goes through the existing async icacls lane. POSIX uses fs.promises.chmod. Paths use node:path.
  • SSH / remote / local: the store runs in the desktop runtime and writes to local userData only. No wire or RPC change.
  • Agents / integrations: notification events are unchanged. Only when they are persisted changes.
  • Performance: removes 2–8 synchronous process spawns per notification from the main thread. Bursts coalesce into at most two writes.
  • Security: keeps restrict-before-publish ordering, returns false on a failed ACL apply, and records retry-budget success only on success, like the sync path. Persisted content is not a credential.

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, cross-platform, SSH, mobile, and backwards-compatibility impact are considered above. The on-disk format is unchanged.

Checklist

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

…thread

MobileNotificationDismissalStore.record() runs on every notification
dispatch and dismiss. It persisted through writeSecureJsonFile, which on
Windows spawns icacls synchronously two to eight times per write, so every
notification stalled the main process and all pending IPC replies.

Record into memory immediately and persist asynchronously, with at most
one write in flight and later records coalesced into one follow-up write
of the latest entries. A failed write is logged and retried by the next
record.

Add writeSecureJsonFileAsync, which keeps writeSecureFile's
restrict-before-publish order but awaits icacls through the existing
async ACL lane instead of runProcessSync.

Part of stablyai#20497
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Moves notification dismissal writes from sync to async.

The PR appears safe to merge under its stated best-effort persistence contract.

Summary

The PR moves mobile notification dismissal writes off the synchronous notification path. It adds an async secure-file writer and serializes and coalesces writes, with tests for persistence and file restrictions.

Reviews (1) · Last reviewed commit: "fix(runtime): write mobile dismissal sta..."

@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

  • Async, coalesced persistence in MobileNotificationDismissalStore — record() now updates in-memory entries immediately and schedules a serialized write (persisting/persistAgain), instead of calling writeSecureJsonFile synchronously; new flush() exposes the in-flight promise.
  • New writeSecureJsonFileAsync — mirrors writeSecureFile's restrict-before-publish order but awaits the existing async icacls lane (bestEffortRestrictWindowsPath) and POSIX chmod 0600, removing the synchronous icacls spawn from the notification hot path (#20497).
  • secure-file.ts internals exported — hardenSecurePathOnce and rememberHardenedPath are now exported so the async writer shares the same directory/file hardening caches.
  • Tests — store coalescing (three records during an in-flight write → exactly two writes, latest state persisted), failed-write retry on next record(), async writer ordering/failed-ACL/rename-cleanup/POSIX mode, and the read-failure test now awaits flush().

The concurrency is sound: entries is replaced rather than mutated, so each write stringifies a stable snapshot, and no record() can slip between the while (persistAgain) check and persisting = null (same synchronous turn). Write errors are caught inside persistLatest, so the promise never rejects and there is no unhandled rejection. The restrict-before-publish ordering and return/caching semantics (record success only, no retry-budget throttle — matching the sync write path) are preserved.

ℹ️ Dismissal recorded in the last moment before quit can still be lost

The PR body already accepts this tradeoff, and the impact is a dismissed mobile alert reappearing once after restart. Worth noting for the next reader: the repository already has a quit barrier that joins sidecar flushes — freezeProfileStateWritesAsync / flushCurrentStateAsync in src/main/persistence/loading-store/ already awaits activeViewPreference.flushAsync(). Routing the dismissal store's flush() through that barrier would close the window, though it needs runtime-controller plumbing, so it is reasonable to defer.

Technical details
# Quit-window dismissal loss

## Affected sites
- `src/main/runtime/mobile-notification-dismissal-store.ts:83` — `flush()` exists but has no production caller.
- `src/main/runtime/runtime-mobile-notification-controller.ts:118` — `dispatch()` records, then returns without awaiting persistence.
- `src/main/persistence/loading-store/profile-state-maintenance.ts:36` and `write-flush-barriers.ts:204` — existing quit barrier already joins `ActiveViewPreference.flushAsync()`.

## Required outcome
- None required; this is an accepted, documented tradeoff. If the window should be closed, a shutdown path must `await` the store's in-flight write before process exit.

## Open questions for the human
- Is a duplicate mobile alert after a quit-window dismissal acceptable long-term, or should the store join the existing flush barrier?

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

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

The dismissal store now persists updated entries with asynchronous secure JSON writes. It can repeat a write when another record arrives during an active write, and it exposes flush() to await persistence. The new writer stages JSON in a restricted temporary file before publishing it. Tests cover file restrictions, publication failures, dismissal history, and persistence retries.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 47e0f

Dismissal history is now saved without blocking the main thread. However, on Windows, a failed permission restriction can still publish the file with broader inherited permissions, and the store does not warn about it. Fix this before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to bbefa

The change remains limited to local notification recovery state and preserves the existing permission-restriction sequence. No new authorization capability was identified. Recording no longer guarantees immediate persistence, so interruption can lose recent dismissal history; Windows permission-failure behavior and production shutdown handling remain incompletely established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The changed write destination is a fixed dismissal-history filename under the configured runtime user-data directory. Notification IDs become JSON values, not destination paths. The demonstrated affected asset is that runtime's local dismissal recovery history.

Trust Boundaries and Controls

  • observed — The writer creates a random-suffixed staging file, attempts restriction before rename, then attempts restriction at the published path. POSIX uses mode 0600. Windows reuses ACL identity and verification rules allowing the current user, SYSTEM, and local Administrators, with the same rules shared by synchronous restriction.
  • observed — Restriction is best-effort, not fail-closed: a false staged Windows restriction result still permits rename, and the store ignores the final boolean. This failure policy predates the PR. The inspected test explicitly expects publication after ACL application failure; it does not establish the effective permissions left on a real Windows host.

Resilience and Maintainability Implications

  • inferred — Interruption or an unretried write failure can lose recent dismissal watermarks, degrading restart recovery rather than changing an authorization decision. The writer attempts staging-file removal on thrown errors, and startup schedules age-gated stale-file cleanup. The inspected controller provides no store-drain operation; process-wide shutdown and overlapping-instance guarantees remain unestablished.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: mobile dismissal-state writes no longer block the main thread.
Description check ✅ Passed The description covers the required sections, explains the change and rationale, links related issues, describes testing and platform limits, and includes the required N/A explanation for visual proof…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

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.

…-store-write

# Conflicts:
#	src/main/runtime/mobile-notification-dismissal-store.ts
…-store-write

# Conflicts:
#	src/main/runtime/mobile-notification-dismissal-store.test.ts
#	src/main/runtime/mobile-notification-dismissal-store.ts
…e test

The dismissal store now persists asynchronously, so the restore test restarts only once the delivery is durable and polls for the persisted retirement instead of reading the file in the same tick.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 50c73681-d79f-443b-a728-191e2dc6bf37
📥 Commits

Reviewing files that changed from the base of the PR and between bbefa08 and 47e0fa2.

📒 Files selected for processing (3)
  • src/main/runtime/mobile-notification-dismissal-store.test.ts
  • src/main/runtime/mobile-notification-dismissal-store.ts
  • src/main/runtime/structured-agent-session-mobile-restore.test.ts

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

@nwparker

Copy link
Copy Markdown
Contributor

The synchronous Windows write cost is a real problem, but closing this implementation as not planned. record() now returns before persistence, and flush() is only used in tests, so an immediate normal exit can forget an already dismissed alert and repeat it after restart. That difference was reproduced with the actual current and proposed stores. Any replacement must preserve acknowledgement/persistence ownership and lifecycle flushing; the broader #20497 remains open.

@nwparker nwparker closed this Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants