Skip to content

fix(sta-5781): stop cross-client resets of workspace view preferences - #17057

Merged
Jinwoo-H merged 8 commits into
mainfrom
sta-5781-filter-persistence-race
Aug 28, 2026
Merged

Jinwoo-H merged 8 commits into
mainfrom
sta-5781-filter-persistence-race

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​839 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​839
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​493 $\color{#cf222e}{\Huge{\mathbf{−}}}$​50 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​443

Fixes STA-5781: workspace sidebar filter/ordering settings intermittently reset across desktop/web/mobile clients.

Root cause

The main-process store already merges ui.set field-by-field, but every client wrote multi-field snapshots from possibly-stale mirrors:

  • Mobile (persistViewSettings): any tap pushed a 6-field snapshot from a mirror refreshed only by ui.get on connect/focus. There is no push channel to paired clients, so the mirror is stale by whatever changed since — a tap then deterministically reverted disjoint desktop changes (no timing race; this is the "happens most of the time" report).
  • Desktop/web (usePersistedUIWriter): any single change flushed a ~20-field snapshot after 150ms, reverting concurrent remote writes still in broadcast flight; a broadcast landing inside the debounce window also clobbered the pending local toggle in the mirror.

Fix

Writers persist field-level patches of only what the client changed:

  • Renderer keeps a slice-owned persistedUIWriteBaseline (last hydration overlaid with flushed writes). The debounced writer diffs mirror vs baseline and writes only diverged fields, folding the flush after the ui.set resolves so a failed write self-heals on the next change. Sync hydration preserves unflushed local edits so a broadcast can't revert a pending toggle.
  • Mobile builds its ui.set payload from the touched patch keys only (buildWorkspaceViewSettingsUpdate; supersedes the [Feature]: Display default branch #8873 whole-payload special case).
  • Compile-time guards: satisfies Record<keyof …, true> census on the field list; key-by-key wire build with a same-name/type assertion (a spread is not excess-property-checked and could ship a key the strict paired-host UiUpdate schema would reject wholesale).

Wire compatibility: no schema changes, no new fields — ui.set already accepts partials, so mixed client/host versions interoperate (an old client keeps its old behavior; the fix is client-side by design). Pairing-local field stripping unchanged.

Verification

  • Deterministic cross-client harness (workspace-view-cross-client-sync.test.tsx): real writer hook + real UI slice (under StrictMode) + real main-process merge as authority, controlled broadcast delivery, fake timers. Red ×3 on origin/main, green ×7 on this branch, red ×3 with the fix reverted under the byte-identical test.
  • Unit tests for the baseline module incl. a runtime field census; mutation-verified (the showSleepingWorkspaces inversion mutant and a field-list deletion mutant both fail tests).
  • Real-app Electron E2E on an isolated profile: clicked the actual "Hide default branch" switch, fired a second-client ui.set({hideSleepingWorkspaces:true}) inside the debounce window — both changes survived in the visible switches, store mirror, and durable orca-data.json.
  • Two independent adversarial reviews (correctness + design/perf); all major findings fixed in the follow-up commits. pnpm tc, changed-code quality gates, mobile suite (3785 tests), and the renderer/store/persistence sweeps green.

Known residuals (out of scope, same family)

  • Same-field concurrent edits remain last-writer-wins (inherent for a single toggle; ~150ms true-concurrency window).
  • Mobile trustedOrcaHooks/taskResumeState single-key whole-record replaces need a main-side merge (like mergeContextualTourSeenIds).
  • filterRepoIds is pruned+persisted when a remote/SSH host's repos temporarily leave the catalog.
  • Mobile/web display staleness (pull-only sync) — live reflection needs a capability-negotiated push channel.

Workspace sidebar filter/ordering settings intermittently reset when
multiple clients (desktop, web, mobile) share PersistedUIState. The main
store already merges ui.set field-by-field, but every client wrote
multi-field snapshots from possibly-stale mirrors:

- desktop/web: usePersistedUIWriter debounced a ~20-field snapshot on any
  single change, reverting concurrent remote writes still in broadcast
  flight, and a sync hydration inside the debounce window clobbered the
  pending local toggle in the mirror.
- mobile: persistViewSettings pushed a 6-field snapshot from a ref only
  refreshed by ui.get on connect/focus, deterministically reverting
  disjoint desktop changes on any tap.

Fix: writers now persist field-level patches of only what the client
changed. The renderer keeps a slice-owned write baseline (last hydration
overlaid with flushed writes); the debounced writer diffs mirror vs
baseline, and sync hydration preserves unflushed local edits so a
broadcast can't revert a pending toggle. Mobile builds its ui.set payload
from the touched patch keys only (supersedes the #8873 whole-payload
special case). No wire changes: ui.set already accepts partial updates,
so mixed client/host versions remain compatible.

Deterministic cross-client harness drives the real writer hook, UI slice,
and main-process merge with controlled broadcast delivery; red on the
previous writers, green now.
- Exhaustiveness-guard the baseline field list with the satisfies-Record
  pattern (a plain keyof[] satisfies never checks coverage, so a new field
  could silently stop persisting).
- Build the wire update key-by-key with a compile-time same-name/type
  assertion instead of a spread, which is not excess-property-checked and
  could ship a mirror-named key that the strict paired-host UiUpdate
  schema would reject wholesale.
- Fold the flush into the baseline only after ui.set resolves; a rejected
  write now leaves its fields dirty and self-heals on the next change
  (before, a failed write was permanently lost).
- Read the baseline via getState instead of a selector so remote
  broadcasts can neither re-render the writer nor re-arm its debounce;
  the timer re-diffs against the latest baseline at fire time.
- Map workspaceStatuses in the mobile builder so a future
  persistViewSettings patch of it cannot silently send nothing.
- Add direct unit tests for the baseline module and document the
  capture-before-overlay ordering in hydratePersistedUI.
- Pin the showSleepingWorkspaces mirror->wire inversion end-to-end from
  the desktop writer (its mutant survived the whole suite).
- Runtime census: the writer field list must match an independently
  maintained full baseline literal, so a dropped field fails vitest,
  not only tc.
- Mount the harness writer under StrictMode like the real renderer.
- Document the width-sanitizer/getPersistedUI clamp coupling that keeps
  baseline capture safe.
@greptile-apps

greptile-apps Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR changes workspace-view preference persistence so desktop, web, and mobile clients send field-level updates rather than stale multi-field snapshots.

  • Adds a renderer-owned baseline, in-flight tracking, and hydration overlay to preserve pending local edits across host broadcasts.
  • Adds acknowledged web persistence behavior so failed writes are not folded into the renderer baseline.
  • Converts mobile workspace-view writes to touched-field patches and adds unit and cross-client synchronization coverage.

Confidence Score: 5/5

The PR appears safe to merge because no blocking failure remains.

No blocking failure remains.

Important Files Changed

Filename Overview
src/renderer/src/app-shell/use-persisted-ui-writer.ts Replaces whole-snapshot writes with debounced field diffs, acknowledged settlement, and trailing reconciliation.
src/renderer/src/store/slices/persisted-ui-write-baseline.ts Defines the persisted-field census, baseline capture, equality-aware diffing, and wire-payload conversion.
src/renderer/src/store/slices/ui.ts Adds baseline generation and in-flight state while preserving pending local changes during hydration.
mobile/src/worktree/workspace-view-settings.ts Maps touched mobile view-state keys to compatible partial host updates.
mobile/app/h/[hostId]/index.tsx Changes mobile persistence from stale full snapshots to touched-field patches.
src/renderer/src/web/preload-api/web-ui-api.ts Adds an acknowledged host-write variant while retaining best-effort offline behavior for the existing API.
src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx Exercises desktop, web, and mobile synchronization orderings with controlled broadcasts and acknowledgements.

Sequence Diagram

sequenceDiagram
    participant C as Desktop/Web/Mobile client
    participant B as Local baseline or view mirror
    participant H as Host UI store
    C->>B: User changes one preference field
    B->>B: Diff changed field against hydrated baseline
    B->>H: ui.set(partial field patch)
    H->>H: Merge patch into durable UI state
    H-->>C: Acknowledge and/or broadcast state
    C->>B: Fold acknowledged write or overlay pending edit
Loading

Reviews (6): Last reviewed commit: "fix(sta-5781): web writer sends through ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 28, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6574a1d5-b0b0-460d-90ff-c3e994acc6ee

📥 Commits

Reviewing files that changed from the base of the PR and between 9b81bcb and e73846c.

📒 Files selected for processing (5)
  • src/preload/api/ui-command-event-api.ts
  • src/preload/index.ts
  • src/renderer/src/app-shell/use-persisted-ui-writer.ts
  • src/renderer/src/web/preload-api/web-ui-api.ts
  • src/renderer/src/web/web-preload-api-ui.test.ts

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


📝 Walkthrough

Walkthrough

The change adds patch-only mobile workspace-setting persistence and baseline-aware desktop UI persistence. Mobile updates now include only patched fields. Desktop writes diff a hydrated baseline, convert changed fields to wire updates, and retain pending local edits during hydration. New tests cover field mapping, baseline equality, wire conversion, debounce timing, broadcasts, concurrent updates, acknowledgements, failures, and same-field convergence. TypeScript compilation now includes additional main-process persistence modules.

Merge Risk: 🔵 Low · up to e7384

This change prevents clients from overwriting unrelated workspace view preferences, but failed mobile writes may remain locally divergent and a hung desktop write acknowledgement may block later preference saves; the cross-client test also does not cover every valid grouping and sorting value. The PR is mergeable with explicit owner awareness and follow-up on these bounded risks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 12 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 and concisely describes the primary change: preventing cross-client resets of workspace view preferences for STA-5781.
Description check ✅ Passed The description is detailed and on-topic. It explains the root cause, field-level patch solution, compatibility, linked issue, testing, and residual risks. It does not reproduce every template heading…
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.
Full details: Description check

Explanation

The description is detailed and on-topic. It explains the root cause, field-level patch solution, compatibility, linked issue, testing, and residual risks. It does not reproduce every template heading or provide the required visual proof entry, but the core required information is present.

  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ff2af552-3e8a-49e4-8bf1-2b68258d198a

📥 Commits

Reviewing files that changed from the base of the PR and between df95f03 and 68eaa5e.

⛔ Files ignored due to path filters (1)
  • mobile/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • config/tsconfig.tc.web.json
  • mobile/app/h/[hostId]/index.tsx
  • mobile/src/worktree/workspace-view-settings.test.ts
  • mobile/src/worktree/workspace-view-settings.ts
  • src/renderer/src/app-shell/use-persisted-ui-writer.ts
  • src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx
  • src/renderer/src/store/slices/persisted-ui-write-baseline.test.ts
  • src/renderer/src/store/slices/persisted-ui-write-baseline.ts
  • src/renderer/src/store/slices/ui.ts

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

…indow survives

CodeRabbit found a hole in the fold-on-ack baseline: toggle -> debounce
fires (write in flight) -> toggle back. The flip-back equals the pre-fold
baseline, so it diffed empty; the ack then folded the obsolete value in
and the write's own echo broadcast reverted the user's second toggle.

Fields now count as in flight for the ui.set round-trip: hydration keeps
the mirror's value for them (an echo can't revert a newer flip-back), and
on ack the writer re-diffs the mirror against the folded baseline and
flushes any trailing edit immediately. A rejected write still folds
nothing and re-flushes on the next change. Red test added first
(preserves a flip-back made while the first write is still in flight).
…eline fold

Round-3 Opus review of the in-flight tracking found two majors:

- Trailing re-diffs were sent inline from the ack handler, so one write in
  flight turned a stream of edits into one ui.set per IPC round trip (the
  #9002 write-amplification class). Trailing flushes now ride their own
  150ms debounce and skip while any write is in flight — that write's own
  ack schedules the next pass.
- An ack folded the SENT values over a baseline a hydration had already
  advanced past (remote same-field write during the round trip), blanking
  the mirror-vs-baseline diff and stranding mirror and authority apart
  until an unrelated broadcast resurfaced the reset. The baseline now
  carries a generation; a fold whose write predates the newest hydration
  is skipped so the trailing flush re-sends the local value. The identical-
  hydration short-circuit also compares baselines, since the in-flight
  overlay can pin the only visibly differing field.

Also: a synchronous ui.set throw now settles the in-flight marker (was a
permanent pin), the rejection handler no longer catches ack-handler
throws (double-settle/leak), the self-heal docstring is scoped to hosts
whose ui.set rejects, and the incidental mobile/pnpm-lock.yaml churn is
reverted. New tests: ack-rate amplification, remote same-field during ack
window, rejected-write self-heal, in-flight count decrement semantics.
…ation identity-stable

Round-3 verification pass (all prior findings CONFIRMED fixed, 8/9 mutants
killed) surfaced two minors, both fixed with their red tests:

- A rejected or synchronously-throwing write scheduled no trailing pass,
  so a pending flip-back whose trailing flush had bailed on that in-flight
  write was stranded until the next unrelated edit. Rejection and the
  sync-throw path now reschedule the trailing flush.
- The baseline-comparing short-circuit returned the full hydrated object
  when only the baseline moved — and our own echo precedes every ack, so
  every ordinary write churned collection identities (collapsedGroups,
  statusBarItems, ...) once per write. It now returns just the two
  baseline keys, preserving all visible-state refs.

Also: the generation option is now required for a fold (an unguarded fold
from a future caller could erase a remote mid-round-trip write), and the
sync-throw settle path is pinned by a test (last surviving mutant M17).

@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

Caution

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

⚠️ Outside diff range comments (1)
src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx (1)

105-107: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Model all valid group and sort values in the mobile client.

Line 106 and Line 129 serialize both none and prStatus as repo. Lines 157-164 do not hydrate groupMode or sortMode. The harness can therefore hide regressions for persisted grouping and ordering preferences.

Proposed fix
-    update.groupBy = next.groupMode === 'workspaceStatus' ? 'workspace-status' : 'repo'
+    update.groupBy =
+      next.groupMode === 'workspaceStatus'
+        ? 'workspace-status'
+        : next.groupMode === 'prStatus'
+          ? 'pr-status'
+          : next.groupMode
...
-    groupBy: next.groupMode === 'workspaceStatus' ? 'workspace-status' : 'repo',
+    groupBy:
+      next.groupMode === 'workspaceStatus'
+        ? 'workspace-status'
+        : next.groupMode === 'prStatus'
+          ? 'pr-status'
+          : next.groupMode,
...
       view = {
         ...view,
+        groupMode:
+          ui.groupBy === 'workspace-status'
+            ? 'workspaceStatus'
+            : ui.groupBy === 'pr-status'
+              ? 'prStatus'
+              : ui.groupBy,
+        sortMode: ui.sortBy,
         hideSleeping: ui.hideSleepingWorkspaces ?? view.hideSleeping,

Also applies to: 129-130, 157-164


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a535a8c8-5db0-4ffc-85b0-cb192aedec4f

📥 Commits

Reviewing files that changed from the base of the PR and between 1eb05f7 and da2f138.

📒 Files selected for processing (3)
  • src/renderer/src/app-shell/use-persisted-ui-writer.ts
  • src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx
  • src/renderer/src/store/slices/ui.ts

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

- Pin the sync-throw trailing reschedule with a test (last surviving
  mutant of the merge reviewer's 15-mutant sweep).
- Bump the baseline generation only when the baseline actually moved, so
  an unrelated-field broadcast during an in-flight write no longer voids
  the fold and costs a redundant trailing re-send.
- Correct the width-sanitizer comment (main does not clamp sidebar widths
  before broadcasting; safety comes from numeric clamping in the
  renderer's sanitizer, not from getPersistedUI).
…writes retry

Both the merge-decision reviewer and CodeRabbit flagged the same medium:
the web preload's ui.set swallows transport failures (deliberately — its
many fire-and-forget callers need best-effort offline behavior), so the
diff writer folded never-persisted patches into its baseline and silently
stopped retrying them; pre-PR whole-snapshot writes had self-healed this
by accident.

Add an optional ui.setWithAck that rejects when the host did not apply
the patch: on web it performs the same local merge but propagates the
runtime failure; on desktop it is the same ui:set invoke (which already
rejects). Only the diff writer uses it, with a fallback to plain set for
older preloads, so no other call site's error behavior changes.
Regression test: setWithAck rejects on transport failure while set stays
best-effort.
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Jinwoo-H
Jinwoo-H merged commit 5c10bf9 into main Aug 28, 2026
27 checks passed
@Jinwoo-H
Jinwoo-H deleted the sta-5781-filter-persistence-race branch August 28, 2026 22:20
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 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.

1 participant