Skip to content

feat(settings): add the cross-platform settings contract and its manifest - #479

Merged
Quick104 merged 71 commits into
mainfrom
feat/settings-contract
Jul 30, 2026
Merged

Quick104 merged 71 commits into
mainfrom
feat/settings-contract

Conversation

@Quick104

@Quick104 Quick104 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Server-side foundation for unifying user settings across web, Apple, and Android (#376). Four commits, readable in order: the design, the manifest it specifies, one scope decision made during review, and the one bug in this repo that didn't need to wait for any of it.

Why

Settings have three partial contracts today — the server's settingsRegistry, web/src/lib/settingsManifest.ts, and independently-owned key constants in each native client — and they have measurably drifted. The root enabler is keyUsesUserScope in internal/api/handlers/settings.go, which returns true for any unregistered key, so a client can invent a production setting unilaterally and the server stores it as an unvalidated string.

What's here

1. docs(settings) — the design

docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md. Decision-complete: ownership, value types, scopes, per-definition resolution order, storage, API shape, client sync, UX language, migration, and release gates.

The decisions most worth reviewing:

  • Preferences versus restrictions. internal/policy already resolves max_playback_quality and metadata-language limits over the same controls this contract resolves preferences for. Definitions declare constrained_by, the effective response reports the permitted value alongside the user's stored one, and a mutation exceeding a restriction is stored, not rejected — a capped 4K preference should take effect the day the cap lifts, not be destroyed by it.
  • One coordinated breaking release. No shim, no projection, no client fallback. After the cutover no future setting requires coordination. No settings version check goes in the authenticated middleware and nothing returns 426 — deleting the old routes already produces the break, and a gate would be more code in four repos for the same outcome while permanently coupling every endpoint to one subsystem's versioning.
  • Widening vs narrowing. Adding a scope, enum member, or wider range is additive and revision-tagged; narrowing needs a new key. introduced_in attaches to individual enum members and scopes, not just definitions, so a newer client never offers a choice an older server rejects.
  • Appearance moves account → profile. Account scope was an artifact of pre-profile storage. Left alone, a household shares one theme and text size, and any non-child profile can restyle everyone else.

2. feat(settings) — the manifest and validator

contracts/settings/v1/ holds the artifact at a stable path because clients vendor it and generate bindings from it; internal/settingscontract/ does loading, validation, RFC 8785 canonicalization, ETag, and a public projection that strips maintainer notes. Nothing reads it yet — no routes, no storage, no behavior change.

38 definitions (35 remote, 3 contract-known client_local). Registering them is where the drift surfaced; each case is recorded in a notes field:

Finding Disposition
ui_theme, ui_text_scale, ui_text_weight, ui_high_contrast, ui_custom_theme_vars, ui_custom_css reached the server only via the unknown-key bag — untyped and unvalidated, with ui_custom_theme_vars storing arbitrary JSON Registered, typed, renamed to the dotted convention, moved to profile scope
player.match_frame_rate and player.sleep_timer_default_minutes are written by Android against a server registering neither, so every write and reset returns 400 today Registered
player.next_up_prompt_seconds is Android's alias for playback.next_up_prompt_seconds Not a definition; pinned as a migration alias in the test matrix
Android clamps playback speed to 4.0, the server to 3.0 Contract maximum is 3.0
subtitle_appearance is the only key with no domain prefix Renamed to playback.subtitle_appearance

Validation is deliberately stricter than the schema can express. Beyond shape it enforces that a resolution order ends in default, that it only resolves allowed scopes, and — the one most likely to bite — that every writable scope is actually read, so a setting cannot accept writes at a scope it will never honor. Defaults validate against their own value schema. ceiling/floor constraints are rejected on unordered types where capping would silently do nothing, which is why playback.preferred_quality's enum is ordered ascending.

ValidateValue is the single validation path, so the mutation endpoint, the migration, and the manifest's own default checks cannot diverge later. Numbers decode through json.Number, so an integer setting rejects 30.5 instead of truncating.

3. feat(settings) — ui.theme device override

Theme joins text scale, weight, and contrast as profile-with-device-override: light on a phone in daylight, dark on a TV. All four appearance keys now cascade identically, which is also one less rule to explain in the UI. ui.custom_theme_vars and ui.custom_css stay profile-wide, so custom tokens tuned against a dark theme will sit on top of a light one if a device overrides — noted in the definition rather than silently accepted. Widening those later is an additive revision bump.

4. fix(web) — appearance caches leaking between accounts

Independent of everything above; a verified P2 from #376 that needed no contract work. Signing into a second account on the same browser showed you the first account's theme, text size, contrast, and custom CSS until you saved your own. Incognito is not the leaking case — it starts empty.

The first attempt at this (commit c9a9007) extracted useDateTimeFormat's owner-stamp trick into a shared createOwnedCache and put useTheme and useCustomTheme on it. Review found that fix had a worse bug than the one it closed — see the section below. It has been replaced with per-account key namespacing.

5. fix(settings) — review pass: make the contract enforceable, fix the cache

Two commits added after an adversarial review of everything above.

The appearance cache fix was wrong. useTheme cleared the cache for any account whose stamp didn't match and then never repopulated it — the only writers were the four user-action setters, and unlike its two siblings it had no API→cache mirror. So every upgrading user (unstamped legacy cache ⇒ untrusted) lost their warm start on every load, not once. That is an accessibility regression for x-large-text and high-contrast users, and it ships on merge rather than at cutover.

Replaced the owner-stamp protocol with per-account key namespacing (silo-theme:7), which is what web/src/lib/tasteSeed.ts already does. A foreign value is absent rather than present-and-distrusted, so nothing is deleted, the first account keeps its warm start when they return, and there is no shared stamp for a second tab, a stale debounce timer, or an out-of-order effect to race on. Widening ownership to profile scope — which this manifest's ui.theme requires — is now a change to appearanceCacheOwner alone, which no call site can be left out of. Also adds the missing API→cache mirror, cancels pending debounced writes across an account change (a write-direction leak: account A's in-flight CSS could land in account B's settings), and re-seeds provider state during render so no frame paints the previous account's look.

Canonicalization was not RFC 8785. writeCanonical used json.Marshal, which HTML-escapes <, > and &; canonicalNumber used Go's 'g' format, which differs from ECMAScript at the exponent threshold, in exponent zero-padding, and on negative zero. Output is now byte-identical to ECMAScript String() — verified by diffing against node over the edge cases (0.00001, 1e-6, 1e-7, -0, 1e21, 5e-324), pinned in TestNumbersMatchECMAScript. The ETag now also covers the value schemas: those decide which object values the server accepts, so previously a schema could change what validates while the tag stood still and every client 304'd forever. All four derived representations are memoized (a conditional GET was paying a full parse and re-serialize).

Validation holes. strictUnmarshal's decoder.More() returns false when the next byte closes a container, so true] and 30} validated. Enum matching compared fmt.Sprintf("%v") tokens, so the string "3" satisfied an integer member 3. Declared step was never enforced. The language pattern rejected tags both mobile platforms emit unprompted (en_US, ca-ES-valencia, ar-EG-u-nu-latn) and never normalized case, so en-US and en-us were two rows for one preference; NormalizeValue now canonicalizes on the shared path.

Manifest vs. reality. playback.show_forced_subtitles defaulted false where user_profiles.show_forced_subtitles is NOT NULL DEFAULT true — that would have turned forced subtitles off for every profile that never touched it. playback.preferred_quality declared 13 members where NormalizeQualityV3 speaks 6 and collapses the rest to auto with a degradation warning. catalog.metadata_language's allowlist was bound to the very column it migrates from — circular. subtitle-appearance.json pinned fontFamily to three families while the Apple clients store any installed system font verbatim. Five user-facing settings the clients already ship are now registered, and three notes that described Android behaviour that was never true are corrected.

Enforcement — the part that makes this a mechanism rather than a document. The package had zero non-test callers, so MustLoad() never ran; it now loads and logs at startup. TestEveryCurrentServerKeyIsRegistered compared the manifest against a hand-transcribed map and so could not detect the drift it was named for; the check now lives in internal/api/handlers, iterates settingsRegistry directly, and also compares defaults. Both were confirmed to fail on injected drift (adding player.drift_canary; flipping playback.auto_play_next's default). And .github/workflows/ci.yml is the repo's first CI that runs tests at all — previously go test ran nowhere, so none of the contract tests gated anything.

Four tests that fail on main are named individually in GOTEST_KNOWN_FAILURES (one replan-v3, three jellycompat autoscan sidecar cases) rather than skipping whole packages, so everything else stays gated and the list can only shrink. Eight pre-existing files were gofmt-ed, since this PR adds the gate enforcing the rule AGENTS.md already states.

Verification

Re-run on this branch at 548b908a. The Go suite is run with the foreign
internal/playback WIP in this worktree stashed, so it reflects the branch only.

$ gofmt -l .
(no output = clean)

$ go vet ./...
(no output = clean)

$ make test-go
packages ok: 112
failures: none

$ make verify-local-paths
scripts/check-local-path-leaks.sh

$ pnpm run format:check
All matched files use Prettier code style!

$ pnpm run lint
158 problems (0 errors, 158 warnings)     # all pre-existing warnings

$ tsc -b
(no errors)

$ make test-web
 Test Files  221 passed (221)
      Tests  1313 passed (1313)

CI on this branch is green — Go, Web and Docs hygiene all pass at 75b17b38
(run 30176053954). Getting there took two fixes to the workflow itself, both of
which are the point of having it: go build ./... needs libvips headers because
h2non/bimg binds it through cgo, and pnpm/action-setup reads its version from
web/package.json since there is no root package.json. It also caught a
frontend test that only passed on Node 24 — new Response(blob) reads the body
via blob.stream(), which jsdom's Blob lacks on the Node 22 the Dockerfile
builds with. Fixed rather than skipped.

golangci-lint is not installed on this host, so make lint's Go half was not run here; .github/workflows/ci.yml runs gofmt, go vet and the full suite on every PR from now on.

New tests were confirmed to actually catch their bugs, not just pass:

  • removing the settings_contract_test.go cross-check's subject (adding player.drift_canary to settingsRegistry) → fails with the unregistered-key message; flipping a registry default → fails with the mismatch
  • the appearance-cache suite covers the account switch inside a live SPA, which the previous suite never exercised (every case signed in before first render, so the render-time guards and clear effects were never run)

Client PRs

Repo PR
silo-android Silo-Server/silo-android#101 — realign device settings with the server contract
silo-apple Silo-Server/silo-apple#104 — apply audio language from the profile so it affects playback

Open questions

  • Stranded Apple device rows. Old Apple builds wrote playback.audio_language device rows nothing ever read. The manifest resolves that key profile_device → profile, so at cutover a stale row would shadow the new profile value — a language someone picked months ago and demonstrably saw no effect from. Needs an explicit migration disposition.
  • The key renames are sanctioned by the design's non-goal of preserving accidental names and are free during a breaking cutover, but they're judgment calls.
  • player.sleep_timer_default_minutes is registered as remote rather than left client-local, on the grounds that a persisted default duration is a real preference and inherently device-specific. Persistence class is immutable after cutover, so this is cheap now and expensive later. (Its range and default were 0..480/0; review aligned them to Android's shipped 0..240/30, since a default of 0 would have silently turned the preset off for everyone at cutover. Widening later is additive via maximum_introduced_in.)

7. fix(settings) — second review pass

A re-review of the full diff after the storage commits. Four defects, none caught by the existing tests; each fix's test was checked to fail without it.

The theme fix reverted itself on the second render. getInitialThemeFromApi compared the server's theme against the appearance cache and fell back when they matched — but the mirroring effect added in the previous pass writes the server's value into that same cache. So the comparison held on the first render and stopped holding on every one after it: an explicitly chosen theme rendered once and then reverted to the default, with the DOM ending on the default. Observed across three renders as oxblood-noir -> midnight-cinema -> midnight-cinema. The ownership test added with the mirror asserted only on the first paint, which is why it passed. The server's value is this account's own stored choice, so it now wins outright, and the regression test re-renders.

The lint gate silently stopped linting 14 files. exclusions.paths is a path regex, not a directory list, so migrating issues.exclude-dirs: [web, migrations] to it turned a bare web into "any path containing web" — dropping internal/jellycompat/web_component.go (touched by this branch: 12 findings to 0), internal/webhooksync/*, internal/notifications/webhook*.go, internal/autoscan/arrwebhook/parse.go and others. Anchored to ^web/ and ^migrations/, verified by diffing the linted file set across both configs.

(Worth recording, since it cuts the other way: the old issues.exclude-dirs block was schema-invalid under golangci-lint v2 — config verify rejects it — so its exclude-rules were being ignored entirely and ~455 test files were carrying findings the config meant to exclude. The migration in this branch is what makes those rules take effect. Only the unanchored path was a regression.)

A numeric setting accepted a JSON string. json.Number is a string kind, so "1.5" unmarshalled into it without complaint and Float64 parsed the quoted digits happily — the value validated, and NormalizeValue stored the quoted form into jsonb, where every consumer reading it as a number disagrees with the row. Both number and integer now reject a quoted value.

The two backends disagreed about lone surrogates. rejectLoneSurrogates ran only on the object branch, so "\ud800" for ui.custom_css validated, decoded to U+FFFD on SQLite, and was rejected outright by Postgres jsonb — the same value storable on one backend and not the other. Hoisted to cover every type that can carry a string.

8. fix(settings) — bot review of the section 7 commits

Two more, both found by the Codex bot reviewing the fixes above, both verified by running the code.

The UTF-8 fix in section 7 was incomplete. Hoisting rejectLoneSurrogates closes the escaped path, but a raw 0xff byte inside a quoted string — what an HTTP body carries when a client encodes text in the wrong charset — is not an escape, so the scan never sees it, while encoding/json still substitutes U+FFFD and reports success. NormalizeValue stored the original bytes, which SQLite's json_valid accepts and Postgres jsonb refuses: the same backend divergence reached the other way. Now checks utf8.Valid on the raw document.

ui.library_page_state was bounded below what the web client writes. The search field was capped at 256 characters, but serializeLibraryPageSearchParams encodes each filter rule as three groups[i][rules][j][...] keys — 216 characters for one rule, 518 for three, 820 for five, measured by calling the function rather than estimated. The current endpoint validates this key by checking only that it parses, so those values are already in production: typing them at 256 would have failed the migration for anyone with more than one filter rule saved. Raised to 4096, with the test pinned to the key shapes the client actually emits.

The bot's other three comments on this round were assessed and not acted on: the unbounded IN lists and the untrimmed scope identities are in the storage commits rather than these fixes and are the author's call, and the conformance_test.go cleanup suggestion is about a cascade that does exist.

Cross-repo: the strict language-tag validation breaks the shipped Android client

The BCP 47 enforcement added in the previous pass is correct, but it rejects what Android actually sends. Traced end to end: PlaybackSettings.kt's picker puts the display label on the wire verbatim, so the client PUTs {"value":"English"} to playback.audio_language, and the phone does the same for the profile's subtitle_language. Apple has always sent codes.

That was already broken before this branch — the same string is handed to ExoPlayer, and setPreferredAudioLanguage("English") never matches a track tagged eng, so choosing an audio language on Android has silently been a no-op, and a language picked on an iPhone read as "Default" on the phone. But with validation on, the flusher's PUT 400s and only logs, so the setting stops persisting entirely after a server upgrade.

Fixed on the client rather than by widening the contract to accept display names: Silo-Server/silo-android#119 (4aeb78b4). It replaces the four drifted option lists — phone audio, phone subtitle, phone metadata, TV audio, which had already diverged from TV subtitle's correct one — with a single table in shared, and translates values already on devices on read so a stored label is not re-sent. That PR should merge first, or Android users lose the setting for one release.

The cutover

Everything above was foundation — the manifest, the validator and the typed
tables existed with nothing able to reach them. These commits complete Phases
2–4 of the design and perform the cutover.

Quality is two axes. The compound ladder values (1080p-high,
720p-medium, 420p, 328p) were never a third dimension, only a bitrate
spelled into the resolution string — useTranscodeQuality.ts has decomposed
them into {resolution, bitrate} and sent the two separately for as long as it
has existed, and NormalizeQualityV3 folded every compound value to auto, so
none of them has had any effect for a while. playback.preferred_quality keeps
the six clean resolutions; playback.max_bitrate_kbps is the second axis,
nullable because "uncapped" is a real answer. Clients compose their own presets
— 1080p High / 1080p / 1080p Low / 720p High / 720p / 480p — so retuning what
"High" means is a client release rather than a contract change four codebases
have to agree on. Migration decomposes every legacy value losslessly; nothing
lands in the rejects table.

The resolution engine (internal/settingsresolve) replaces the four ladders
that disagreed about precedence: catalog/detail.go resolved subtitles across
four levels and audio across three by hand, handlers/settings.go had a
two-level resolution with a lazy write-back inside a GET, and jellycompat read
profile columns directly. One batched read regardless of how many keys,
libraries or series are in play. Two cases needed care and were found by running
the code rather than reading it: null on a nullable numeric means unbounded,
so a ceiling must cap it instead of ranking it equal and letting the value that
most needs capping slip past; and an allowlist must fall back to a permitted
member, since the definition's own default may sit outside the list.

The one-time migration runs on both backends from one set of rules in
internal/settingsmigrate, so SQLite and Postgres cannot decide differently.
The traps, each pinned by a test:

  • quality_preference is NOT NULL DEFAULT '1080p' while the contract defaults
    to auto. Migrating it unconditionally would have pinned every profile in
    every install
    to 1080p having never chosen it — and that stored value then
    outranks the contract default forever.
  • The empty string is the legacy spelling of unset, not a value. Storing it
    would make a cleared setting outrank the default.
  • preferred_metadata_language exists only in the Postgres schema.
  • Subtitle and audio preferences are two tables keyed alike; converting them
    independently would produce two rows racing for one identity.
  • Reject identities are JSON because both backends store that column as JSON —
    free-form prose would have failed to insert on exactly the rows the table
    exists to record.

Everything unconvertible is recorded with a reason rather than dropped, and the
whole thing runs in one transaction: a database comes out fully migrated or
untouched.

The canonical API serves the contract behind an ETag, reads and writes
explicit values at one named scope, resolves any number of keys in one request,
and makes writes idempotent under X-Silo-Mutation-Id — a retry after a dropped
response replays the receipt, and reusing an id with different content is a
conflict rather than a silent overwrite.

The extension bag is closed. keyUsesUserScope returned true for any
unregistered key, which is how six ui.* settings and five orphan keys reached
production untyped. All eleven are registered definitions now, and an unknown
key is refused.

Generated bindings for all four languages from one generator — four
independently written ones would be four chances to disagree. make verify-settings-bindings gates CI, so a manifest change cannot merge leaving
clients on stale keys. On Android the generated output replaces two
hand-maintained tables, including the type classification that had to agree with
the key list by discipline alone.

Companion client PRs

  • fix(settings): send language tags, not display names silo-android#119 — language tags plus generated bindings. Its
    new contract test immediately caught two real drifts:
    subtitle_appearance had no domain prefix, and next_up_prompt_seconds was
    player.* on Android against playback.* on Apple and the server, so the
    same preference was two settings and neither client could read the other's.
  • silo-apple feat/settings-contract — replaces the private key enum inside
    the 906-line PlayerSettings singleton with the generated SettingKey.

All three must ship together; the design calls for one coordinated cutover and
there is no dual-write.

Supersedes #477, #473, and #478, which split this across three PRs.

Phase A completed, and the web client is on the contract

Since the last update this branch finishes the server side and moves the web client over. Twelve commits, 22e9d7f1..8cacc513:

Server (Phase A). The last legacy column readers are gone: access scope, policy input, and playback start resolve catalog.metadata_language / playback.audio_language canonically (internal/access/metadata_language.go), degrading to the contract default on store failure rather than 5xx-ing. Jellyfin DisplayPreferences moved out of user_settings into a dedicated jellycompat_displayprefs table on both backends — shared parse rules drive both migrations, blobs copy byte-for-byte, unparseable rows land in the rejects table, and the jellycompat:* carve-out is deleted so the legacy API refuses those keys. The ten /admin/users/{id}/settings* routes are replaced by three canonical ones sharing SettingValuesHandler's validation and idempotency (all ten recorded in the pre-lock removals table). The cross-platform conformance fixture lands at contracts/settings/v1/conformance.json with Go and web runners; both reject unknown fixture fields and pin the manifest revision. A daily sweeper now enforces mutation-receipt expiry, and user_settings.changed events publish key+scope (never the value — admins receive every user's events).

Web (Phase B). All 13 legacy-hook surfaces are on the canonical API: appearance hooks at profile scope with the warm-start cache namespaced per profile (silo-theme:7:p1), the query-layer stores (pins, page state, disabled/order, overlays) writing typed JSON at their declared scopes, settings screens and player panels at profile / profile_device / profile_library / profile_series, controls rendered from generated SETTING_DEFINITIONS. settingsManifest.ts and the legacy hooks are deleted; the user_settings channel invalidates the react-query cache so another device's change refetches. The admin pages consume the new canonical admin routes.

Two review passes over the new work, findings verified by probe before fixing. Phase A: 8 findings, 8 confirmed — including profile create/update writing only legacy columns while readers had moved (write-through added), and the Postgres displayprefs migration deleting rows it hadn't read under READ COMMITTED (reproduced against real Postgres; it now deletes exactly the rows it copied). Phase B: 12 findings, 5 confirmed, all one shape — a value written at a scope no UI can reach, shadowing the editable one: auto-play-next split profile_device/profile between player and settings (now one shared hook), the in-player subtitle pick writing three per-series rows while "Auto" cleared one (now a shared key list both sides iterate), and the admin settings tab routing object values through a destructive select (now a JSON editor).

Cross-client coherence fix (8cacc513). The Android review found that GET /profiles still served the raw legacy columns for subtitle language/mode/forced while canonical profile writes never touch them — so a preference saved through the new API was invisible to every profile-DTO reader, including Apple's shipped build. toProfileResponse now resolves those fields canonically (batched across the household's profiles — one store read per request, not per profile), falling back to the contract default, never the stale column. quality_preference and the auto_skip_* fields deliberately stay column-backed (the compound legacy value has no lossless canonical read; the sync path never mirrored auto-skip) — noted in code.

Verification at 8cacc513: gofmt/go vet clean, make test-go green, make verify-settings-bindings and verify-local-paths green, web lint 0 errors / format clean, make test-web 225 files / 1359+ tests green, and the live-Postgres suites (pgstore, settingsmigrate, database incl. the new concurrency test) run for real against a scratch database. The A5 admin surface intentionally has no canonical bulk-delete route — the web page issues per-row deletes; an additive endpoint can follow if it matters.

One scope note for A6 (the post-merge legacy-route deletion PR): GET /settings/overlay-config stays — it reads server_settings, a different system, and useOverlayPrefs still consumes it for admin defaults.

Part of #376.

AI Disclosure

  • Tool(s): Claude Code
  • Model(s): claude-opus-5[1m], claude-fable-5
  • Involvement: AI-assisted, under maintainer direction
  • Adversarial review: The original commits were reviewed by a ten-agent parallel pass over this diff plus an independent adversarial pass using Codex, then the findings were cross-compared. Both independently found the non-RFC-8785 canonicalization, the fmt.Sprintf enum type confusion, the unimplementable quality ceiling, and the Android migration's dependence on a lossy flusher. Codex alone found the debounced-timer cross-account write leak, the show_forced_subtitles default inversion, the unenforced step, and the circular metadata_language constraint. The parallel pass alone found that the appearance-cache fix cleared without repopulating, that no CI ran go test at all, and that the inventory test could not see the drift it named. Everything above is fixed in the two review commits; each fix's test was checked to fail without it. Two reviewer claims were investigated and rejected: that the resolution orders were internally inconsistent (they are not — device sits below content specificity uniformly, and subtitle_appearance simply has no content scopes), and that a blanket hasDeviceOverride gate was the right Android fix (it would have broken resetAllDeviceSettings).

Second review pass: a re-review of the full diff found the four defects in section 7 plus the Android incompatibility, and the review bots then found two more in those fixes themselves (section 8) — the UTF-8 guard was incomplete, and a bound was set below what the client writes. Each was verified by running the code rather than by reading it — the theme revert via a multi-render vitest repro, the lint regression by installing the pinned golangci-lint v2.12.2 and diffing the linted file set across both configs, the two validator holes via probe tests, and the Android wire value by tracing the picker through the ViewModel, the settings store, the flusher, and the HTTP client. One prior finding (namespaceFor(null) falling back to the last writer for pre-auth frames) was re-examined and left alone: it is documented as deliberate, and it is what keeps the login screen from flashing an unstyled paint. One finding from the previous pass (15 golangci-lint findings on this branch's own lines) had already been fixed by 1f9b300a before this pass ran, and is confirmed clean.

Every claim about current behavior was verified against the cited source files, and all test and lint results were re-run on this branch after main moved.

Summary by CodeRabbit

  • New Features

    • Added an embedded cross-platform user settings contract (manifest + schemas).
    • Introduced typed, revisioned per-user settings storage with mutation receipts.
    • Added account-scoped appearance/theme warm-start caching in the web UI.
    • Added CI workflow to run Go, web, and docs checks on changes.
  • Bug Fixes

    • Stricter playback speed step alignment and BCP-47 language-tag validation for device/user settings.
  • Tests & Documentation

    • Expanded contract drift and settings conformance coverage; updated build/test guidance.

Maintainer remediation for review 4812437265

Commit f11fb598 addresses the latest review comments:

  • preserves the legacy effective quality cap as explicit canonical 1080p plus 6000 kbps rows;
  • adds the documented collection GET for explicit values;
  • prevents DisplayPreferences rollback from deleting a concurrently updated canonical value;
  • keeps legacy audio, subtitle, library, and profile preference writes synchronized with canonical rows in one SQLite/PostgreSQL transaction, publishing events only after commit;
  • rejects nonexistent library contexts on both session and admin setting routes;
  • preserves the physical source table and content identity on orphan migration rejects; and
  • resolves series-scoped canonical audio language while retaining specialized track identity.

This corrects two earlier statements in the PR description: existing legacy profiles are intentionally migrated to explicit 1080p and 6000 values because those were the effective legacy defaults, and the retained legacy preference routes now transitionally dual-write canonical rows rather than relying on a no-dual-write cutover.

One deployment concern remains report-only: during a rolling deployment, an old binary can write a legacy row after the new binary's one-time backfill has read that table. Closing that window requires rollout quiescence, compatibility-period behavior in already-deployed old binaries, or another deployment/architecture decision; this remediation does not pretend a local handler change can make that guarantee.

Maintainer remediation verification

  • make build
  • make test — 244 web test files and 1,525 tests passed
  • focused handler, SQLite, notification-decorator, and store transaction tests passed
  • fresh PostgreSQL 18 migration and PreferenceTransactionRollback conformance passed
  • golangci-lint v2.12.2 run --new-from-merge-base=origin/main ./... — 0 issues
  • cd web && pnpm run lint — 0 errors (157 existing warnings)
  • cd web && pnpm run format:check
  • make verify-local-paths
  • git diff --check
  • deployed to the configured development backend while holding the shared backend lock; /api/v1/ready was healthy, legacy audio/library writes and deletes changed canonical rows as expected, nonexistent-library writes returned 404, and a profile PUT was reflected in both the legacy projection and canonical admin listing before restoration. No related panic, migration error, or HTTP 500 appeared in the inspected logs.

Maintainer remediation AI disclosure

  • Tool: Codex in T3 Code
  • Model: gpt-5.6-sol
  • Involvement: AI-assisted implementation, verification, and final two-axis review under maintainer direction### Maintainer remediation for review 4815451856

Commit c1db41a5 addresses seven actionable comments from the latest review:

  • adds batched POST /api/v1/settings/values/effective resolution with one candidate read;
  • returns the documented constraint fields, permitted enum choices, source metadata, and current definition revision;
  • batches viewer settings resolution into one canonical query while retaining legacy fallbacks;
  • rejects profile-scoped migration orphans when the loaded profile list is empty;
  • includes canonical-only device overrides in admin fleet counts, profile totals, and timestamps with alias deduplication;
  • mirrors retained legacy account/device writes and deletes to canonical rows transactionally, serializing account fan-out with profile creation across replicas; and
  • carries the validated active profile in full-page plugin launch cookies while preserving profile-less launches.

The rollback comment remains report-only: the checked-in design explicitly states that rollback discards canonical settings written while the new binary was live. Preserving them requires a compatibility/migration decision beyond this review remediation.

Maintainer remediation verification

  • make build
  • make test — all Go packages plus 244 web test files / 1,525 tests passed
  • focused affected Go packages passed
  • fresh PostgreSQL scratch database: settings backfill, DisplayPreferences migration/rollback guards, setting-value conformance, per-user advisory-lock serialization, and migrate-down restoration all passed; the scratch database was dropped afterward
  • golangci-lint v2.12.2 run --new-from-rev=a7601028d9d606f1de7f9ec6bef72c759de7c91a ./... — 0 issues
  • cd web && pnpm run lint — 0 errors (157 existing warnings)
  • cd web && pnpm run format:check
  • make verify-local-paths
  • git diff --check
  • redeployed the configured development backend while continuously holding the shared backend lock through probes and cleanup; readiness stayed healthy
  • live probes verified two-context batched resolution, the constrained quality response shape, legacy write/delete mirroring across every profile, canonical-only admin device summaries, and plugin launch claims with and without an active profile
  • cleanup audit confirmed no probe-created cap, legacy/canonical setting, canonical device value, or device registration remained; probe requests produced no HTTP 5xx

Maintainer remediation AI disclosure

  • Harness: T3 Code Codex harness
  • Model: gpt-5.6-sol
  • Reasoning effort: xhigh
  • Reviewed SHA: f11fb598976a5335deec1e67c7f2aa45fd3090cf
  • Scope: latest-review implementation, backend verification, and final independent Standards/Spec review under maintainer direction

@coderabbitai

coderabbitai Bot commented Jul 25, 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

This PR adds a versioned embedded settings contract, typed setting persistence and resolution for SQLite and PostgreSQL, account-scoped web appearance caching, migration planning, CI and local verification targets, and compatibility updates.

Changes

Embedded settings contract and persistence

Layer / File(s) Summary
Contract artifacts and runtime validation
contracts/settings/v1/*, internal/settingscontract/*, cmd/silo/main.go, internal/api/handlers/settings.go
Adds revisioned typed settings, schemas, canonicalization, strict validation, startup loading, ETags, language-tag normalization, and numeric step enforcement.
Typed persistence and conformance
internal/userstore/*, internal/userdb/*, internal/userstore/pgstore/*, migrations/*
Adds scoped setting values, resolution queries, mutation idempotency, database constraints, migrations, deletion behavior, and shared SQLite/PostgreSQL conformance tests.
Migration and resolution
internal/settingsmigrate/*, internal/settingsresolve/*
Converts legacy settings into validated scoped rows and resolves effective values using contract precedence and policy constraints.

Account-scoped appearance cache

Layer / File(s) Summary
Namespaced appearance storage and flows
web/src/utils/storage.*, web/src/hooks/themePreferences.ts, web/src/hooks/useTheme.*, web/src/hooks/useCustomTheme.*, web/src/hooks/useDateTimeFormat.tsx
Scopes cached appearance values and persistence by authenticated account, including account switching and debounced custom-theme writes.
Appearance validation
web/src/hooks/appearanceCacheOwnership.test.tsx, web/src/utils/storage.test.ts, web/src/hooks/useTheme.test.ts
Tests account isolation, warm starts, owner transitions, debounced writes, and cache fallback behavior.

Repository verification and compatibility

Layer / File(s) Summary
CI, local tests, and build wiring
.github/workflows/ci.yml, Makefile, .golangci.yml, AGENTS.md, Dockerfile*, go.mod
Adds Go, web, and documentation checks, filtered test targets, embedded frontend stubbing, lint configuration, container build wiring, and verification guidance.
Compatibility and maintenance updates
internal/scantrigger/*, internal/jellycompat/*, internal/api/handlers/*_test.go, internal/audiobooks/*, internal/models/*
Adds structured scan rejection reasons, stabilizes asynchronous cleanup and file-revision tests, extends interface stubs, adds marker fallback handling, and applies formatting-only changes.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: adding the cross-platform settings contract and manifest.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/settings-contract

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

Quick104 and others added 8 commits July 26, 2026 15:24
Turns the audit in #376 into a decision-complete design for how user settings
work across the server, bundled web client, Apple clients, and Android clients.

Today there are three partial contracts - the server registry, the web client's
own manifest, and independently owned key constants in each native client - and
they have measurably drifted. The root enabler is that keyUsesUserScope returns
true for any unregistered key, so a client can invent a production setting
unilaterally and the server stores it as an unvalidated string.

The design decides:

Ownership. Every production user-facing setting needs a server-owned manifest
entry, even when the value is stored only on one client. The single exception is
private local.<client>.* diagnostics, bounded by five conditions.

Types and scopes. Native JSON values instead of strings. Five remote scopes plus
client_local, and each definition declares its own resolution order rather than
inheriting a global precedence.

Preferences versus restrictions. internal/policy already resolves
max_playback_quality and metadata-language limits over the same controls this
contract resolves preferences for. Definitions declare constrained_by, the
effective response reports the permitted value alongside the user's stored one,
and a mutation exceeding a restriction is stored rather than rejected - a capped
4K preference should take effect the day the cap lifts, not be destroyed by it.

Compatibility. Widening a scope, adding an enum member, or widening a range is
additive and revision-tagged; narrowing anything needs a new key. introduced_in
is a manifest revision attached to individual enum members and scopes, not just
whole definitions, so a newer client never offers a choice an older server will
reject.

Rollout. One coordinated breaking release, with no compatibility shim,
projection, or client fallback. After the cutover no future setting requires
coordination. No settings version check goes in the authenticated middleware and
nothing returns 426: deleting the old routes already produces the break, and a
gate would be more code in four repos for the same outcome while permanently
coupling every endpoint to one subsystem's versioning.

Scope placement. Appearance and date/time move from account to profile scope.
Account scope was an artifact of pre-profile storage; leaving it there means a
household shares one theme and text size, and any non-child profile can restyle
everyone else.

Read path. Batched context resolution, index requirements, a session-snapshot
rule, and a no-regression benchmark gating storage consolidation - profile_series
resolution is per-item, so a season view would otherwise issue one request per
episode.

Verified against the current server, Apple, and Android implementations. Two
findings shape it: the unknown-key extension bag is real, and v1 scope reads NOT
LOCKED, so removing the legacy surface needs no amendment if it lands before
lock.

Related to #376.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
First implementation step for the cross-platform settings contract (#376).
Adds the artifact everything else depends on: the manifest, its JSON Schema,
the object value schemas, and a Go loader that validates the whole thing at
load time. No routes, no storage, no behavior change — nothing reads this yet.

contracts/settings/v1/ holds the artifact at a stable path because clients
vendor it and generate bindings from it. The embed directive has to sit beside
it (go:embed cannot reach outside its own directory), so that directory is a
tiny Go package containing nothing else; loading and validation live in
internal/settingscontract.

38 definitions: 35 remote, 3 contract-known client_local. That covers every key
the legacy registry accepts, every unregistered key the extension bag was
silently accepting from the web client, every unregistered device key Android
writes, and the profile preference columns that become settings.

Registering the previously-unregistered keys is where the drift shows up, and
the manifest records each case in a notes field:

- ui_theme, ui_text_scale, ui_text_weight, ui_high_contrast,
  ui_custom_theme_vars, and ui_custom_css reached the server only because
  keyUsesUserScope returns true for any unregistered key. They are now typed,
  renamed to the dotted convention every other key uses, and moved to profile
  scope per the design.
- player.match_frame_rate and player.sleep_timer_default_minutes are written by
  Android against a server that does not register them, so every write and reset
  is currently rejected. Registered.
- player.next_up_prompt_seconds is Android's alias for
  playback.next_up_prompt_seconds and does not become a definition; the test
  matrix pins it as a migration alias.
- player.playback_speed is capped at 3.0, matching the server rather than
  Android's 4.0.
- subtitle_appearance becomes playback.subtitle_appearance. Every other
  canonical key carries a domain prefix, and preserving accidental key names is
  an explicit non-goal of the design.

Validation is deliberately stricter than the schema can express. Beyond shape,
it enforces that a resolution order ends in "default", that it only resolves
scopes the definition allows, and — the one most likely to bite — that every
writable scope is actually read, so a setting cannot accept writes at a scope it
will never honor. Defaults are validated against their own value schema, so a
default that violates its own range or enum fails at load. Revision tags are
checked to never run ahead of the manifest revision, which is what makes
revision-aware client filtering trustworthy. Ceiling and floor policy
constraints are rejected on unordered types, where capping would silently do
nothing; playback.preferred_quality's enum is therefore ordered ascending.

ValidateValue is the single validation path, so the mutation endpoint, the
migration, and the manifest's own default checks cannot diverge later. Numbers
decode through json.Number so an integer setting rejects 30.5 rather than
truncating, and object values validate against their referenced JSON Schema
instead of accepting arbitrary JSON the way validateJSONSetting does today.

Canonicalization implements RFC 8785 over the value domain the contract uses:
sorted keys, no insignificant whitespace, ECMAScript number formatting. The
digest is the ETag, and PublicBytes strips maintainer notes so the served
manifest never carries internal commentary.

Promotes santhosh-tekuri/jsonschema/v6 from indirect to direct.

Verification: 124 tests pass across 16 cases; golangci-lint clean;
make verify-local-paths passes. Two failures in internal/api/handlers
(TestRemoveJellyfinCompatWebDisablesWebSetting, the playback v3 seek recovery
test) reproduce unchanged on main and are unrelated.

Part of #376.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Theme joins text scale, text weight, and high contrast as a profile default
with an optional per-device override, resolving profile_device -> profile ->
default. The right theme is partly a function of the screen and the room — a
light theme on a phone in daylight, a dark one on a TV at night — which is the
same reasoning the other three appearance keys already used.

All four appearance settings now cascade consistently, which also means one
rule to explain in the UI rather than "these three follow the device, that one
does not".

ui.custom_theme_vars and ui.custom_css stay profile-wide. They are authored
styling rather than a contextual preference, so a profile's custom tokens still
apply on top of whichever theme a device resolves to. Recorded in the
definition notes because it is a visible consequence: vars tuned against a dark
theme will sit on top of a light one if a device overrides the theme. Widening
those to profile_device later is an additive revision bump if it turns out to
matter.

Part of #376.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The theme, text scale, text weight, high contrast, custom theme variable
and custom CSS caches in localStorage were untagged, so on a shared
browser a second account inherited the first account's appearance: with
no server value of its own, every fallback resolved to whatever the
previous account had stored, and the leftover `silo-theme` key also
suppressed the admin-configured default theme for the new account.

DateTimeFormatProvider already solved this by stamping its cache with the
authenticated user id and refusing another account's values. Extract that
mechanism into `createOwnedCache` in utils/storage.ts (where key
namespacing lives) and put all three groups behind it, so appearance and
custom theme get the same protection instead of a third copy of the rule.

- Each group carries its own owner stamp. A shared stamp would be unsafe:
  the groups are written by hooks nested inside each other, and effects
  run inner-first, so whichever hook stamped first would vouch for the
  other's still-stale values.
- A null owner (auth bootstrapping, or signed out) still trusts the
  cache, which keeps the warm start and the login screen's last look.
- An unstamped cache is not trusted once an account is known, so existing
  users take a one-time appearance reset on first load rather than a
  chance of seeing someone else's settings.
- When a foreign cache is detected the values are dropped and the empty
  cache is handed to the new account, so a later single save cannot
  re-trust the rest of the previous account's state.

Owner is the user id because /settings is user-scoped server side; it
lives in one helper (`appearanceCacheOwner`) so it can be widened if
appearance moves to profile scope. `shouldLoadApiTheme` is gone: it had
become a synonym for `appearanceCacheOwner(...) !== null` with no callers
left.

Part of #376

AI-use disclosure: implemented with Claude Code.

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

The contract manifest landed as a document nothing checked. This makes it a
mechanism, and fixes the one defect in the change set that hurt users on merge
rather than at cutover.

Web appearance cache. useTheme cleared the cache for any account whose stamp
did not match and never repopulated it — the only writers were the four
user-action setters — so every upgrading user lost their warm start on every
load, not once, and x-large-text and high-contrast users lost theirs too. The
owner-stamp protocol is replaced with per-account key namespacing
(`silo-theme:7`): a foreign value is absent rather than present-and-distrusted,
so nothing has to be deleted, the first account keeps its warm start, and there
is no shared stamp for a second tab, a stale debounce timer, or an out-of-order
effect to race on. Widening ownership to profile scope, which this manifest
requires, is now a change to appearanceCacheOwner alone. Adds the API-to-cache
mirror useTheme was missing, cancels pending debounced writes across an account
change, and re-seeds provider state during render so no frame paints the
previous account's look.

Canonicalization. writeCanonical used json.Marshal, which HTML-escapes < > and
&, and canonicalNumber used Go's 'g' format — both diverge from RFC 8785, so
the first label containing an ampersand or bound below 1e-4 would have forked
the server's ETag from every conforming client. Output is now byte-identical to
ECMAScript String() across the edge cases, verified against node. The ETag also
covers the value schemas, which decide what the server accepts and previously
could change while the tag stood still. All four derived representations are
memoized; a conditional GET no longer costs a full parse and re-serialize.

Validation. strictUnmarshal's decoder.More() answered false for a stray ] or },
so `true]` validated as a boolean. Enum matching compared fmt.Sprintf tokens, so
the string "3" satisfied an integer member. Declared steps were never enforced.
The language pattern rejected tags both mobile platforms emit unprompted
(en_US, ca-ES-valencia, ar-EG-u-nu-latn) and never normalized case, so en-US and
en-us were two rows for one preference; NormalizeValue now canonicalizes on the
shared path.

Manifest. show_forced_subtitles defaulted false where the server column is NOT
NULL DEFAULT true, which would have turned forced subtitles off for every
profile that never touched it. preferred_quality declared 13 members where the
planner speaks 6 and collapses the rest to auto. metadata_language's allowlist
was bound to the very column it migrates from. subtitle-appearance pinned
fontFamily to three families while Apple stores any installed system font.
Registers five user-facing settings the clients already ship, and corrects three
notes that described Android behaviour that was not true.

Enforcement. The package had no non-test callers, so MustLoad never ran; it now
loads and logs at startup. The inventory test compared the manifest against a
hand-copied map and could not see the drift it named; it now iterates
settingsRegistry and checks defaults too — both verified to fail on injected
drift. Adds .github/workflows/ci.yml, the repo's first CI that runs go test,
go vet, gofmt, and the frontend suite. Known pre-existing failures are named
individually in the Makefile so everything else stays gated and the list can
only shrink.

Part of #135

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

Android is the only client that implements this setting. It clamps to 0..240
and defaults to 30. The manifest said 0..480 with a default of 0, so a
manifest-driven UI would have offered durations no client can store, and every
user who never opened the picker would have had the preset silently turned off
at cutover.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The first run exposed two gaps in the workflow itself. go build ./... fails
without libvips headers, because h2non/bimg binds libvips through cgo and
pkg-config; the Dockerfile installs the same package. And pnpm/action-setup
resolves its version from package.json, but there is no package.json at the
repo root — the packageManager field lives in web/package.json, and a job's
defaults.run.working-directory does not apply to an action's inputs.

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

new Response(blob) reads the body through blob.stream(), which jsdom's Blob
does not implement on Node 22 — the version the Dockerfile builds with. The
test passed locally on Node 24 and threw "object.stream is not a function" in
CI. Nothing in it asserts on the body, only that the object URL and filename
reach the anchor, so a string body is equivalent and works on both.

Surfaced by the CI workflow added in this branch, which is the first thing in
this repo to run the frontend suite anywhere but a developer's machine.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 26, 2026
@Quick104
Quick104 force-pushed the feat/settings-contract branch from 75b17b3 to 45ca765 Compare July 26, 2026 15:28
Both Dockerfiles copy cmd/, internal/, migrations/ and web/embed.go, but the
manifest lives in contracts/settings/v1 — an embedded Go package that sits
outside internal/ because clients vendor those files. The image build therefore
fails with "no required module provides package .../contracts/settings/v1".

Caught deploying to the dev box. Nothing had built an image since the manifest
landed: the Docker workflow only runs on pushes to main and workflow_dispatch,
and CI's go build runs against a full checkout, so neither gate covers the
container context. This would have broken the published image on merge.

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.

Actionable comments posted: 8

🧹 Nitpick comments (4)
web/src/hooks/themePreferences.ts (1)

25-27: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider exporting a useAppearanceCacheOwner() hook alongside this function.

All three consumers (useTheme.tsx, useCustomTheme.ts, useDateTimeFormat.tsx) repeat the identical useOptionalAuth() → { loading: auth?.loading ?? false, user: auth?.user ? { id: auth.user.id } : null } adapter. Wrapping that in a hook here keeps the whole owner derivation — auth shape included — in one place, which is the property the doc comment is arguing for.

🤖 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 `@web/src/hooks/themePreferences.ts` around lines 25 - 27, The repeated
auth-to-owner adapter should be centralized in a hook. Add and export
useAppearanceCacheOwner() alongside appearanceCacheOwner(), have it call
useOptionalAuth(), normalize loading and user into AppearanceAuth, and return
appearanceCacheOwner()’s result; update useTheme.tsx, useCustomTheme.ts, and
useDateTimeFormat.tsx to use the new hook instead of duplicating the adapter.
internal/settingscontract/load.go (1)

177-215: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider filtering schemas/ entries to .json files only.

compileObjectSchemas parses every non-directory file under schemas/ as a JSON Schema. A stray non-JSON file in that directory (e.g. an accidentally committed .DS_Store) would fail parsing and, via MustLoad, panic the server at startup rather than surfacing as a manifest content problem. Filtering by the same .json suffix already required by schema_ref (^[a-z0-9-]+\.json$ in manifest.schema.json) would make this resilient to that class of accident.

♻️ Suggested filter
 		name := entry.Name()
+		if !strings.HasSuffix(name, ".json") {
+			continue
+		}
 		body, err := fs.ReadFile(fsys, path.Join(schemasDir, name))
🤖 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 `@internal/settingscontract/load.go` around lines 177 - 215, Update
compileObjectSchemas to skip non-directory entries whose names do not end with
the required .json suffix before reading or parsing them. Preserve processing of
JSON schema files and the existing compilation/error behavior for those files.
contracts/settings/v1/manifest.json (1)

406-428: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Track the ui_theme rename's plugin-lookup dependency before this ships.

The notes correctly flag that internal/plugins/user_theme_lookup.go still queries user_settings for the old key ui_theme at account scope, and that this key's rename to ui.theme (profile scope) will make that query match nothing — silently falling back to each plugin's default theme with no error surfaced. Since the manifest isn't wired to storage yet, this is safe today, but it's exactly the kind of follow-up that's easy to lose track of once implementation starts.

Want me to open a tracking issue for updating user_theme_lookup.go alongside whichever change actually switches storage/lookup to the new key?

🤖 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 `@contracts/settings/v1/manifest.json` around lines 406 - 428, Track the
required follow-up for internal/plugins/user_theme_lookup.go: update its raw SQL
lookup from the legacy ui_theme account-scoped setting to the new ui.theme
profile-scoped setting when manifest storage is wired. Ensure the lookup
preserves the X-Silo-Theme header behavior and supports the profile/device scope
defined by the ui.theme manifest entry.
cmd/silo/main.go (1)

399-413: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor inconsistency: MustLoad() panics while every other startup check uses log.Fatalf.

settingscontract.MustLoad() panics on an invalid manifest, whereas the immediately following ETag() error and every other startup failure in this function (bootstrap, secret cipher, database pool, migrations, etc.) fail via log.Fatalf. For consistency of startup failure UX (clean exit vs. a stack-trace dump), consider using Load() + log.Fatalf here too. Low risk in practice since the embedded manifest is already validated by TestEmbeddedManifestLoads/TestContractLoadsUnderTheServerBuild in CI.

♻️ Optional consistency fix
-	contract := settingscontract.MustLoad()
-	contractETag, err := settingscontract.ETag()
-	if err != nil {
-		log.Fatalf("settings contract: %v", err)
-	}
+	contract, err := settingscontract.Load()
+	if err != nil {
+		log.Fatalf("settings contract: %v", err)
+	}
+	contractETag, err := settingscontract.ETag()
+	if err != nil {
+		log.Fatalf("settings contract: %v", err)
+	}
🤖 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 `@cmd/silo/main.go` around lines 399 - 413, Replace settingscontract.MustLoad()
in the startup validation block with the error-returning Load() path, capture
its error, and terminate via log.Fatalf consistently with the subsequent ETag()
check and other startup failures. Preserve the existing contract logging and
ensure the contract is only used after successful loading.
🤖 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 @.github/workflows/ci.yml:
- Around line 47-60: Add the backend golangci-lint run step to the Go job in
.github/workflows/ci.yml at lines 47-60, alongside the existing Build, gofmt,
and Vet checks, matching the documented make lint command. Retain the
verification claim in AGENTS.md at line 91 because it will be accurate once the
workflow includes this lint gate.
- Around line 14-17: Restrict workflow credentials by adding workflow-level
permissions with contents read, and set persist-credentials to false on every
actions/checkout step. Update any private module authentication to use a
separately scoped credential rather than the checkout token.

In
`@docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md`:
- Around line 505-561: Update the “API delivery and compatibility” section to
explicitly address the v1 additive-only policy before removing the legacy
/api/v1/settings routes and DTO fields. Add either a documented policy exception
approved through the required process or a staged Deprecation/Sunset removal
plan, including the relevant transition behavior; do not rely solely on the
pre-lock rationale or route deletion.

In `@internal/audiobooks/abs_smart_collection_store.go`:
- Line 25: Update the profile_id schema comment to use the valid SQL
empty-string literal DEFAULT '' instead of the malformed typographic quote,
preserving the rest of the comment.

In `@internal/settingscontract/validate.go`:
- Around line 159-253: Thread the definition’s own IntroducedIn revision into
ValueSchema.validate and update its callers to pass that value. In the numeric
bound checks for minimum_introduced_in and maximum_introduced_in, and the
enum-member introduced_in check, reject nonzero revisions earlier than the
definition revision while preserving existing manifestRevision upper-bound
validation. Align the lower-bound error behavior with validateScopes.

In `@Makefile`:
- Around line 57-61: Remove the four newly added test names from
GOTEST_KNOWN_FAILURES in the Makefile so make test-go does not exclude them;
retain only existing entries and implement the corresponding test fixes instead
of adding exclusions.

In `@web/src/hooks/useCustomTheme.ts`:
- Around line 84-98: Scope the settingsKeys.list() and settingsKeys.detail()
cache reads and writes used by useCustomTheme, including both API-sync effects,
by the active account/profile identifier so cached theme variables and CSS
cannot cross account switches. Apply the same account/profile scoping to the
corresponding mirror effects in useTheme.tsx and useDateTimeFormat.tsx, reusing
the existing account-scoped key convention.

In `@web/src/hooks/useTheme.test.ts`:
- Around line 24-26: Update the beforeEach cleanup in useTheme tests to call
localStorage.clear() instead of iterating storage.KEYS with storage.remove,
ensuring appearanceCache entries and the UI_CACHE_OWNER pointer written by the
tests are removed between cases.

---

Nitpick comments:
In `@cmd/silo/main.go`:
- Around line 399-413: Replace settingscontract.MustLoad() in the startup
validation block with the error-returning Load() path, capture its error, and
terminate via log.Fatalf consistently with the subsequent ETag() check and other
startup failures. Preserve the existing contract logging and ensure the contract
is only used after successful loading.

In `@contracts/settings/v1/manifest.json`:
- Around line 406-428: Track the required follow-up for
internal/plugins/user_theme_lookup.go: update its raw SQL lookup from the legacy
ui_theme account-scoped setting to the new ui.theme profile-scoped setting when
manifest storage is wired. Ensure the lookup preserves the X-Silo-Theme header
behavior and supports the profile/device scope defined by the ui.theme manifest
entry.

In `@internal/settingscontract/load.go`:
- Around line 177-215: Update compileObjectSchemas to skip non-directory entries
whose names do not end with the required .json suffix before reading or parsing
them. Preserve processing of JSON schema files and the existing
compilation/error behavior for those files.

In `@web/src/hooks/themePreferences.ts`:
- Around line 25-27: The repeated auth-to-owner adapter should be centralized in
a hook. Add and export useAppearanceCacheOwner() alongside
appearanceCacheOwner(), have it call useOptionalAuth(), normalize loading and
user into AppearanceAuth, and return appearanceCacheOwner()’s result; update
useTheme.tsx, useCustomTheme.ts, and useDateTimeFormat.tsx to use the new hook
instead of duplicating the adapter.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e6ebf956-5f22-405c-92d8-2dfd77a68dbf

📥 Commits

Reviewing files that changed from the base of the PR and between 10394b0 and 75b17b3.

📒 Files selected for processing (35)
  • .github/workflows/ci.yml
  • AGENTS.md
  • Makefile
  • cmd/silo/main.go
  • contracts/settings/v1/embed.go
  • contracts/settings/v1/manifest.json
  • contracts/settings/v1/manifest.schema.json
  • contracts/settings/v1/schemas/library-page-state.json
  • contracts/settings/v1/schemas/subtitle-appearance.json
  • contracts/settings/v1/schemas/theme-var-overrides.json
  • docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md
  • go.mod
  • internal/api/handlers/settings_contract_test.go
  • internal/audiobooks/abs/bookmarks.go
  • internal/audiobooks/abs/jwt.go
  • internal/audiobooks/abs_smart_collection_store.go
  • internal/audiobooks/podcastfeed/refresher_test.go
  • internal/audiobooks/smartcoll/evaluator_test.go
  • internal/audiobooks/smartcoll/query_test.go
  • internal/models/library_collection.go
  • internal/models/marker_source.go
  • internal/settingscontract/canonical.go
  • internal/settingscontract/contract.go
  • internal/settingscontract/contract_test.go
  • internal/settingscontract/load.go
  • internal/settingscontract/validate.go
  • web/src/hooks/appearanceCacheOwnership.test.tsx
  • web/src/hooks/queries/admin/diagnostics.test.ts
  • web/src/hooks/themePreferences.ts
  • web/src/hooks/useCustomTheme.ts
  • web/src/hooks/useDateTimeFormat.tsx
  • web/src/hooks/useTheme.test.ts
  • web/src/hooks/useTheme.tsx
  • web/src/utils/storage.test.ts
  • web/src/utils/storage.ts
💤 Files with no reviewable changes (1)
  • internal/models/marker_source.go

Comment thread .github/workflows/ci.yml Resolved
Comment thread .github/workflows/ci.yml Resolved
//
// abs.SmartCollection.IsPublic maps to user_personal_collections.is_shared.
// profile_id is a text column (NOT NULL DEFAULT '') in the canonical
// profile_id is a text column (NOT NULL DEFAULT ”) in the canonical

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Restore the empty-string SQL literal in the comment.

DEFAULT ” is a malformed representation of the empty-string default. Keep the documentation as DEFAULT '' so it matches the actual schema notation.

Proposed fix
-// profile_id is a text column (NOT NULL DEFAULT ”) in the canonical
+// profile_id is a text column (NOT NULL DEFAULT '') in the canonical
📝 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
// profile_id is a text column (NOT NULL DEFAULT ”) in the canonical
// profile_id is a text column (NOT NULL DEFAULT '') in the canonical
🤖 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 `@internal/audiobooks/abs_smart_collection_store.go` at line 25, Update the
profile_id schema comment to use the valid SQL empty-string literal DEFAULT ''
instead of the malformed typographic quote, preserving the rest of the comment.

Comment thread internal/settingscontract/validate.go Resolved
Comment thread Makefile Resolved
Comment thread web/src/hooks/useCustomTheme.ts Resolved
Comment thread web/src/hooks/useTheme.test.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 044f159b79

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/settingscontract/validate.go Resolved
Comment thread internal/settingscontract/canonical.go Resolved
Comment thread .github/workflows/ci.yml
Comment on lines +59 to +60
- name: Vet
run: go vet ./...

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Run golangci-lint in the Go CI job

In .github/workflows/ci.yml's Go job, the only static checks are gofmt and go vet; the workflow never installs or runs golangci-lint, even though the repository's required pre-merge command is make lint and the same instructions state that CI runs those checks on every pull request. Consequently, a change that fails the documented Go lint gate can still pass all three CI jobs, so this job needs to install and execute the configured linter.

AGENTS.md reference: AGENTS.md:L82-L93

Useful? React with 👍 / 👎.

…fest declares

A sweep of all 43 manifest definitions against the running server (160 checks:
declared default, both boundaries, and deliberate violations for each remote
key) found two places where the live registry accepts what the contract
forbids. Both are fixed by calling the contract's own validators rather than
adding a second implementation.

playback.audio_language was checked as "32 characters or fewer", so the server
stored "!!!" for a field the manifest declares as language_tag — a value track
matching would then silently never match. It now requires a well-formed tag via
settingscontract.NormalizeLanguageTag. The empty string is still accepted: the
string-only endpoint has no way to send null, and both Android and web send ""
to clear the choice, so rejecting it would break clearing the preference.

player.playback_speed declared step 0.05 and nothing enforced it, so 0.26 was
stored — a value no client's stepper can represent and that every client would
silently snap on the next write. settingscontract.StepAligned is now exported
and used by both the contract validator and the registry, so there is one
definition of "on step" rather than two that can drift.

This gives the contract its first production consumer beyond the startup load,
which is the direction Phase 2 continues in.

Also fixes a genuinely flaky test that the new CI gate would have hit
intermittently: TestRemoveJellyfinCompatWebDisablesWebSetting used t.TempDir as
the install root, but the endpoint returns 202 and its goroutine keeps writing
there after the test body returns, so cleanup tripped "directory not empty"
roughly one run in four. Confirmed pre-existing and unrelated to settings; the
suite now passes six consecutive full-package runs.

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.

Actionable comments posted: 2

🤖 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 `@internal/api/handlers/jellyfin_compat_test.go`:
- Line 238: Update the test cleanup around the StartWebComponentRemove calls to
wait for the background removal operation to finish before invoking os.RemoveAll
on dir. Poll or use the operation’s completion mechanism, and only then clean up
the temporary directory so late writes cannot race with teardown.

In `@internal/api/handlers/settings_contract_test.go`:
- Around line 80-95: In the registryKey subtest, check for the nullable contract
case where spec.DefaultValue is empty and def.DefaultValue is null before
calling scalarDefault. Return immediately for that matching representation;
otherwise continue into scalarDefault and retain its existing skip and
comparison behavior so mismatches are detected.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ad94e8eb-9179-4a85-b192-da5a22df47e0

📥 Commits

Reviewing files that changed from the base of the PR and between 75b17b3 and a1bf79c.

📒 Files selected for processing (39)
  • .github/workflows/ci.yml
  • AGENTS.md
  • Dockerfile
  • Dockerfile.dev
  • Makefile
  • cmd/silo/main.go
  • contracts/settings/v1/embed.go
  • contracts/settings/v1/manifest.json
  • contracts/settings/v1/manifest.schema.json
  • contracts/settings/v1/schemas/library-page-state.json
  • contracts/settings/v1/schemas/subtitle-appearance.json
  • contracts/settings/v1/schemas/theme-var-overrides.json
  • docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md
  • go.mod
  • internal/api/handlers/jellyfin_compat_test.go
  • internal/api/handlers/settings.go
  • internal/api/handlers/settings_contract_test.go
  • internal/audiobooks/abs/bookmarks.go
  • internal/audiobooks/abs/jwt.go
  • internal/audiobooks/abs_smart_collection_store.go
  • internal/audiobooks/podcastfeed/refresher_test.go
  • internal/audiobooks/smartcoll/evaluator_test.go
  • internal/audiobooks/smartcoll/query_test.go
  • internal/models/library_collection.go
  • internal/models/marker_source.go
  • internal/settingscontract/canonical.go
  • internal/settingscontract/contract.go
  • internal/settingscontract/contract_test.go
  • internal/settingscontract/load.go
  • internal/settingscontract/validate.go
  • web/src/hooks/appearanceCacheOwnership.test.tsx
  • web/src/hooks/queries/admin/diagnostics.test.ts
  • web/src/hooks/themePreferences.ts
  • web/src/hooks/useCustomTheme.ts
  • web/src/hooks/useDateTimeFormat.tsx
  • web/src/hooks/useTheme.test.ts
  • web/src/hooks/useTheme.tsx
  • web/src/utils/storage.test.ts
  • web/src/utils/storage.ts
💤 Files with no reviewable changes (1)
  • internal/models/marker_source.go
🚧 Files skipped from review as they are similar to previous changes (25)
  • internal/audiobooks/abs/jwt.go
  • internal/audiobooks/abs/bookmarks.go
  • contracts/settings/v1/schemas/library-page-state.json
  • contracts/settings/v1/embed.go
  • internal/audiobooks/podcastfeed/refresher_test.go
  • contracts/settings/v1/schemas/subtitle-appearance.json
  • web/src/hooks/useTheme.test.ts
  • contracts/settings/v1/schemas/theme-var-overrides.json
  • internal/models/library_collection.go
  • web/src/utils/storage.test.ts
  • contracts/settings/v1/manifest.schema.json
  • AGENTS.md
  • web/src/hooks/appearanceCacheOwnership.test.tsx
  • Makefile
  • contracts/settings/v1/manifest.json
  • web/src/utils/storage.ts
  • internal/settingscontract/load.go
  • web/src/hooks/useDateTimeFormat.tsx
  • docs/superpowers/specs/2026-07-10-cross-platform-user-settings-contract-design.md
  • go.mod
  • web/src/hooks/useTheme.tsx
  • internal/settingscontract/contract.go
  • internal/settingscontract/contract_test.go
  • internal/settingscontract/canonical.go
  • internal/settingscontract/validate.go

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a1bf79c5f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/settingscontract/validate.go Resolved
Comment thread web/src/hooks/useTheme.tsx Resolved
Quick104 added 6 commits July 27, 2026 00:12
A bound was one scalar plus the revision that introduced it, which discards
the value it replaced. Widening a maximum from 240 to 480 at revision 3 left
a revision-3 client with no correct answer against a revision-1 server:
honoring 480 offers values that server rejects, and filtering the tagged
bound out leaves the setting unbounded. Since clients are specified to filter
their pinned contract against the server's advertised revision, the bound has
to carry what it used to be.

Bounds now hold their full history, oldest first, and AtRevision hands back
the limit a given peer actually enforces. A bound nobody has widened still
serializes as a bare number, so the manifest reads the same and untouched
entries do not churn the ETag.

Validation gains the rules the representation makes checkable: a maximum may
only grow and a minimum may only shrink, history is strictly ordered, later
entries must say when they arrived, and the first entry cannot predate the
definition. That last rule is the lower bound allowed_scopes already
enforced; the same gap is closed for enum members, which could previously
claim to predate the definition containing them.

Reported by Codex review on #479.
… stored

The schema required all nine properties, but the current API accepts and
round-trips sparse objects — settings_device_test.go stores
{"fontSize":"xxlarge"} and reads it back — and the web client has always
merged whatever it gets over DEFAULT_SUBTITLE_APPEARANCE. Requiring the full
object would have made the cutover migration quarantine preferences users
really set, or block on them.

Every property is now optional and a stored value is documented as a sparse
override merged over the definition's complete default. An empty object is
still rejected: an override that overrides nothing is the same state as no
override, which the contract represents as unset.

Cross-scope resolution is deliberately unchanged. A device override still
replaces the profile's object rather than merging into it, because a device
override means "draw subtitles this way on this screen", not "amend the
profile" — and that is what the server does today.

Reported by Codex review on #479.
Autoscan matched scantrigger rejections by comparing RequestError.Message
against literal strings. One of those messages became "Unsupported media file
extension for library type" and the copy in handlers_autoscan.go did not, so
the comparison silently stopped matching.

The effect is user-visible: a Jellyfin client posting a change for Movie.nfo
or poster.jpg gets a 400 and the batch is abandoned, when the sidecar should
have resolved to a scan of the directory containing it. Three tests covered
exactly this and had been excluded rather than read.

RequestError now carries a Reason the caller can switch on. Message stays
prose for the client reading the response — it is meant to be reworded, and
nothing should break when it is.

Also makes two tests honest about asynchronous work. The Jellyfin Web
teardown deleted its install root while the operation goroutine was still
writing to it, where a late write recreates a path RemoveAll already walked
past; it now waits for the operation's terminal state, which required
exporting CurrentWebOperation. And the direct-play If-Range test pinned size
and mtime so ctime was the only remaining validator, then read it back inside
a single coarse-clock tick — it failed about 85% of the time on main for a
reason unrelated to what it tests, and now rewrites until the stamp moves.

With those fixed, GOTEST_KNOWN_FAILURES is empty and gone: make test-go runs
the whole Go suite. The one test that cannot pass yet —
TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion, which
has failed since the commit that introduced it and describes unimplemented v3
planner behavior — carries a t.Skip explaining that where the test is, rather
than a regex in the Makefile.

Reported by CodeRabbit review on #479.
Two cases where encoding/json accepts input by quietly changing it, which is
the one thing a contract promising byte-identical agreement between peers
cannot tolerate.

Duplicate object properties. jsonschema.UnmarshalJSON keeps the last
occurrence, so {"fontSize":"small","fontSize":"large"} validated and stored
"large". Which one wins is a property of the parser, not of the contract: a
client generated against a different JSON library can disagree about what it
just sent, and the canonical form cannot represent the duplicate at all.

Lone surrogates. An unpaired \ud800 became U+FFFD and canonicalization
reported success, so the server would issue canonical bytes and an ETag for
an artifact a conforming implementation must refuse — RFC 8785 requires
terminating here. Substitution also means the value read back is not the
value written.

Both checks run before the decode that would hide them, on the shared
decodeJSON path that the manifest, its public projection and every value
schema go through, and again on the object branch of ValidateValue, which
uses a different decoder.

Reported by Codex review on #479.
AGENTS.md told contributors CI ran the same checks as `make lint`, and the Go
job ran only gofmt and vet. A change failing the documented Go lint gate
passed all three jobs.

Running the linter as-is is not an option: the tree has ~296 findings today,
which is why this half of `make lint` was never enforced. Blocking every PR
on a cleanup nobody has scheduled gets the gate deleted again, so CI runs
with --new-from-merge-base and only the lines a branch touches have to be
clean. The count can then only fall.

golangci-lint is built from source at a pinned version rather than
downloaded. A released binary refuses to run against a Go newer than the one
it was built with, and go.mod here tracks Go closely enough that the current
release already fails that way on 1.26.4.

.golangci.yml declared version 2 while still using v1's issues.exclude-rules
key. Current golangci-lint ignores it, so the "allow repeated strings and
unchecked cleanup errors in tests" exclusions silently did not apply — 16
findings in test files that the config says to skip. Moved to
linters.exclusions, which `golangci-lint config verify` accepts.

The four lines this surfaced in scantrigger are fixed rather than excluded:
its repeated status codes and messages are now named constants, so one
condition cannot end up worded two ways.

Also drops the workflow token to contents:read and stops persisting
credentials in the three checkouts, neither of which any job needs.

Reported by CodeRabbit and Codex review on #479.
The design removes the legacy /api/v1/settings routes and the profile DTO
preference fields, while AGENTS.md states /api/v1 is additive-only and
removals go through Deprecation/Sunset. Read together those contradict.

They do not actually conflict: v1-scope.md scopes the additive-only rule to
"when the scope locks", and the scope is still open, so a removal taken now
is in scope and there is no amendment process to invoke yet. But that
reasoning lived only in the settings design, where nobody checking the API
policy would find it.

v1-scope.md now carries a pre-lock removals table naming what goes and why
waiting is worse, and states the deadline the argument depends on: a removal
listed there must ship before lock or fall back to Deprecation/Sunset.
AGENTS.md points at the table and says to treat an unlisted removal as a
mistake.

Reported by CodeRabbit review on #479.
Three from the review of the pushed work:

- The live profile sync omitted auto_skip_intro/credits/recap and
  auto_play_next_preview, which my own change made load-bearing: the
  player now resolves those keys canonically, so a legacy PUT /profiles
  moved the columns, returned 200, and changed nothing about playback.
  All four now mirror on write. The DTO read block keeps its shape —
  clients pin it — and its columns are what the sync keeps current.

- The effective endpoint dropped unknown keys silently, letting a
  client fill the gap with its own vendored default and present a value
  this server would refuse to store. Unknown keys now 404 by name.

- Two sidebar-pin toggles in flight at once could commit in either
  order, and the server upsert is last-write-wins, so the first request
  landing second restored the pre-toggle document. The writes are now
  chained, and each link reads the document when it runs, so a queued
  toggle sends the newest state rather than the one it was queued with.

Co-Authored-By: Claude Fable 5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 197f86528d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

) {
return;
}
setValue.mutate({ key: SETTING_KEYS.UI_CARD_OVERLAYS, value: next, identity: PROFILE_SCOPE });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep pending card-overlay edits composed

When a user changes two overlay controls before the first PUT and refetch complete, both full-document values are built from the same stale userValue because useSetSettingValue does not update the effective-settings cache optimistically. The second document therefore omits the first edit, and whichever request reaches the server last silently discards one of the user's changes; retain an optimistic local document or serialize and merge these saves.

Useful? React with 👍 / 👎.

}

// DeleteForSeries removes every user's profile_series values for one series.
func (c *SettingValuesCleaner) DeleteForSeries(ctx context.Context, seriesID string) int64 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wire series cleanup into deletion paths

When library deletion or scanner reconciliation removes an actual series, no production path calls this method—a repo-wide search finds DeleteForSeries only here, while the library-delete executor invokes only DeleteForLibrary and scanner paths delete media_items directly. The corresponding profile_series rows therefore accumulate indefinitely and can restore stale language/subtitle choices if the stable series ID is imported again; invoke this cleanup for the IDs actually deleted.

Useful? React with 👍 / 👎.

subtitle_track_index: index ?? -1,
subtitle_mode: mode,
track_signature: trackSignature,
show_forced_subtitles: showForcedSubtitles,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stop track changes from pinning forced-subtitle behavior

Whenever the web player changes a subtitle track, showForcedSubtitles is a resolved boolean and is included here, but HandleSetSubtitlePref treats a present value as an authored preference and writes it to playback.show_forced_subtitles at profile_series scope. That row outranks the profile setting, so merely selecting a track permanently prevents later changes to the profile-level forced-subtitle toggle from affecting this series; omit the resolved field from this legacy request or keep it out of the canonical sync unless the user explicitly edited it.

Useful? React with 👍 / 👎.

Comment on lines +745 to +746
if value, err := strconv.Atoi(part); err == nil && value > 0 {
out = append(out, value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject malformed library resolution contexts

When library_ids contains a typo, zero, or a negative value, this parser silently drops that context and the effective endpoint proceeds with the remaining scopes. A request intended to resolve a library override can therefore return a plausible device/profile fallback instead of reporting the malformed context, causing clients to act on the wrong setting; validate every supplied token and return 400 if any library ID is invalid.

Useful? React with 👍 / 👎.

Quick104 and others added 2 commits July 29, 2026 19:33
Rolling back this release meant restoring a backup, for a reason that
was not obvious: the DisplayPreferences move deletes the jellycompat
rows from user_settings once it has copied them, and the previous
binary reads exactly those rows. An older server therefore starts
cleanly and silently serves defaults, so every Jellyfin client's saved
view preferences look reset.

The down functions were already written and correct — nothing could
invoke them. The backfill and the DisplayPreferences move are Go
migrations registered in-process, so the standalone goose CLI in the
Makefile cannot see them, and the server exposed only --migrate-only
and --migrate-status.

Adds MigrateDownTo, the --migrate-down-to flag, and a make target, plus
a rehearsal test that seeds a legacy row the way the old binary wrote
it, applies the move, rolls back, and asserts the row returns
byte-for-byte.

Documents the ordering in the spec's cutover section, including the two
caveats an operator needs beforehand: take a backup, and the per-user
SQLite backend cannot be rolled back at all — its migrations have no
down path and an older binary refuses to open a newer database, so
those installs restore from backup rather than degrade.

Co-Authored-By: Claude Fable 5 <[email protected]>
The dev-server migration aborted on real data:

  writing playback.subtitle_appearance at profile_device for user 1:
  violates foreign key constraint user_setting_values_profile_fkey

user_device_settings carries an ON DELETE CASCADE on (user_id,
profile_id) today, but rows written before that constraint outlived the
profiles they belonged to — that install had 46 such rows across 14
deleted profiles. The planner copied them faithfully and the canonical
table, which declares the same foreign key, refused them; because the
backfill runs in one transaction, the whole migration failed and the
server could not start.

An override belonging to a profile nobody can select is not a preference
anyone can be shown or reset, so Plan now drops those rows rather than
repairing them, recording each in user_setting_migration_rejects so an
operator can see what was left behind. Account-scope rows carry no
profile and pass through untouched.

Verified by replaying that install's 514 device rows through the
planner: 9 rows would have hit the constraint before, 0 after.

Co-Authored-By: Claude Fable 5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

seriesPref := r.audioPreference(ctx)
preferredLang := r.profileLanguage(ctx)
libraryAudioLang := ""

P1 Badge Resolve canonical series audio overrides in track selection

When a client writes playback.audio_language at profile_series through the canonical API, track selection still obtains the series language exclusively from the legacy GetAudioPreference row here; the canonical resolver is invoked only with profile or library context and never with this series ID. The accepted canonical write therefore has no playback effect, while any stale legacy language can continue winning; keep the specialized track index/signature lookup but resolve the language with the series context.

AGENTS.md reference: AGENTS.md:L67-L69

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/settingsmigrate/plan.go Outdated
Comment on lines +417 to +419
p.addQuality(res, sourceUserProfiles, id("quality_preference"),
settingscontract.ScopeProfile, Row{ProfileID: profile.ID},
deref(profile.QualityPreference), defaultQualityPreference)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the legacy 1080p playback default

For an existing profile still holding the schema default quality_preference = '1080p', passing defaultQualityPreference suppresses the canonical row even though the contract default is auto. The old playback path therefore capped this profile at 1080p, but useQualityPreference switches from its legacy-column fallback to the canonical auto result as soon as the query loads, silently removing that cap and potentially selecting 4K/original-quality streams; preserve 1080p explicitly or use an equivalent contract default.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment thread internal/api/router.go
Comment on lines +2360 to +2361
r.Get("/values/effective", settingValuesHandler.HandleGetEffective)
r.Get("/values/{key}", settingValuesHandler.HandleGetValue)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Expose the documented explicit-values endpoint

Clients following the committed contract call GET /api/v1/settings/values?keys=...&scope=..., but the checked router mounts only /values/effective and the incompatible per-key /values/{key} form; a repo-wide route search finds no collection handler. Such clients receive 404 and cannot independently inspect profile defaults and device overrides or represent the documented is_set: false result, so mount the specified collection route or coordinate the contract and client bindings before release.

AGENTS.md reference: AGENTS.md:L67-L69

Useful? React with 👍 / 👎.

Comment thread internal/database/displayprefs_move.go Outdated
Comment on lines +151 to +154
if _, err := tx.ExecContext(ctx, `
DELETE FROM jellycompat_displayprefs
WHERE user_id = $1 AND prefs_id = $2 AND client = $3`,
row.userID, row.prefsID, row.client,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve concurrent writes during DisplayPreferences rollback

If migrate-down-to runs while any new-binary instance is still serving DisplayPreferences writes, this delete can remove a value updated after unmoveDisplayPrefs performed its SELECT, because it matches only the identity rather than the value read. The legacy table then contains the older snapshot while the newer preference is lost; include the selected value in the delete predicate, mirroring the guarded up-migration delete.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +2700 to +2704
resolved, err := s.settingsResolver().Resolve(ctx, store, rc, []string{
settingskeys.PlaybackSubtitleLanguage,
settingskeys.PlaybackSubtitleMode,
settingskeys.PlaybackShowForcedSubtitles,
}, nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Dual-write legacy library playback preferences

When a shipped client updates or deletes preferences through PUT/DELETE /library-playback-prefs/{library_id}, that handler still changes only user_library_playback_preferences, while this canonical-only subtitle resolution and libraryAudioLanguage now read user_setting_values. Because the backfill runs only once, later language, subtitle-mode, and forced-subtitle changes return success but do not affect playback, and deletes leave migrated canonical overrides active; dual-write/clear the corresponding profile_library rows or retain the legacy fallback during cutover.

AGENTS.md reference: AGENTS.md:L67-L69

Useful? React with 👍 / 👎.

Comment on lines +617 to +621
libraryID, err := strconv.Atoi(strings.TrimSpace(query.Get("library_id")))
if err != nil || libraryID <= 0 {
writeError(w, http.StatusBadRequest, "bad_request",
"library_id is required for a library override")
return userstore.SettingIdentity{}, false

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject nonexistent library override contexts

When a canonical mutation supplies any positive but nonexistent library_id, this path accepts it and stores a profile_library row without consulting the catalog; the legacy library-preference handler explicitly calls ensureLibraryExists first. A typo therefore returns success and creates an orphan that no library deletion can clean up, and it may become active if that ID later appears; validate the library context before set/get/delete, including the shared admin path.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment thread internal/settingsmigrate/plan.go Outdated
Comment on lines +317 to +321
res.Rejects = append(res.Rejects, Reject{
SourceTable: sourceUserDeviceSettings,
SourceKey: row.Key,
Identity: identityJSON(map[string]any{
fieldProfileID: row.ProfileID,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve orphan reject provenance

When the orphan filter drops a row originating from user_subtitle_preferences, user_audio_preferences, or user_library_playback_preferences, every reject is mislabeled as user_device_settings and its identity records device_id instead of the actual series or library ID. The audit row consequently cannot identify the source or content context needed to inspect or restore the quarantined preference; carry each row's source provenance through planning and serialize the scope-appropriate identity.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +54 to +58
input, err := readLegacySettingsForUser(ctx, tx, userID)
if err != nil {
return fmt.Errorf("reading legacy settings for user %d: %w", userID, err)
}
result := planner.Plan(input)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Quiesce legacy writes during the settings backfill

During a rolling deployment, an old server can update a profile or legacy settings row after readLegacySettingsForUser has read it but before this migration commits. The transaction takes no locks on those source rows, so the canonical table retains the earlier value and the successful later write becomes invisible as soon as new readers switch to canonical resolution; stop legacy writers, lock the source data, or dual-write/catch up changes across the cutover.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f11fb59897

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/api/router.go
r.Group(func(r chi.Router) {
r.Use(apimw.RequireProfile)
r.Get("/values", settingValuesHandler.HandleGetValues)
r.Get("/values/effective", settingValuesHandler.HandleGetEffective)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Expose the batched effective-values endpoint

When a season or list needs settings for multiple content contexts, the committed contract requires POST /api/v1/settings/values/effective with a context array, but the router registers only this GET and a repo-wide route/handler search finds no POST implementation. The GET cannot substitute for it: multiple series_ids or library_ids are collapsed into one candidate set and pickForScope selects the first sorted override, so conforming clients receive 405 and must either apply one item's preference to the whole batch or issue the per-item requests the contract explicitly rejects.

AGENTS.md reference: AGENTS.md:L67-L69

Useful? React with 👍 / 👎.

"user_setting_values",
"user_setting_migration_rejects",
} {
if _, err := tx.ExecContext(ctx, "DELETE FROM "+table); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve canonical edits during rollback

When an operator rolls back after users have changed settings through the canonical API, this deletes every current row rather than only the rows derived by the backfill. For example, a post-upgrade playback.subtitle_language write does not update the legacy profile column, so rollback restores the stale column value, and a later re-upgrade backfills that stale value permanently; copy representable canonical values back to legacy storage before clearing the table or otherwise retain runtime-authored rows.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +128 to +130
StoredValue json.RawMessage `json:"stored_value,omitempty"`
Constrained bool `json:"constrained,omitempty"`
ConstraintKind string `json:"constraint_kind,omitempty"`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Match the documented constraint response shape

When policy caps a setting such as preferred quality, clients implemented against the added contract expect requested_value, a constrained_by object, and permitted_values, but this response emits the incompatible names stored_value and constraint_kind and never provides the permitted choices. Such clients therefore see only the capped value and cannot explain the user's authored choice or restrict the picker as the contract requires; align the response fields or coordinate the contract and client bindings.

AGENTS.md reference: AGENTS.md:L67-L69

Useful? React with 👍 / 👎.

Comment thread internal/policy/viewer_resolver.go Outdated
// value unchanged as a preference; the manifest deliberately declares no
// constraint on it, since constraining a setting by a policy input fed
// from that same setting would be circular.
policyInput.ProfileMetadataLang = access.PreferredMetadataLanguage(ctx, store, input.ProfileID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Batch canonical settings in viewer resolution

On every profile-bound request under RequireViewerAccess, DisabledLibraryIDs now performs a canonical settings query and usually a legacy fallback query, and this subsequent call performs another independent canonical query for metadata language. Because viewer scope is resolved for essentially every authenticated API route, the cutover adds two database round trips to the hot request path for the common unset case; resolve both canonical keys in one store read and reuse those results when applying the legacy fallback.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment thread internal/settingsmigrate/plan.go Outdated
Comment on lines +314 to +315
if len(profiles) == 0 {
return rows

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject orphan rows when the profile list is empty

When a legacy account has zero current profiles but still has an account setting plus an orphan device, series, or library preference, the production backfill has read the profile table and an empty slice means there are no valid profile IDs—not that validation was unavailable. This early return passes the orphan through, and inserting its nonempty profile_id into PostgreSQL then violates the canonical composite profile foreign key and aborts the entire server migration; treat an empty loaded profile list as an empty allowlist and record every profile-scoped row as a reject.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +1481 to +1483
// Counted from the canonical rows rather than the endpoint's override_count,
// which is computed over the legacy table and would disagree with the rows
// rendered below.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count canonical overrides in the device fleet

After a device override is written through the new canonical API, this detail panel correctly counts it from overrides, but the fleet rows still use /admin/devices summaries whose handler builds override_count, profile counts, and timestamps exclusively from legacy ListAllDeviceSettings rows. Canonical-only devices therefore appear to have zero overrides in the list, disappear under “Overrides only,” and produce incorrect group totals and anomaly flags even while their detail panel shows the stored overrides; derive the fleet summaries from canonical rows as well.

Useful? React with 👍 / 👎.

key = canonicalDeviceSettingKey(key)
spec, ok := settingsRegistry[key]
return !ok || spec.Scope == scopeUser
return ok && spec.Scope == scopeUser

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Mirror surviving legacy settings writes canonically

When a shipped client uses the still-mounted PUT/DELETE /settings/{key} or /settings/device/{key} routes after migration, these predicates continue accepting registered keys but the handlers mutate only user_settings or user_device_settings. New consumers resolve keys such as ui.date_format, search.media_scope, and playback preferences exclusively from user_setting_values, so a successful legacy update is ignored and a legacy delete leaves the migrated canonical override active; dual-write or clear the corresponding profile and profile-device rows until all clients cut over.

AGENTS.md reference: AGENTS.md:L67-L69

Useful? React with 👍 / 👎.

Comment thread internal/plugins/http_proxy.go Outdated
// The browser already sends X-Profile-Id for its own silo API
// calls; reuse that as the active profile for both lookups. Empty
// just means "no profile selected".
profileID := r.Header.Get("X-Profile-Id")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Carry the active profile into plugin navigation

When a user opens a plugin through navigateToPluginRoute, the full-page browser navigation cannot include X-Profile-Id—the navigation helper only prepares a launch cookie and appends ?theme=. Consequently this value is empty, LookupUITheme skips the new canonical profile row, and the proxy injects the stale legacy account theme or no X-Silo-Theme at all on subsequent plugin requests; carry the profile through a navigation-safe server-side or URL mechanism.

Useful? React with 👍 / 👎.

Quick104 added a commit to Silo-Server/silo-android that referenced this pull request Jul 30, 2026
* fix(settings): send language tags, not display names

playback.audio_language and the profile's subtitle_language are BCP 47
language tags in the server's settings contract. The phone put the display
label on the wire verbatim — "English", not "en" — and the TV did the same
for audio while doing it correctly for subtitles.

That was already broken before the server started enforcing it: the same
string is handed to ExoPlayer as preferredAudioLanguage, and
setPreferredAudioLanguage("English") never matches a track tagged eng, so
choosing an audio language on Android has silently been a no-op. It also
meant Android and Apple wrote different vocabularies to the same key —
Apple has always sent codes, so a language picked on an iPhone read as
"Default" on the phone and vice versa.

Now that the server validates the tag, the flusher's PUT 400s and only
logs, so the setting would stop persisting entirely after a server upgrade.

Replaces the four drifted option lists with one table in shared, so a
language cannot be added to one surface and missed on the others, and
translates values already on devices on read rather than re-sending a
label the server will reject.

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

* feat(settings): adopt the generated contract bindings

SettingKeys.kt is generated from the server's manifest by cmd/settingsgen,
so this client cannot drift from the contract by editing a constant.

The two hand-maintained tables in AndroidPlayerSettingsStore now delegate to
it. BOOLEAN_KEYS/INT_KEYS/DOUBLE_KEYS was a second table that had to agree
with PlaybackSettingsKeys.DeviceSettings by discipline alone — a key added
to one and missed in the other flushes as the wrong type and is silently
dropped on read. Only the granular subtitle appearance fields stay local,
since the contract carries them as one composite object.

A new contract test caught two real drifts, both of which are the
disagreements the contract exists to end:

  subtitle_appearance -> playback.subtitle_appearance. Every other key
  carries a domain prefix; this one never did.

  player.next_up_prompt_seconds -> playback.next_up_prompt_seconds. Android
  shipped player.* while Apple and the server used playback.*, so the same
  preference was two settings and neither client could read the other's.

Both are wire-format changes with no dual-write, which is what the
coordinated cutover is for.

Part of the cross-platform settings contract (Silo-Server/silo-server#479).

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

* feat(settings): add the canonical settings API client

The clients adopted the generated contract bindings but still speak only
the legacy string-only settings registry; nothing calls the canonical
/settings/contract or /settings/values routes. This adds that surface to
SettingsApi, mirroring the server's settings_values.go shapes exactly:

- getContractCapabilities() probes /settings/contract/capabilities and
  returns a sealed SettingsCapabilitiesResult. A 404 means the server
  predates the canonical API entirely, so it is a typed
  ServerUpgradeRequired case the UI can present as "this server needs an
  upgrade" instead of an empty settings screen.
- getEffectiveValues(keys, libraryIds, seriesIds) hits the batched
  /settings/values/effective resolution: typed JSON values, the source
  scope of each answer, constraint reporting (value vs stored_value),
  and the contract revision the resolution was computed at.
- putValue/deleteValue address one scope explicitly via a validated
  SettingScopeIdentity: scope + library_id/series_id ride the query, the
  profile and device identity ride the session headers the auth
  interceptor already attaches (with a setDeviceSetting-style optional
  profileId override), matching how the server derives the identity so
  one profile cannot write another's settings by naming it.
- Writes carry X-Silo-Mutation-Id from newSettingMutationId(): one UUID
  per logical write, held across retries, so the flusher's retries
  replay the recorded receipt instead of re-applying, and a reused id
  with different content surfaces as 409 mutation_id_conflict.

Wire models live in SettingValueModels.kt beside the legacy models;
response scope/source fields stay raw strings so a server that adds a
scope cannot break deserialization. Shared unit tests cover the
serialization round-trips, the query/header/body encoding, and the
upgrade-required mapping for both routeless (plain-text) and JSON 404s.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): flush and refresh device settings through the canonical API

ServerSettingsFlusher now writes to PUT/DELETE /api/v1/settings/values/{key}
at scope=profile_device with values encoded as the contract's JSON types
(classified by the generated SettingKeys.BOOLEAN_KEYS/INT_KEYS/DOUBLE_KEYS
sets; subtitle appearance goes up as its JSON object, and an empty language
tag as JSON null because the server's language_tag validator rejects "").
The 750ms debounce semantics are unchanged.

The old failure handling was a named defect: a failed PUT logged at Log.w
and dropped the write, so any server hiccup silently turned settings
non-persistent. Now a transient failure (network, 5xx, 408/429/401) keeps
the op queued and retries it with the SAME mutation id — minted once per
logical write via newSettingMutationId() — so the retry is an idempotent
replay the server can dedupe, first on a capped backoff and after that on
the next enqueue/flushNow trigger. Only a response that proves retrying is
pointless (contract rejection, mutation-id conflict) drops the op, and
every failure is logged at warning level with the key and status through
SiloLog. A delete answered 404 not_found is treated as already done.
Non-contract keys (the granular subtitle.* fields Android flattens out of
the composite appearance object) never reach the server, where they would
404 as unknown_setting.

AndroidPlayerSettingsStore.refreshFromServer() now hydrates from the
batched GET /settings/values/effective: typed JSON parsed per the generated
type sets, and a key nothing is stored for arrives as the contract default
with source "default" — so defaults come from the contract, never from a
hardcoded fallback, and a value reset from another device snaps back on
refresh. The subtitle device-override flag now derives from the resolved
scope (profile_device) instead of the legacy has_device_override field. A
key absent from the response means the server's contract predates it, so
the local value is kept. resetAllDeviceSettings deletes only server-stored
keys.

Part of the canonical settings API adoption; the API surface itself landed
in the previous commit.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): write profile and quality preferences at canonical scopes

The subtitle triple (language, mode, forced) and the metadata language rode
named columns on PUT /profiles/{id}. The server still accepts them, but every
server-side reader resolves those preferences canonically from
user_setting_values, so the column write only takes effect via the mirror the
server keeps until cutover. Android now writes them itself, at scope=profile,
one key per edit — a failed write no longer reverts the other two, which is
what sending the whole triple every time did.

Reads come from the batched effective endpoint rather than the profile object,
so a value set on another device, or narrowed by policy, is what the screen
shows. Both apps go through one shared ProfileSettingsController: this repo's
history has the TV screen missing behaviors the phone has, and a behavior that
lives in one class cannot be present on one platform only.

Quality becomes the two axes the contract actually stores —
playback.preferred_quality (resolution) and playback.max_bitrate_kbps
(bandwidth, null = uncapped) — behind one preset picker whose table is a port
of the web client's qualityPresets.ts. Presets stay client-side on purpose:
retuning what "1080p High" means is a client release, not a contract break.
The compound legacy spellings ("1080p-high") are dead and never written; a
stored one is decomposed on read, dropping the bitrate it encoded rather than
inventing a cap the user never chose.

Subtitle appearance keeps its granular subtitle.* fields client-local (the
contract carries one composite object and would refuse them as unknown_setting)
but they are no longer stranded there: they project into
playback.subtitle_appearance on flush, so a per-field edit reaches the server,
and a resolved appearance flattens back into them so the overlay cannot
resurrect the value the server just replaced.

A server that predates the canonical settings API 404s the contract probe.
Both settings screens now say so instead of rendering rows whose edits
silently go nowhere; playback keeps working from the device-scoped defaults.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(settings): add the cross-platform conformance runner

The settings contract names four resolvers that must agree: Go in
internal/settingsresolve, TypeScript in web/src/lib, Swift in the Apple
clients, and Kotlin here. Three of them ran the shared conformance
fixture; Kotlin did not, so nothing caught this client resolving a
setting differently from the server until a user saw the wrong value.

Vendors contracts/settings/v1/conformance.json byte-identically, plus
the manifest it was authored against. The manifest is needed because the
generated SettingKeys bindings carry key names and a coarse type table
but not the facts resolution turns on — resolution_order, default_value,
enum member order with its `ordered` flag, and constrained_by. Copying
those into Kotlin by hand would recreate exactly the drift the contract
exists to remove, so the runner parses the manifest and is driven by it.
No generator change is required.

The resolver lives in test sources on purpose. Android does not resolve
settings in production: it writes through /settings/values and reads
effective values back, leaving the server the single authority. This
exists so the fixture has a fourth independent implementation to
disagree with, which is what makes it a drift gate rather than a
tautology.

Four things fail the suite, each of them drift: a resolution
disagreement, a revision mismatch across the fixture / vendored manifest
/ generated bindings, a key those two JSON files disagree about (which
catches them being vendored from different server commits — skew the
revision check cannot see), and any fixture field the runner does not
recognize. The last one is why decoding is strict: a field one platform
reads and another silently skips means the platforms have stopped
running the same cases, and a silent skip is indistinguishable from a
pass.

Verified by mutating the resolver and confirming the suite fails:
reversed resolution order, a null bitrate slipping past a ceiling, a
floor capping an unbounded value, allowlist falling back to the
definition default, locked narrowing an already-equal value, ordered
enum ranking disabled, and foreign-profile rows resolving. Each gate was
mutation-tested too. One mutation survives — dropping the non-empty
device-id guard — because no fixture case makes it load-bearing in any
language; that gap is documented at the guard and is fixed upstream in
the fixture, not here, so all four runners gain the case together.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): review pass over the canonical API adoption

Six defects found reviewing the canonical settings adoption, five of which
lose or misreport a user's setting.

A transiently-failed flusher op was re-queued even after a newer value for
the same key was drained and sent in the same flush. `retryable` was
add-only, so a later drain pass that landed a newer op left the older
failed entry behind, and the post-loop `composite !in pending` guard could
not compensate — the pass that sent the newer op had already cleared
`pending`. `scheduleRetry` then replayed the superseded value with its
original mutation id, which the server's first-use-id path does not dedupe,
overwriting the edit the user had just made. Reachable from every
`flushNow()` caller (activity onStop, logout, the device-setting resets),
where a concurrent enqueue is not cancelled. Dropping the composite from
`retryable` on success keeps only the latest failed state per key.

The phone playback starter still read `user_profiles.subtitle_language`.
The settings screens write these preferences at `scope=profile` now, and
nothing on the server mirrors a canonical write back into that column, so
the phone auto-selected subtitles from the pre-edit value while Android TV
— which reads WatchDetail's server-resolved `effective_*` fields — played
the new one. Same intent, same server, different playback per platform.
The phone starter now prefers `effective_*` the way the TV starter does,
and passes the mode and forced-subtitle flag it previously dropped.

The TV detail page's "Auto" subtitle preview had the same stale source:
it advertised the pre-edit preference while starting playback from that
same row used the canonical one. It resolves through
ProfileSettingsController now, translating the snapshot's "" (no
preference) into the preview's null so an unset language does not read as
"no subtitles".

A 404 on the capabilities probe was read as "server too old". That route
sits behind the viewer-access middleware, which answers a JSON
`{"error":"not_found"}` when the X-Profile-Id we send names a profile the
household deleted elsewhere — so a current server told users to go ask
their admin for an upgrade when the fix was re-selecting a profile. A
genuinely old server has no `/settings/contract` routes and gets chi's
plain-text 404, which parses to an empty error code, so gating on that
separates the two.

The TV legacy-prefs import wrote only the resolution axis, leaving a
(resolution, no bitrate) pair no picker preset covers: the row read
"720p" but the picker showed nothing selected with the cursor on Auto, and
the sentinel is marked on the same pass so it could never be re-migrated.
It now writes both axes at the bitrates the server's own migration assigns
the same legacy values.

The only test for the subtitle-appearance projection passed with the whole
feature reverted — it asserted a negative that any no-op satisfies. It now
writes a granular slot through the legacy-import path (the genuinely
unguarded one) and asserts the flush carries it, with a second test for the
read overlay and the redundant-write guard kept separately. Verified by
mutation: deleting either half of the projection now fails.

Every fix is pinned by a test that fails without it, checked by reverting
each change in turn. Full suites green: 2996 tests across shared,
android-shared, androidApp and androidTvApp.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): address PR #119 review findings

Eight findings from the Codex and CodeRabbit passes over the canonical
settings adoption, six of which lose or misreport a user's setting.

The settings cutover renamed two keys (subtitle_appearance ->
playback.subtitle_appearance, player.next_up_prompt_seconds ->
playback.next_up_prompt_seconds). That is a contract question for the
server, but on disk it orphans values an installed build already wrote.
Both keys read local-first — subtitle appearance drives downloaded
playback with no server in the loop, next-up prompt falls back to its 30s
default — so an upgrade silently reverted both. PlaybackSettingsKeys
carries the rename table now and the store copies each slot forward once,
under its own sentinel: the existing one is already marked on every device
that has run a scoped build, so a pass gated on it would never run for the
installs actually holding the orphans. A value already under the new name
always wins.

A queued flusher op outlived a server switch. The flusher is
application-scoped and SettingsApi requests are relative, so a retained
retry addressed whichever server was active when it was finally sent —
and a restored or cloned server recognizing the same profile id would
accept it. Ops carry the server they were authored against and are
dropped, not deferred, once that origin is no longer active.

The bandwidth half of the quality choice never reached playback. The
server applies the cap only from the request's bandwidth_cap_kbps and
nothing on the playback path reads the stored setting, so "1080p Low"
streamed at whatever bitrate the ladder picked. Both starters send it now
and the attempt carries it, so replans re-send it rather than silently
lifting the limit mid-session.

A successful PUT stores the authored value; it does not make it effective.
Policy can narrow a setting and a profile_device row outranks the profile
row these setters write, so both screens could show a preference playback
was not using. ProfileSettingsController re-resolves after each successful
write and returns what the server actually holds; a failed re-resolve
keeps the optimistic value rather than rolling back a change that landed.

The TV legacy import guarded only the resolution axis while setQuality
writes both, so a device with a server-side bitrate cap and no resolution
override had that cap overwritten by the legacy preset's bitrate — or by
JSON null for a legacy Auto. Both axes are queried and guarded.

Blank effective_* strings reached subtitle auto-selection as a real
preference. A canonical row holding JSON null unmarshals to "" server-side
and arrives present-but-empty, which both auto-selectors read as an
explicit "subtitles off" — turning subtitles off for users who never chose
a language. Normalized on every rung, matching the audio path.

Metadata language rendered its unset value as "Off" on both platforms,
though it means "inherit the library's language" rather than disabling
anything.

Verification: :shared, :android-shared, :androidApp and :androidTvApp unit
tests plus both app compiles, --rerun-tasks to defeat stale caches —
3173 tests, 0 failures.

Not reproduced: CodeRabbit flagged AndroidPlayerSettingsStoreTest:535-543
as a critical compile failure on a nullable smart cast. kotlin.test
.assertTrue declares a returns()-implies contract, so the cast holds; the
file compiles clean under --rerun-tasks.

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

---------

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c1db41a58c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +25 to +29
const { data } = useEffectiveSettings({ keys: [SETTING_KEYS.PLAYBACK_PREFERRED_QUALITY] });
const resolved = data?.[SETTING_KEYS.PLAYBACK_PREFERRED_QUALITY]?.value;

if (typeof resolved !== "string") return fallback ?? null;
if (resolved === "original") return "auto";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve both axes of the canonical quality choice

When a profile selects a bitrate-specific preset such as 1080p at 6000 kbps or 720p at 2000 kbps, this hook fetches only playback.preferred_quality and discards playback.max_bitrate_kbps. useTranscodeQuality then chooses the first option matching that resolution—1080p-high or 720p-high—so playback sends 10000 or 4000 kbps and silently ignores the stored bandwidth cap; mapping original to auto also makes transcoded sources choose a lower tier instead of uncapped source quality. Carry both canonical axes through WatchPage and preserve the original sentinel rather than collapsing the choice to the legacy string.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +262 to +265
for (const mutation of buildLibraryPlaybackMutations(nextState)) {
if (mutation.value === undefined) {
try {
await clearValue.mutateAsync({ key: mutation.key, identity: scope });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Roll back partially applied library resets

When “Reset all” clears a library and an early DELETE succeeds but a later one fails, this loop has already permanently removed some of the four rows; the catch only restores React state, so the server is left half-reset and the next refetch changes the controls again. The previous composite-row DELETE applied the reset atomically, so either make this reset atomic or compensate the successful mutations from rollbackState before reporting failure.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +187 to +190
for (const request of requests) {
void playerFetch(config, request.path, {
method: "PUT",
body: JSON.stringify(request.body),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Serialize each subtitle choice as one coherent write

When the viewer changes subtitle tracks twice before these requests settle, each choice launches separate language, mode, and legacy-row PUTs that can interleave. The legacy /subtitle-prefs handler now also dual-writes language and mode canonically, so a late language PUT from the first choice can overwrite the second choice after its atomic legacy write, leaving canonical language from one selection with mode and track signature from the other; future item resolution reads those stores separately. Send one atomic request per choice or serialize and coalesce the whole operation per series.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Quick104 added a commit to Silo-Server/silo-android that referenced this pull request Jul 30, 2026
* fix(settings): send language tags, not display names

playback.audio_language and the profile's subtitle_language are BCP 47
language tags in the server's settings contract. The phone put the display
label on the wire verbatim — "English", not "en" — and the TV did the same
for audio while doing it correctly for subtitles.

That was already broken before the server started enforcing it: the same
string is handed to ExoPlayer as preferredAudioLanguage, and
setPreferredAudioLanguage("English") never matches a track tagged eng, so
choosing an audio language on Android has silently been a no-op. It also
meant Android and Apple wrote different vocabularies to the same key —
Apple has always sent codes, so a language picked on an iPhone read as
"Default" on the phone and vice versa.

Now that the server validates the tag, the flusher's PUT 400s and only
logs, so the setting would stop persisting entirely after a server upgrade.

Replaces the four drifted option lists with one table in shared, so a
language cannot be added to one surface and missed on the others, and
translates values already on devices on read rather than re-sending a
label the server will reject.

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

* feat(settings): adopt the generated contract bindings

SettingKeys.kt is generated from the server's manifest by cmd/settingsgen,
so this client cannot drift from the contract by editing a constant.

The two hand-maintained tables in AndroidPlayerSettingsStore now delegate to
it. BOOLEAN_KEYS/INT_KEYS/DOUBLE_KEYS was a second table that had to agree
with PlaybackSettingsKeys.DeviceSettings by discipline alone — a key added
to one and missed in the other flushes as the wrong type and is silently
dropped on read. Only the granular subtitle appearance fields stay local,
since the contract carries them as one composite object.

A new contract test caught two real drifts, both of which are the
disagreements the contract exists to end:

  subtitle_appearance -> playback.subtitle_appearance. Every other key
  carries a domain prefix; this one never did.

  player.next_up_prompt_seconds -> playback.next_up_prompt_seconds. Android
  shipped player.* while Apple and the server used playback.*, so the same
  preference was two settings and neither client could read the other's.

Both are wire-format changes with no dual-write, which is what the
coordinated cutover is for.

Part of the cross-platform settings contract (Silo-Server/silo-server#479).

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

* feat(settings): add the canonical settings API client

The clients adopted the generated contract bindings but still speak only
the legacy string-only settings registry; nothing calls the canonical
/settings/contract or /settings/values routes. This adds that surface to
SettingsApi, mirroring the server's settings_values.go shapes exactly:

- getContractCapabilities() probes /settings/contract/capabilities and
  returns a sealed SettingsCapabilitiesResult. A 404 means the server
  predates the canonical API entirely, so it is a typed
  ServerUpgradeRequired case the UI can present as "this server needs an
  upgrade" instead of an empty settings screen.
- getEffectiveValues(keys, libraryIds, seriesIds) hits the batched
  /settings/values/effective resolution: typed JSON values, the source
  scope of each answer, constraint reporting (value vs stored_value),
  and the contract revision the resolution was computed at.
- putValue/deleteValue address one scope explicitly via a validated
  SettingScopeIdentity: scope + library_id/series_id ride the query, the
  profile and device identity ride the session headers the auth
  interceptor already attaches (with a setDeviceSetting-style optional
  profileId override), matching how the server derives the identity so
  one profile cannot write another's settings by naming it.
- Writes carry X-Silo-Mutation-Id from newSettingMutationId(): one UUID
  per logical write, held across retries, so the flusher's retries
  replay the recorded receipt instead of re-applying, and a reused id
  with different content surfaces as 409 mutation_id_conflict.

Wire models live in SettingValueModels.kt beside the legacy models;
response scope/source fields stay raw strings so a server that adds a
scope cannot break deserialization. Shared unit tests cover the
serialization round-trips, the query/header/body encoding, and the
upgrade-required mapping for both routeless (plain-text) and JSON 404s.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): flush and refresh device settings through the canonical API

ServerSettingsFlusher now writes to PUT/DELETE /api/v1/settings/values/{key}
at scope=profile_device with values encoded as the contract's JSON types
(classified by the generated SettingKeys.BOOLEAN_KEYS/INT_KEYS/DOUBLE_KEYS
sets; subtitle appearance goes up as its JSON object, and an empty language
tag as JSON null because the server's language_tag validator rejects "").
The 750ms debounce semantics are unchanged.

The old failure handling was a named defect: a failed PUT logged at Log.w
and dropped the write, so any server hiccup silently turned settings
non-persistent. Now a transient failure (network, 5xx, 408/429/401) keeps
the op queued and retries it with the SAME mutation id — minted once per
logical write via newSettingMutationId() — so the retry is an idempotent
replay the server can dedupe, first on a capped backoff and after that on
the next enqueue/flushNow trigger. Only a response that proves retrying is
pointless (contract rejection, mutation-id conflict) drops the op, and
every failure is logged at warning level with the key and status through
SiloLog. A delete answered 404 not_found is treated as already done.
Non-contract keys (the granular subtitle.* fields Android flattens out of
the composite appearance object) never reach the server, where they would
404 as unknown_setting.

AndroidPlayerSettingsStore.refreshFromServer() now hydrates from the
batched GET /settings/values/effective: typed JSON parsed per the generated
type sets, and a key nothing is stored for arrives as the contract default
with source "default" — so defaults come from the contract, never from a
hardcoded fallback, and a value reset from another device snaps back on
refresh. The subtitle device-override flag now derives from the resolved
scope (profile_device) instead of the legacy has_device_override field. A
key absent from the response means the server's contract predates it, so
the local value is kept. resetAllDeviceSettings deletes only server-stored
keys.

Part of the canonical settings API adoption; the API surface itself landed
in the previous commit.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): write profile and quality preferences at canonical scopes

The subtitle triple (language, mode, forced) and the metadata language rode
named columns on PUT /profiles/{id}. The server still accepts them, but every
server-side reader resolves those preferences canonically from
user_setting_values, so the column write only takes effect via the mirror the
server keeps until cutover. Android now writes them itself, at scope=profile,
one key per edit — a failed write no longer reverts the other two, which is
what sending the whole triple every time did.

Reads come from the batched effective endpoint rather than the profile object,
so a value set on another device, or narrowed by policy, is what the screen
shows. Both apps go through one shared ProfileSettingsController: this repo's
history has the TV screen missing behaviors the phone has, and a behavior that
lives in one class cannot be present on one platform only.

Quality becomes the two axes the contract actually stores —
playback.preferred_quality (resolution) and playback.max_bitrate_kbps
(bandwidth, null = uncapped) — behind one preset picker whose table is a port
of the web client's qualityPresets.ts. Presets stay client-side on purpose:
retuning what "1080p High" means is a client release, not a contract break.
The compound legacy spellings ("1080p-high") are dead and never written; a
stored one is decomposed on read, dropping the bitrate it encoded rather than
inventing a cap the user never chose.

Subtitle appearance keeps its granular subtitle.* fields client-local (the
contract carries one composite object and would refuse them as unknown_setting)
but they are no longer stranded there: they project into
playback.subtitle_appearance on flush, so a per-field edit reaches the server,
and a resolved appearance flattens back into them so the overlay cannot
resurrect the value the server just replaced.

A server that predates the canonical settings API 404s the contract probe.
Both settings screens now say so instead of rendering rows whose edits
silently go nowhere; playback keeps working from the device-scoped defaults.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(settings): add the cross-platform conformance runner

The settings contract names four resolvers that must agree: Go in
internal/settingsresolve, TypeScript in web/src/lib, Swift in the Apple
clients, and Kotlin here. Three of them ran the shared conformance
fixture; Kotlin did not, so nothing caught this client resolving a
setting differently from the server until a user saw the wrong value.

Vendors contracts/settings/v1/conformance.json byte-identically, plus
the manifest it was authored against. The manifest is needed because the
generated SettingKeys bindings carry key names and a coarse type table
but not the facts resolution turns on — resolution_order, default_value,
enum member order with its `ordered` flag, and constrained_by. Copying
those into Kotlin by hand would recreate exactly the drift the contract
exists to remove, so the runner parses the manifest and is driven by it.
No generator change is required.

The resolver lives in test sources on purpose. Android does not resolve
settings in production: it writes through /settings/values and reads
effective values back, leaving the server the single authority. This
exists so the fixture has a fourth independent implementation to
disagree with, which is what makes it a drift gate rather than a
tautology.

Four things fail the suite, each of them drift: a resolution
disagreement, a revision mismatch across the fixture / vendored manifest
/ generated bindings, a key those two JSON files disagree about (which
catches them being vendored from different server commits — skew the
revision check cannot see), and any fixture field the runner does not
recognize. The last one is why decoding is strict: a field one platform
reads and another silently skips means the platforms have stopped
running the same cases, and a silent skip is indistinguishable from a
pass.

Verified by mutating the resolver and confirming the suite fails:
reversed resolution order, a null bitrate slipping past a ceiling, a
floor capping an unbounded value, allowlist falling back to the
definition default, locked narrowing an already-equal value, ordered
enum ranking disabled, and foreign-profile rows resolving. Each gate was
mutation-tested too. One mutation survives — dropping the non-empty
device-id guard — because no fixture case makes it load-bearing in any
language; that gap is documented at the guard and is fixed upstream in
the fixture, not here, so all four runners gain the case together.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): review pass over the canonical API adoption

Six defects found reviewing the canonical settings adoption, five of which
lose or misreport a user's setting.

A transiently-failed flusher op was re-queued even after a newer value for
the same key was drained and sent in the same flush. `retryable` was
add-only, so a later drain pass that landed a newer op left the older
failed entry behind, and the post-loop `composite !in pending` guard could
not compensate — the pass that sent the newer op had already cleared
`pending`. `scheduleRetry` then replayed the superseded value with its
original mutation id, which the server's first-use-id path does not dedupe,
overwriting the edit the user had just made. Reachable from every
`flushNow()` caller (activity onStop, logout, the device-setting resets),
where a concurrent enqueue is not cancelled. Dropping the composite from
`retryable` on success keeps only the latest failed state per key.

The phone playback starter still read `user_profiles.subtitle_language`.
The settings screens write these preferences at `scope=profile` now, and
nothing on the server mirrors a canonical write back into that column, so
the phone auto-selected subtitles from the pre-edit value while Android TV
— which reads WatchDetail's server-resolved `effective_*` fields — played
the new one. Same intent, same server, different playback per platform.
The phone starter now prefers `effective_*` the way the TV starter does,
and passes the mode and forced-subtitle flag it previously dropped.

The TV detail page's "Auto" subtitle preview had the same stale source:
it advertised the pre-edit preference while starting playback from that
same row used the canonical one. It resolves through
ProfileSettingsController now, translating the snapshot's "" (no
preference) into the preview's null so an unset language does not read as
"no subtitles".

A 404 on the capabilities probe was read as "server too old". That route
sits behind the viewer-access middleware, which answers a JSON
`{"error":"not_found"}` when the X-Profile-Id we send names a profile the
household deleted elsewhere — so a current server told users to go ask
their admin for an upgrade when the fix was re-selecting a profile. A
genuinely old server has no `/settings/contract` routes and gets chi's
plain-text 404, which parses to an empty error code, so gating on that
separates the two.

The TV legacy-prefs import wrote only the resolution axis, leaving a
(resolution, no bitrate) pair no picker preset covers: the row read
"720p" but the picker showed nothing selected with the cursor on Auto, and
the sentinel is marked on the same pass so it could never be re-migrated.
It now writes both axes at the bitrates the server's own migration assigns
the same legacy values.

The only test for the subtitle-appearance projection passed with the whole
feature reverted — it asserted a negative that any no-op satisfies. It now
writes a granular slot through the legacy-import path (the genuinely
unguarded one) and asserts the flush carries it, with a second test for the
read overlay and the redundant-write guard kept separately. Verified by
mutation: deleting either half of the projection now fails.

Every fix is pinned by a test that fails without it, checked by reverting
each change in turn. Full suites green: 2996 tests across shared,
android-shared, androidApp and androidTvApp.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): address PR #119 review findings

Eight findings from the Codex and CodeRabbit passes over the canonical
settings adoption, six of which lose or misreport a user's setting.

The settings cutover renamed two keys (subtitle_appearance ->
playback.subtitle_appearance, player.next_up_prompt_seconds ->
playback.next_up_prompt_seconds). That is a contract question for the
server, but on disk it orphans values an installed build already wrote.
Both keys read local-first — subtitle appearance drives downloaded
playback with no server in the loop, next-up prompt falls back to its 30s
default — so an upgrade silently reverted both. PlaybackSettingsKeys
carries the rename table now and the store copies each slot forward once,
under its own sentinel: the existing one is already marked on every device
that has run a scoped build, so a pass gated on it would never run for the
installs actually holding the orphans. A value already under the new name
always wins.

A queued flusher op outlived a server switch. The flusher is
application-scoped and SettingsApi requests are relative, so a retained
retry addressed whichever server was active when it was finally sent —
and a restored or cloned server recognizing the same profile id would
accept it. Ops carry the server they were authored against and are
dropped, not deferred, once that origin is no longer active.

The bandwidth half of the quality choice never reached playback. The
server applies the cap only from the request's bandwidth_cap_kbps and
nothing on the playback path reads the stored setting, so "1080p Low"
streamed at whatever bitrate the ladder picked. Both starters send it now
and the attempt carries it, so replans re-send it rather than silently
lifting the limit mid-session.

A successful PUT stores the authored value; it does not make it effective.
Policy can narrow a setting and a profile_device row outranks the profile
row these setters write, so both screens could show a preference playback
was not using. ProfileSettingsController re-resolves after each successful
write and returns what the server actually holds; a failed re-resolve
keeps the optimistic value rather than rolling back a change that landed.

The TV legacy import guarded only the resolution axis while setQuality
writes both, so a device with a server-side bitrate cap and no resolution
override had that cap overwritten by the legacy preset's bitrate — or by
JSON null for a legacy Auto. Both axes are queried and guarded.

Blank effective_* strings reached subtitle auto-selection as a real
preference. A canonical row holding JSON null unmarshals to "" server-side
and arrives present-but-empty, which both auto-selectors read as an
explicit "subtitles off" — turning subtitles off for users who never chose
a language. Normalized on every rung, matching the audio path.

Metadata language rendered its unset value as "Off" on both platforms,
though it means "inherit the library's language" rather than disabling
anything.

Verification: :shared, :android-shared, :androidApp and :androidTvApp unit
tests plus both app compiles, --rerun-tasks to defeat stale caches —
3173 tests, 0 failures.

Not reproduced: CodeRabbit flagged AndroidPlayerSettingsStoreTest:535-543
as a critical compile failure on a nullable smart cast. kotlin.test
.assertTrue declares a returns()-implies contract, so the cast holds; the
file compiles clean under --rerun-tasks.

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

* fix(android): resolve settings end-to-end defects

* fix(android): address review feedback

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Quick104 added a commit to Silo-Server/silo-apple that referenced this pull request Jul 30, 2026
* feat(settings): adopt the generated contract bindings

SettingKeys.generated.swift comes from the server's manifest via
cmd/settingsgen, replacing the private enum inside PlayerSettings that held
the wire keys as raw strings.

That enum is how two drifts survived: subtitle_appearance kept an unprefixed
name every other key had, and next_up_prompt_seconds disagreed with
Android's spelling, so the same preference was two settings and neither
client could read the other's. Both are settled in the contract now, and a
key this client sends is one the manifest declares by construction rather
than by review.

The short case names the file uses throughout are kept as aliases onto the
generated cases, so the call sites stay readable without reintroducing a
second list of strings — a key removed from the contract now fails to
compile here instead of failing at runtime against a server that no longer
accepts it.

playback.max_bitrate_kbps joins the synced set: quality is two axes now, and
without it the resolution would sync while the bandwidth cap silently did
not.

Verified on mac-builder: xcodegen picks the generated file up from the
existing source glob, and both the iOS and tvOS targets build.

Part of the cross-platform settings contract (Silo-Server/silo-server#479).

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

* feat(settings): add the canonical settings API client

The generated contract bindings landed last commit, but nothing could talk
to the endpoints they describe. This adds that client: contract capabilities,
batched effective resolution, and idempotent per-scope writes and clears,
mirroring internal/api/handlers/settings_values.go.

Setting values are heterogeneous JSON (bool/int/double/string/array/object/
null), so SettingJSONValue holds the shape rather than flattening everything
to a string the way the legacy /settings/{key} registry does. Values must
round-trip byte-for-byte: an object-valued setting whose keys get rewritten is
corrupted permanently in the user's stored settings. These models therefore
code through SettingsWireCoding — no key strategy — and spell their snake_case
field names out in CodingKeys.

That inverts HTTPClient's convention, and the two do not mix: the app's
.convertFromSnakeCase decoder camel-cases an incoming key before matching it,
so "profile_id" looks for a CodingKey named "profileId", misses the
"profile_id" one, and decodes as nil without throwing. A test pins that
failure so a future caller who reaches for http.get finds out at CI rather
than by shipping a value whose scope identity has silently evaporated.

Two things the server requires that the client did not previously send:
X-Profile-Id (every /settings/values route is profile-gated, and
scope=profile_device takes its profile half from that header), resolved up
front so a call before profile selection fails locally as .profileRequired
instead of an opaque 400; and X-Silo-Mutation-Id, so a retried write replays
the recorded receipt — surfaced as isIdempotentReplay — rather than
double-applying, with a reused id carrying different content mapping to a
named .mutationIdConflict. HTTPClient grows requestData for this: per-request
headers out, status and response headers back, no JSON coding, sharing the
existing auth and 401-refresh path.

"Server too old" is a typed result, not an error. The distinction is the
envelope rather than the status: a 404 carrying Silo's {"error","message"}
came from a route that exists (unknown key, nothing stored there), while a
bare 404 is the router saying these routes are not mounted at all. Mapping
every 404 to serverUpgradeRequired would tell a user to upgrade because they
asked for a key that does not exist.

Verified on mac-builder: iOS scheme builds; SiloTests 804 tests, 0 failures.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): flush and refresh player settings through the canonical API

PlayerSettings still spoke the legacy string-only registry: every value went
out as a string, the scope was implied by which endpoint you called, and an
unknown key was accepted silently. It now writes typed JSON to
PUT/DELETE /api/v1/settings/values/{key} at scope profile_device and reads one
batched /settings/values/effective, so the same preferences resolve here the way
they do on web and Android.

The write path moves into PlayerSettingsFlusher, because the old inline flusher
retried nothing. A write that failed mid-drain sat in the queue until the next
user edit happened to trigger another flush, so one server hiccup made a setting
look non-persistent until the user toggled something unrelated. A transient
failure is now retried on a capped backoff carrying the SAME mutation id — the
server replays its recorded receipt, so a retry after a dropped response cannot
double-apply — while a response that proves retrying is pointless (invalid
value, unknown key, scope not allowed, id reused for different content) drops
the op loudly. Semantics match Android's ServerSettingsFlusher so a user with
both clients sees a setting land the same way on each.

The 750ms debounce is parity with Android, and it opens a hole the old code did
not have: a toggle flipped and the app immediately backgrounded would leave the
write in a timer that never fires. The flusher therefore flushes on
didEnterBackground. Its queue is lock-guarded rather than actor-isolated so a
setter never hops actors to enqueue — two rapid edits hopping could be delivered
out of order, which for a slider means the server keeps a value the user dragged
through rather than the one they stopped on.

Two encodings the contract forces, neither of which the old registry validated:

playback.preferred_quality is an enum of bare resolutions, so Apple's compound
ladder ids ("1080p-high") are a permanent invalid_value. AppleQualityAxes splits
a tier into that enum plus playback.max_bitrate_kbps and rejoins the pair on the
way back, honouring both caps — a web-authored 1080p/6Mbps becomes 720p High at
4Mbps rather than Apple's 1080p at 8Mbps, since exceeding a bandwidth cap the
user set is the harmful direction. The Apple bitrate rungs deliberately stay put
rather than being retuned to the web's: the two clients agree on the axes, and
what "1080p High" means to a user is a client-side table on each. Uncapped is
JSON null and not an omitted write, or the old cap would keep throttling a tier
the user just widened. playback.audio_language is likewise null, not "", which
its language_tag validator rejects.

The effectiveBool empty-string guard is deleted, as planned. It existed because
the legacy endpoint had no way to say "unset" — it answered "" for both unset
and false — so anything unparseable had to be read as absent. The canonical
endpoint types the value and reports source:"default", making the two distinct;
keeping the guard would now swallow a genuine stored false. Absent keys fall
back to the generated contract's typed defaults instead.

player.playback_speed gains step alignment. The contract declares step 0.05 and
the server rejects anything off that grid, so a value that arrived at
1.7500000000000002 through ordinary double arithmetic would queue a write that
could never succeed.

The singleton's public API is unchanged; its ~50 call sites need no edits.

Verified on mac-builder: iOS and tvOS schemes build; SiloTests 840 tests, 0
failures, including 36 new ones covering the debounce, retry-with-the-same-id,
the typed-default fallback and the quality-axis round trip, all against a fake
transport with no network.

Part of the cross-platform settings contract (Silo-Server/silo-server#479).

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(settings): write profile and quality preferences at canonical scopes

Two preferences on the settings screens were still on pre-contract paths. The
subtitle trio and the metadata language travelled as fields on
PUT /profiles/{id}, and quality was stored as a compound tier id. Both now go
through the canonical settings API at the scope the contract defines.

Profile preferences write at scope=profile. The legacy endpoint still works —
the server mirrors those fields into the canonical rows
(internal/api/handlers/profiles_settings_sync.go) — but it is a narrower pipe:
it can only address the profile's own scope, spells "no preference" as the empty
string where the contract spells it null, and validates nothing until the mirror
runs. Reads move to the batched effective endpoint, which is the only source
that accounts for a library, series or device override winning over the profile
row; the profile snapshot now only seeds first paint so the screen does not open
on contract defaults that visibly correct themselves.

playback.audio_language deliberately does NOT move. It is written at
profile_device, and the contract resolves profile_device above profile, so a
profile-scope write would be shadowed by this device's own row and look like it
never saved. Old Apple builds already wrote those rows, so the shadowing is real
on existing installs rather than hypothetical; a test pins the exclusion.

Quality adopts the cross-client preset table — a field-for-field port of
web/src/lib/qualityPresets.ts and Android's QualityPresets.kt, so "1080p High"
means the same thing on every client. That forced the local representation to
change: what is stored is now the (resolution, bitrate) PAIR, not a tier id.
Both tables spell a rung `1080p-high` and mean different bitrates by it — 10
Mbps in the shared presets, 20 Mbps in this client's in-player ladder — so a
stored id would silently change meaning depending on which table read it back.
A pair says what it means and each table interprets it. PlayerSettings.
preferredQuality survives as a derived in-player ladder id, so playback's dozen
call sites are untouched.

The effective read adopts the pair verbatim rather than quantizing it onto this
client's ladder. Quantizing would rewrite the profile's stored choice on the
next edit made from this device, so a 1080p/6 Mbps preference set on the web
would decay into Apple's 720p High the first time someone opened Settings on
their phone. A pair no preset covers keeps its own description in the picker
instead of snapping to a nearby preset that would misreport the stored cap.

Server-upgrade-required is surfaced rather than swallowed. A server with no
canonical settings routes now renders an explanation on both subtitle screens
saying playback still works from local defaults, instead of leaving controls
that silently fail. A transient read failure deliberately does not blank the
editor: snapping every control to a contract default looks exactly like the
server having wiped the user's settings.

The editor and its save behaviour are now one type shared by both platforms.
The two screens each had a verbatim copy, which is how they drifted apart
before; with contract-validated values a spelling only one screen got right
would be a permanent invalid_value on the other. tvOS gets the preset picker in
the same commit as iOS for the same reason.

Writing the tests found a real bug: saving the subtitle trio stopped at the
first failed write, so one hiccup on the language key meant the mode and
forced-subtitle choices were never sent — the user changed one control and
silently lost two others. All three are attempted now, with the first failure
reported.

Verified on mac-builder: iOS and tvOS schemes build; SiloTests 865 tests, 0
failures, including 25 new ones covering the preset table against the contract's
own enum and bounds, the two-axis round trip for every preset, profile-scope
writes, the null-not-empty-string language spelling, upgrade-required, and
mutation-id reuse across retries.

Follow-up: ContinuumAPI.updateProfile and UpdateProfileBody now have no callers.
Removing them is a separate change.

Part of the cross-platform settings contract (Silo-Server/silo-server#479).

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(settings): add the cross-platform conformance runner

The settings contract names a Swift resolver as one of four that must agree
on contracts/settings/v1/conformance.json. Go, TypeScript, and Kotlin runners
already exist; without this one Apple could silently resolve a setting
differently from the server and nothing would catch it.

The fixture and the manifest it was authored against are vendored
byte-identically from the server repo, with provenance and re-vendor
instructions in a SOURCE note beside them. The manifest is carried alongside
the fixture rather than the fixture alone because the expectations are only
valid at one revision: the runner fails when the fixture's manifest_revision,
the vendored manifest's revision, and the generated SettingKey.revision stop
agreeing, and separately when the two JSON files were vendored from different
server commits — skew the revision check cannot see, since a revision only
moves on a manifest PR.

The resolver reads resolution order, defaults, enum member order, and
constraint bindings out of the vendored manifest rather than a hand-copied
table, so it cannot pass the fixture while having drifted from the contract.
It lives in the test target: the Apple clients do not resolve settings in
production, they write through /settings/values and read effective values
back, and the server stays the single authority.

Swift has no DisallowUnknownFields, so strictness is two passes over the same
bytes — a typed decode for the values, and a walk of the raw tree that rejects
an unknown field at every level. The walk also answers what typed decoding
cannot: whether stored_value was absent or authored as JSON null, which three
fixture cases depend on. testAnUnknownFixtureFieldFails injects a field at
each level so the gate's own regression cannot go unnoticed.

Both JSON files are declared as SiloTests resources in project.yml by hand
rather than left to XcodeGen's inference, and the runner fails hard rather
than skipping when either is missing from the bundle: a drift gate that
quietly stopped running is worse than no gate.

Verified on mac-builder: all six tests pass and the result bundle names all
24 fixture cases as executed activities.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): review pass over the canonical API adoption

Five defects found reviewing the settings-contract adoption, all in code this
branch introduced.

**A shared 1080p preset resolved to 720p on Apple only.**
`AppleQualityAxes.join` picked the highest tier within the stored bandwidth
cap, regardless of resolution. Apple's ladder has no 1080p rung below 8 Mbps,
so the shared "1080p" preset (1080p, 6000) joined to `720p-high` and the V3
start request carried `quality_preference="720p"` — while the web and Android
clients sent `1080p` from the identical stored pair. The rationale for trading
the tier away was to honour the cap, but the cap is not a field on the V3
request (`bandwidthCapKbps` is nil on both the start and the replan), so the
trade bought nothing and cost a resolution tier plus, via `resolutionRank`, a
preference for the 720p source edition.

The resolution axis is now authoritative: the joined tier always names the
stored resolution, and the bitrate axis chooses which rung of it. The cap is
applied where it *is* expressible — `targetBitrateKbps` and
`shouldForceTranscode` now take it and clamp the legacy `/transcode/start`
encode target, so a 1080p/6 Mbps preset encodes at 6 rather than at the rung's
8. Every existing tier still round-trips split→join unchanged.

**Every debounced write failed its first attempt.**
The debounce timer called `flushNow()`, which opens by cancelling
`debounceTask` — on that path the task executing the call. The drain, the send
and the URLSession round trip then ran with `Task.isCancelled == true`, and
URLSession reports its enclosing task's cancellation as NSURLErrorCancelled.
The write was classified as a transport failure and only landed ~1 s later on
the first backoff retry. The timer now retires its own registration before
flushing, so the cancel is a no-op. `FakeSettingsTransport` fails a cancelled
send the way the network does — without that it was more forgiving than
URLSession, which is why the suite could not see this.

**Two mutation-id tests reported a real regression as a skip.**
`XCTSkipUnless(modeWrites.count == 2)` guarded the assertion that catches
`saveSubtitlePrefs` aborting its batch on the first error — the exact
regression the comment above it names. XCTSkip is recorded as a skip, which CI
counts as a pass. Both are `XCTAssertEqual` now, with index-free unwraps.

**Opening Settings promoted a device override into the profile row.**
`load()` reads through the effective endpoint, which resolves `profile_device`
above `profile`, and paints the result into the same fields the screens watch
with `.onChange { saveProfilePrefs() }` — while every write here goes to
`profile`. A `profile_device` subtitle row (creatable today through the web
admin's per-device settings pane) was therefore read in and written back one
scope up on screen open, with no user interaction, destroying the profile's
own value household-wide. Saves now diff against a baseline captured on every
repaint, per key, so only a control the user actually moved is written. A
failed write does not advance its baseline, so it is still retried.

**The 750 ms debounce window was a data-loss hole.**
The window is new on this branch — the previous flusher sent on every edit —
and the queue lived only in memory. `willResignActive` on macOS does not wait
for the flush it starts before Cmd-Q terminates the process, and a suspended
iOS app killed from the switcher gets no notification at all; the edit was
then lost on both sides, because the next `refreshFromServer` overwrote the
local value with the stale server one. The queue is now journalled to
UserDefaults as it is enqueued, partitioned by (server, profile, device) so a
queue cannot replay onto another profile, and carrying its mutation ids so a
replay cannot double-apply. In-flight ops stay journalled until acknowledged.
`refreshFromServer` restores before it reads, since the app-wide flusher is
built long before the scope is known. `willTerminate` is now observed on both
platforms, and the iOS flush holds a background-task assertion.

Verified on mac-builder: iOS, tvOS and macOS all build; 75 tests pass. Each
fix is pinned — reverting all five and rerunning leaves 27 failures across 12
tests, and reverting none leaves 0.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): address PR review findings

* fix(player): preserve quality intent across recovery

* fix(settings): preserve writes across async races

* fix: address settings contract review feedback

* fix: settle stale metadata save state

* fix: resolve settings review edge cases

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@Quick104
Quick104 merged commit dc4b9a0 into main Jul 30, 2026
8 checks passed
@Quick104
Quick104 deleted the feat/settings-contract branch July 30, 2026 14:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant