Repository navigation
✨ feat(preferences): opt-in cross-device preference sync (#220) - #504
Conversation
…v1/preferences (#220) - ✨ new ui-preferences LokiJS collection keyed by username (indexed lookup, remove-then-insert upsert, server-set updatedAt) - ✨ /api/v1/preferences router: 403 for anonymous sessions, 409 on apiVersion mismatch, joi envelope with the preferences blob kept opaque, nocache, mounted inside the authenticated/CSRF section - ✨ dd:preferences-updated SSE broadcast — username-only payload (SSE fan-out is global, never carries preference values), id-stamped/replayable - 📝 OpenAPI: Preferences envelope schema (nullable never-synced fields) + /api/v1/preferences path entry - ✅ full test coverage: store module, router guard ordering, OpenAPI response validation, SSE broadcast, store index wiring
…ion (#220) - ✨ sync engine (preferences/sync.ts): server hydration after auth, 3s debounced server writes, outbound echo suppression, pending-local-edit guard (an unpushed local edit always outranks fetched server state), apply-gate on the server blob's own sync.enabled so toggle-off sticks across reloads - ✨ schema v11: new sync.enabled preference + v10→11 migration branch, wired into DEEP_WATCH_SECTIONS - ✨ Sync across devices toggle atop Config > Appearance — hidden for anonymous sessions, explicit immediate push on BOTH toggle transitions (the off-push records the disabled state server-side) - ✨ SSE wiring: eventStream dd:preferences-updated listener → AppLayout dd:sse-preferences-updated CustomEvent, username self-filter, re-fetch on reconnect - 🔒 sanitize hardening: deleteIfInvalid now rejects non-string enum values ({}, [], numbers, null) — the server-stored opaque blob applied cross-device made this a real trust boundary - ✅ full test coverage incl. adversarially-hardened suites (non-vacuous suppression test, distinguishable apply-gate blobs, router anonymous negatives, anti-flash window)
- 📝 UI customization page: drop the localStorage-only claims, add a Sync across devices section (opt-in, live SSE propagation, off-keeps-server-copy, anonymous-mode hiding, last-write-wins) - 📝 API reference: /api/v1/preferences endpoint table row + Preferences section with GET/PATCH examples and 400/401/403/409 codes - 📝 CHANGELOG: [Unreleased] feature entry
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (16)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (10)
📝 WalkthroughWalkthroughAdds authenticated preferences GET/PATCH endpoints with OpenAPI schemas, Loki-backed storage, and replayable SSE updates. Extends client preference migration and schema handling with debounced synchronization, guarded hydration, SSE merging, and navigation integration. Adds configuration UI controls, localization, documentation, and tests for server, client, storage, synchronization, and event handling. 🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 14
🧹 Nitpick comments (2)
app/api/preferences.ts (1)
12-17: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winMake the API version a checked contract, not a convention.
The server and client constants are manually duplicated, so a one-sided version bump will make every sync write fail at runtime with
409. Share/generate the value from the API contract, or add a CI contract test that fails when the two versions diverge.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/api/preferences.ts` around lines 12 - 17, Update the PREFERENCES_API_VERSION contract across app/api/preferences.ts and the client preferences module so the values cannot silently diverge: preferably share or generate the version from one API contract source, or add a CI contract test that compares both constants and fails on mismatch. Remove the convention-only synchronization approach while preserving the existing API version behavior.ui/src/preferences/sync.ts (1)
105-109: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsume the debounce after an explicit toggle push.
pushInitialSync()writes toggle transitions immediately, but the deep watcher also observessync. Enabling sync marks the blob dirty and leaves a 3-second timer active, causing a second identical PATCH and SSE broadcast. Cancel or consume the matching pending debounce after the explicit push.Also applies to: 142-151
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ui/src/preferences/sync.ts` around lines 105 - 109, Update pushInitialSync and the corresponding logic around the sync toggle path to cancel or consume the pending debounce after the immediate updatePreferences call. Ensure enabling sync does not leave the deep watcher’s 3-second timer active, while preserving the existing anonymous-user guard and immediate push behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/api/openapi/paths/index.ts`:
- Line 663: Update the apiVersion schema definition to use an enum containing
only the supported value 1, replacing the current minimum-based integer
constraint so client validation matches the handler’s accepted contract.
In `@app/api/preferences.ts`:
- Around line 19-23: Update the preferences GET/PATCH flow around
preferencesPatchSchema to expose a revision or ETag from GET and require that
value in PATCH requests. Pass the precondition into the storage operation and
perform the revision check atomically with the full snapshot replacement,
returning 409 for stale writes; preserve successful updates for matching
revisions.
In `@app/api/sse.ts`:
- Around line 512-520: Update broadcastPreferencesUpdated so it does not expose
the username through globally broadcast or replayable SSE data. Route the
notification only to clients associated with that username with matching replay
scope, or change it to a username-free invalidation event when global fan-out is
required; preserve the preference-update notification behavior.
In `@app/store/ui-preferences.ts`:
- Around line 30-36: Update cloneRecord() to use
structuredClone(record.preferences), and update replacePreferences() to clone
preferencesBlob with structuredClone before storing or returning it. Ensure both
persisted records and returned values no longer share the caller’s nested
preferences object reference.
In `@content/docs/current/api/index.mdx`:
- Line 432: Update the response-status description for the preferences endpoint
to include 413 for request bodies rejected by the global 256kb limit, while
preserving the existing 200, 400, 401, 403, and 409 responses.
- Around line 392-413: Update the preferences API curl examples under the
“Update preferences” section to include the repository’s required authentication
header or session cookie, matching the handler’s authenticated request format.
Ensure the examples represent a real user request rather than anonymous calls
that would return 403, and apply the same authentication context to the
preceding GET example.
In `@ui/src/preferences/migrate.ts`:
- Around line 691-701: Update the schemaVersion 10 migration to normalize
data.sync.enabled before spreading persisted sync data: remove or discard
non-boolean enabled values so DEFAULTS.sync.enabled is retained, while
preserving valid boolean values and other sync fields. Ensure malformed strings
such as "false" cannot reach downstream synchronization logic.
In `@ui/src/preferences/sync.ts`:
- Around line 56-58: Update the merge-gating logic around the syncDirty check
and the updatePreferences flow to track in-flight PATCH requests independently
of the cleared dirty flag. Keep SSE updates from merging while a write is
pending, then queue or refetch the remote snapshot after the write settles,
using an existing mutation/version token if available.
- Around line 48-74: Reset currentUsername, hydrated, syncDirty, and
syncFlushTimer when authentication changes, including the anonymous path in
hydrateFromServer, so the next user hydrates afresh and cannot flush prior
preferences. Add a session token for the active authentication session and
validate it before applying fetch results or completing writes in
fetchAndMergeFromServer and related persistence flows, discarding stale
completions from the previous user.
In `@ui/src/router/index.ts`:
- Around line 109-115: Update the authentication guard around hydrateFromServer
so route validation and navigation are not blocked by an unbounded preference
fetch. Start hydrateFromServer(user.username) without awaiting it, or apply a
bounded timeout/cancellation mechanism before awaiting; preserve the existing
username checks and validateAndGetNextRoute flow.
In `@ui/src/views/ConfigView.vue`:
- Around line 343-354: Update toggleSync so it captures the current
preferences.sync.enabled value before flipping it, then restores that previous
value in the catch path when pushInitialSync rejects. Keep the existing error
reporting and loading-state cleanup unchanged.
- Around line 202-204: Update the showSyncToggle computed predicate in
ConfigView.vue to require a successfully loaded, non-empty authenticated profile
before displaying the sync toggle; preserve the existing loading guard and
continue excluding the anonymous username, preventing pushInitialSync from
running with an empty username.
In `@ui/tests/views/ConfigView.spec.ts`:
- Around line 554-563: Update mountAppearance so its wait assertion is scoped to
the current factory mount rather than cumulative mock history: clear mockGetUser
before creating the wrapper or capture the pre-mount call count and wait for it
to increase. Keep waiting for the current profile request before continuing.
- Around line 594-607: Update the “pushes both enabled and disabled blobs
explicitly” test to initialize the shared preferences state with
preferences.sync.enabled set to false before triggering the toggle sequence, and
clear mockPushInitialSync before making assertions. Preserve the existing checks
for true/false state transitions and pushedStates order.
---
Nitpick comments:
In `@app/api/preferences.ts`:
- Around line 12-17: Update the PREFERENCES_API_VERSION contract across
app/api/preferences.ts and the client preferences module so the values cannot
silently diverge: preferably share or generate the version from one API contract
source, or add a CI contract test that compares both constants and fails on
mismatch. Remove the convention-only synchronization approach while preserving
the existing API version behavior.
In `@ui/src/preferences/sync.ts`:
- Around line 105-109: Update pushInitialSync and the corresponding logic around
the sync toggle path to cancel or consume the pending debounce after the
immediate updatePreferences call. Ensure enabling sync does not leave the deep
watcher’s 3-second timer active, while preserving the existing anonymous-user
guard and immediate push behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: fca78773-5c1f-46d8-a53f-b4f609d9f34e
⛔ Files ignored due to path filters (1)
CHANGELOG.mdis excluded by!CHANGELOG.md
📒 Files selected for processing (36)
app/api/api.test.tsapp/api/api.tsapp/api/index.test.tsapp/api/openapi/paths/index.tsapp/api/openapi/schemas.tsapp/api/preferences.test.tsapp/api/preferences.tsapp/api/sse.test.tsapp/api/sse.tsapp/store/index.test.tsapp/store/index.tsapp/store/ui-preferences.test.tsapp/store/ui-preferences.tscontent/docs/current/api/index.mdxcontent/docs/current/configuration/ui/index.mdxui/src/components/config/ConfigAppearanceTab.vueui/src/components/config/ConfigGeneralTab.vueui/src/layouts/AppLayout.vueui/src/locales/en/configView.jsonui/src/preferences/migrate.tsui/src/preferences/schema.tsui/src/preferences/store.tsui/src/preferences/sync.tsui/src/router/index.tsui/src/services/preferences.tsui/src/stores/eventStream.tsui/src/views/ConfigView.vueui/tests/composables/useIcons.spec.tsui/tests/layouts/AppLayout.spec.tsui/tests/preferences/migrate.spec.tsui/tests/preferences/store.watchers.spec.tsui/tests/preferences/sync.spec.tsui/tests/router/index.spec.tsui/tests/services/preferences.spec.tsui/tests/stores/eventStreamStore.spec.tsui/tests/views/ConfigView.spec.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.coderabbit.yaml:
- Around line 48-51: Update the base_branches configuration to use the regex
pattern "dev/.*" instead of "dev/*", ensuring automatic reviews match dev/vX.Y
integration branches.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 3a8c68bc-522c-4067-8df4-0c9ab715fd62
📒 Files selected for processing (1)
.coderabbit.yaml
| # Default is default-branch-only; v1.6+ feature work lands via PRs into | ||
| # dev/vX.Y integration branches and needs the same automatic reviews. | ||
| base_branches: | ||
| - "dev/*" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n## .coderabbit.yaml around the reported lines\n'
nl -ba .coderabbit.yaml | sed -n '40,60p'
printf '\n## Search for base_branches references in repo\n'
rg -n "base_branches|dev/\*" -S .
printf '\n## Search for any local docs mentioning regex/glob semantics\n'
rg -n "regex|glob|base_branches" -S README* .github docs .coderabbit.yaml 2>/dev/null || trueRepository: CodesWhat/drydock
Length of output: 242
🌐 Web query:
CodeRabbit base_branches regex patterns configuration auto-review docs
💡 Result:
In CodeRabbit, the base_branches configuration allows you to specify which target branches (in addition to the repository's default branch) should receive automatic code reviews [1][2]. Configuration details: - File Location: This setting is configured within the.coderabbit.yaml file in your repository [2][3]. - Path: The setting is nested under reviews and auto_review: reviews: auto_review: base_branches: - "regex-pattern-1" - "regex-pattern-2" - Regex Support: Each entry in the base_branches list is treated as a regular expression [2][4]. This allows for flexible pattern matching, such as using "release/." to include all branches starting with "release/" [2]. - Default Behavior: By default, CodeRabbit automatically reviews pull requests that target the repository's default branch (e.g., main or master) [2]. The base_branches setting extends this behavior; it does not replace the default branch [2]. - Match All: You can set base_branches to ["."] if you wish for CodeRabbit to review pull requests targeting any branch [2]. Important considerations: - Precedence: CodeRabbit reads the configuration from the PR's base branch [3]. - Organization Settings: If your repository is configured to use organization-level settings, those may override or combine with your repository-specific configuration [5]. You can manage this via the CodeRabbit web interface by toggling the Use Organization Settings option [5]. - Troubleshooting: If reviews are not triggering as expected, ensure your YAML syntax is correct, as invalid syntax may cause the entire configuration to be ignored [3]. Additionally, ensure that your regex patterns accurately capture the intended branch names [2].
Citations:
- 1: https://docs.coderabbit.ai/configuration/auto-review
- 2: https://coderabbit.mintlify.app/configuration/auto-review
- 3: https://github.com/jeremylongshore/claude-code-plugins-plus-skills/blob/main/plugins/saas-packs/coderabbit-pack/skills/coderabbit-common-errors/SKILL.md
- 4: https://docs.coderabbit.ai/reference/glossary
- 5: https://docs.coderabbit.ai/guides/repository-settings
Use a regex for dev branches.
base_branches entries are regexes, so "dev/*" won’t match branches like dev/v1.6 and skips automatic reviews for dev/vX.Y PRs. Change it to "dev/.*".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @.coderabbit.yaml around lines 48 - 51, Update the base_branches
configuration to use the regex pattern "dev/.*" instead of "dev/*", ensuring
automatic reviews match dev/vX.Y integration branches.
Source: MCP tools
- 🔒 security(api): dd:preferences-updated SSE event is now a username-free invalidation payload — no identity in the global broadcast or replay buffer; clients refetch their own session-scoped preferences - 🐛 fix(ui): reset sync module state on same-tab user switch and discard stale fetch completions — a pending flush could PATCH user A's blob into user B's server record after logout/login - 🐛 fix(ui): syncWriteInFlight guard — SSE-triggered fetches no longer merge an older server snapshot over values mid-flight to the server - 🐛 fix(ui): toggleSync restores the pre-flip state when the explicit push fails; showSyncToggle requires a loaded, non-empty profile - 🐛 fix(ui): pushInitialSync consumes the pending ambient debounce on success, killing the duplicate PATCH + broadcast after a toggle - 🔒 security(ui): sanitizeSync strips non-boolean sync.enabled on every load, so a tampered "false" string no longer acts as enabled - 🐛 fix(api): structuredClone preference blobs in the store — no shared references with persisted Loki documents - 🐛 fix(api): OpenAPI apiVersion advertises enum [1], not minimum 1 - ⚡ perf(ui): router guard no longer awaits preference hydration, so a stalled API cannot block authenticated navigation - ✅ test: coverage for all of the above, a server/client/OpenAPI version-contract tripwire, and ConfigView spec hygiene fixes - 📝 docs(api): preferences examples note the auth requirement; 413 added to the documented response statuses
|
Both nitpicks are also addressed in b901bec: the API version is now a checked contract (server constant exported + a tripwire test asserting server const == client const == the OpenAPI enum, so a one-sided bump fails CI), and pushInitialSync consumes the pending ambient debounce on success so a toggle no longer produces a second identical PATCH + broadcast 3s later. All 14 inline comments are answered in-thread — 13 fixed in b901bec, 1 skipped with reasoning (the PATCH revision/ETag suggestion; last-write-wins is the documented v1 design for this endpoint). |
Implements cross-device preference sync (Phase 5.5b, Discussion #220) — the next v1.6 feature from the tracker.
What
ui-preferencesLokiJS collection (one doc per username, indexed),GET/PATCH /api/v1/preferences(403 for anonymous sessions, 409 onapiVersionmismatch, opaque preferences blob, full-replace semantics),dd:preferences-updatedSSE broadcast with a username-only payload (SSE fan-out is global — the payload never carries preference values), OpenAPI schema + path entry.sync.enabledfield.Correctness notes (adversarially reviewed)
The design was scoped and then verified by a multi-agent adversarial review; three defects it confirmed are fixed in this PR:
sync.enabled: false— the ambient debounce is gated on the flag, so without the explicit push the off-state could never reach the server and reloads would silently re-enable sync.sync.enabledis true, so a server-side "off" leaves localStorage authoritative everywhere while fresh devices still discover sync-on.deleteIfInvalid()in the sanitize pipeline (non-string enum values are now stripped) since the server-stored blob applied cross-device is the first real trust boundary for those fields.Deliberate v1 constraints (documented in code/docs): last-write-wins, no per-user SSE targeting, 5-minute autosave durability window, server never inspects or migrates the blob (client
migrate()pipeline owns schema evolution).Testing
Changelog
✨ Added
ui-preferences) and new store module.GET/PATCH /api/v1/preferences(full-replace updates, API-version enforcement, OpenAPI docs + schemas).dd:preferences-updated+ client-side bus event (preferences-updated) and UI custom event dispatch (dd:sse-preferences-updated).sync.enabledfrom schemaVersion 10 → 11 (plus expanded sync sanitization rules).getPreferences,updatePreferences) and extensive unit/integration test coverage (API router, SSE, store, sync engine, UI toggle behavior).🔧 Changed
preferencessub-router under/preferencesalongside other authenticated routers.ui-preferencescollection.syncand allow-list deletion semantics.preferences.sync.🔒 Security
403), and server validates payloads (400) and API-version mismatches (409), with global mutating-body limit protection documented (413).Concerns
413behavior forPATCH /api/v1/preferences(middleware/request-body limit vs handler assumptions) matches OpenAPI documentation.