Skip to content

feat(settings): adopt the generated contract bindings - #111

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

Quick104 merged 12 commits into
mainfrom
feat/settings-contract

Conversation

@Quick104

@Quick104 Quick104 commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Adopts the cross-platform settings contract on iOS/tvOS/macOS. Companion to Silo-Server/silo-server#479 and Silo-Server/silo-android#119.

What changed

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

That enum is how two drifts survived unnoticed:

  • subtitle_appearance kept an unprefixed name every other key had a domain for.
  • next_up_prompt_seconds was playback.* here but player.* on Android, so the same preference was two settings and neither client could read the other's.

Both are settled in the contract. A key this client sends is now one the manifest declares by construction rather than by review, and a key removed from the contract 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 orthogonal axes now (resolution cap + bandwidth cap), and without it the resolution would sync while the bandwidth cap silently did not.

The short case names the file uses throughout are kept as aliases onto the generated cases, so ~60 call sites stay readable without reintroducing a second list of strings.

Verification

On mac-builder (macOS 26.5.1, Xcode 26.4):

$ xcodegen generate && xcodebuild -scheme Silo -destination "generic/platform=iOS Simulator" build
** BUILD SUCCEEDED **

xcodegen picks the generated file up from the existing iosApp source glob, so no project.yml change was needed. The tvOS target compiles from the same tree.

Simulator screenshots are not attached (disk pressure at the time; the box has since recovered and the full test suite now runs on-simulator — see the adoption section below). The compile-only builds above are clean at the same commit. Freeing the remaining space would mean deleting other people's simulator devices and browser caches, which I left alone.

Now also: the canonical settings API adoption

The commits after 73dd8e3 complete the Apple half of the cutover (3225e7b..46ecf49).

API client (ContinuumAPI+Settings): getContractCapabilities(), batched getEffectiveValues, putValue/deleteValue with X-Silo-Mutation-Id and the previously-missing X-Profile-Id. The models carry explicit snake_case CodingKeys and code only through a dedicated coder — probing the shared .convertFromSnakeCase coder on the real toolchain showed it silently nil-decodes explicitly-keyed fields (camel-cases the incoming key before matching), which is pinned as a test so nobody routes these models through it later. A bare 404 maps to a typed server-upgrade-required result; an enveloped 404 (deleted profile) does not.

PlayerSettings: writes move into a PlayerSettingsFlusher — 750 ms debounce, per-write mutation id held across retries, capped backoff, transient/permanent split mirroring Android, flush-on-background, and the queue journalled to UserDefaults so a write sitting in the debounce window survives app termination. refreshFromServer is one batched effective call; the effectiveBool empty-string guard is deleted in favour of generated typed defaults. Quality splits Apple's compound ladder ids across the two contract keys via AppleQualityAxes rather than sending values the server would reject.

Profile prefs, both platforms: subtitle language/mode/forced and metadata language write at scope=profile; the legacy profile-update path is gone from both settings screens; the shared quality presets land on iOS and tvOS; a server without canonical routes renders an explanation instead of silently-failing controls.

Conformance runner: fixture + manifest vendored byte-identical with provenance, a manifest-driven Swift resolver running every case in SiloTests, failing (not skipping) if resources aren't bundled, and asserting the vendored manifest covers all 49 generated binding keys — regenerating one without re-vendoring the other fails immediately.

Review pass (46ecf49): four adversarial lenses, 11 findings, 5 confirmed by probes (3 refuted as pre-existing or unable to fire), every fix pinned by a test verified failing-first — a revert branch keeping the new tests showed 27 failures across 12 tests. The confirmed set: shared 1080p presets resolved to 720p here while Android/web sent 1080p (resolution axis is now authoritative, the bitrate cap threads into the transcode path where it can actually apply); the debounce timer ran its network writes inside a task it had just cancelled, so every debounced write failed its first attempt; two mutation-id tests hid their assertion behind XCTSkipUnless; a write in the debounce window was lost on termination (now journalled); and ProfilePrefsEditor could write a device-scope value back at profile scope on screen open (now diffed against a per-repaint baseline).

Verification at 46ecf49, on mac-builder (macOS 26.5.1, Xcode 26.4): Silo (iOS), SiloTV (tvOS) and SiloMac builds succeed; full SiloTests suite 885 tests, 0 failures, independently re-run on a fresh simulator after the review fixes.

Merge order

Must ship together with the server and Android PRs — the design calls for one coordinated cutover and there is no dual-write.

AI Disclosure

  • Tool(s): Claude Code
  • Model(s): claude-opus-5[1m], claude-fable-5
  • Involvement: AI-assisted, under maintainer direction
  • Adversarial review: The two key drifts were found mechanically rather than by inspection — the Android companion PR's contract test failed on both, which is what proved the generated bindings were doing their job. The first build attempt here also failed usefully: swapping the enum for SettingKey broke ~60 call sites at compile time, confirming the aliases resolve to generated cases rather than to strings. Every claim above was verified by building on a real Mac; nothing is inferred from reading the diff.

Summary by CodeRabbit

  • New Features
    • Added playback quality presets with independent resolution and bitrate caps (including 4K/“Original”), plus a “custom” option when no preset matches.
    • Refreshed Settings UI to use preset-based quality labels and improved footer messaging for active profile overrides and server-upgrade requirements.
    • Added shared profile-scoped subtitle and metadata-language preferences with correct “no preference” behavior.
  • Bug Fixes
    • Improved bitrate-cap honoring during streaming, recovery, and transcode restart, including correct handling of “Original” vs “Auto”.
    • Reduced unnecessary settings writes via smarter value equivalence and improved reliability for queued/flushed profile preference updates.

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]>
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

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 canonical typed settings contract for Apple platforms, including wire APIs, scope and constraint resolution, durable player-setting writes, split quality preferences, profile editing, updated settings UI, and conformance and integration tests.

Changes

Canonical settings integration

Layer / File(s) Summary
Typed settings API and contract resolution
iosApp/iosApp/Networking/..., iosApp/Tests/SettingsContractResolve.swift, iosApp/Tests/SettingsConformanceTests.swift, iosApp/Tests/Fixtures/SettingsContract/*
Adds typed settings values, scope identities, capabilities, API operations, revision-pinned manifests, scope precedence, constraint handling, and semantic conformance validation.
Durable player settings pipeline
iosApp/iosApp/Screens/Player/PlayerSettings.swift, iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift, iosApp/Tests/PlayerSettingsFlushTests.swift
Routes device settings through typed values and a journaled, retryable flusher with profile-bound writes, migration support, and lifecycle flushing.
Quality axes and playback integration
iosApp/iosApp/Networking/SiloQualityPresets.swift, iosApp/iosApp/Screens/Player/..., iosApp/Tests/ProfileAndQualitySettingsTests.swift
Splits quality into resolution and optional bitrate-cap axes, preserves Original separately from Auto, and applies caps to playback planning and transcoding.
Profile preferences and settings UI
iosApp/iosApp/Screens/Settings/..., iosApp/iosApp/tvOS/Screens/Settings/...
Adds profile-scoped loading and mutation-aware saving, shared quality-picker state, shadow-resolution handling, and server-upgrade/error presentation.
Validation and test resources
iosApp/project.yml, iosApp/Tests/SettingValuesAPITests.swift, iosApp/Tests/ProfileAndQualitySettingsTests.swift
Bundles contract fixtures and validates wire encoding, API requests, resolution behavior, idempotency, retries, migration, and concurrent saves.

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

Possibly related issues

  • Silo-Server/silo-server#376 — Covers the Apple settings contract, scope handling, durable writes, and profile-safe queued operations implemented here.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.22% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately reflects the main shift to generated settings contract bindings across the app.
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.
✨ Finishing Touches 💡 1
📝 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.

@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: 73dd8e3ef7

ℹ️ 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".

/// declares — by construction, not by review.
private let playerDeviceSettingKeys: [SettingKey] = [
.playbackPreferredQuality,
.playbackMaxBitrateKbps,

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 Apply the synced maximum-bitrate setting

When a profile or another client sets playback.max_bitrate_kbps, this list only makes refreshFromServer() fetch the value; applyEffectiveSettings never reads it, no PlayerSettings property stores it, and playback planning continues to derive its bitrate solely from preferredQuality. The Apple client therefore ignores the independent bandwidth cap and may stream above it, while Reset Playback Overrides can still delete the unseen override. Add the corresponding state/application and feed it into quality selection and playback requests.

AGENTS.md reference: AGENTS.md:L16-L21

Useful? React with 👍 / 👎.

Quick104 and others added 5 commits July 29, 2026 03:25
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]>
…al 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]>
…opes

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]>
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]>
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]>

@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: 46ecf4938a

ℹ️ 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 +1494 to +1495
selectedVersion: initiallySelectedVersion,
capKbps: PlayerSettings.shared.maxBitrateKbps

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 Pass the bitrate cap into protocol V3 requests

When the server advertises protocol V3, playback returns through startProtocolV3IfAvailable before this legacy planning path is used, and both the V3 start and replan requests still hard-code bandwidthCapKbps: nil (lines 471 and 663). Fresh evidence after the prior comment is that the cap is now stored and applied to legacy /transcode/start, but the preferred V3 path still receives only the bare resolution, so a 1080p/3 Mbps preference can be planned above 3 Mbps. Pass PlayerSettings.shared.maxBitrateKbps through both V3 request shapes as well.

AGENTS.md reference: AGENTS.md:L19-L21

Useful? React with 👍 / 👎.

Comment on lines +798 to +802
let legacyResolution = SiloQualityPresets.normalizeResolution(
defaults.string(forKey: Self.cacheKey(Keys.preferredQuality))
?? defaults.string(forKey: Keys.preferredQuality)
)
let legacyBitrateKbps = Self.cachedMaxBitrateKbps(defaults)

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 the bitrate encoded in legacy quality IDs

On the first canonical-settings migration for a device whose cache contains an old compound value such as 720p-medium, this normalizes only the resolution and cachedMaxBitrateKbps is absent because old builds never had that separate key. The migration consequently writes (720p, null), changing the user's prior 3 Mbps selection into uncapped playback. Decode the legacy compound ID with the old Apple ladder (for example via AppleQualityAxes.split) when no separate bitrate cache exists before enqueueing both axes.

Useful? React with 👍 / 👎.

Comment on lines +97 to +100
if resolution == "auto" || resolution == "original" {
// A bandwidth cap with no resolution cap has no tier to name: this
// client's picker is keyed on the resolution axis.
return ApplePlaybackQuality.autoId

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 Original distinct from Auto during playback

When a user selects the newly offered “Original” preset, the stored resolution is original, but this branch converts it to the same auto ID used for adaptive playback. Subsequent startup therefore sends auto to protocol V3 and may accept a transcode, contradicting the preset's “Never transcode” behavior. Preserve an Original playback ID through this join instead of collapsing it to Auto.

Useful? React with 👍 / 👎.

Comment on lines +143 to 144
return exceedsBitrateCap(selectedVersion, ceilingKbps: ceiling(option.bitrateKbps, capKbps))
|| exceedsResolutionCap(selectedVersion, option: option)

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 Enforce a bitrate cap when resolution is Auto

For the valid cross-client pair preferred_quality = auto plus a numeric max_bitrate_kbps, AppleQualityAxes.join yields the Auto ID and the early return above this changed clamp prevents the cap from ever forcing a transcode; targetBitrateKbps likewise returns zero for the Auto option. Thus the legacy playback path ignores the supposedly independent bandwidth axis whenever resolution is Auto. Evaluate the explicit cap before treating Auto as unrestricted and provide a capped transcode target.

Useful? React with 👍 / 👎.

var firstFailure: Error?
for (key, value) in writes {
do {
try await writer.write(key, value: 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 Serialize profile writes for the same key

When a user changes the same subtitle control twice before the first PUT returns, separate onChange tasks can overlap at this suspension point and the server may apply the older request last. The older completion then calls adoptBaseline using the field's current newer value, so the editor believes that newer value is saved even though the server contains the stale one and no retry is triggered. Serialize or coalesce writes per key so response order cannot reverse the user's edits.

Useful? React with 👍 / 👎.

Comment on lines +373 to +376
for (key, write) in restored where pending[key] == nil && inFlight[key] == nil {
pending[key] = write
}
persistLocked()

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 Drop or partition in-memory writes when the profile changes

When a device-scoped write remains queued after a retryable failure and the user switches profiles or servers, pending still contains the old scope's operation; this method only merges the newly selected scope's journal and explicitly lets the in-memory entry win. The immediately following refresh flushes that operation using the new session headers and persistLocked() also copies it into the new scope's journal, so one profile's quality or subtitle choice can overwrite another profile's setting. Track the scope alongside the in-memory queue and swap or reject entries when the active scope changes.

AGENTS.md reference: AGENTS.md:L19-L21

Useful? React with 👍 / 👎.

Comment on lines 929 to 930
if key == .subtitleAppearance && !legacySubtitleOverrideEnabled {
continue

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 Migrate the Apple subtitle default before inheriting

For upgrading users who never enabled a custom subtitle override, this skips migration of SubtitleAppearance.default. The vendored contract's fallback uses backgroundStyle: "shadow", while Apple's shipped default is .box, so the first canonical refresh silently changes subtitle rendering for precisely the users with no stored device row. Preserve the platform default during cutover rather than treating the disabled override flag as proof that no migration is needed.

Useful? React with 👍 / 👎.

Comment on lines +116 to +117
apply(preferences)
resolvedSources = byKey.compactMapValues { $0.source }

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 Surface narrower overrides before reporting a profile save

When any subtitle preference resolves from profile_device, this paints that effective value into the profile editor and records its source, but resolvedSources is never consumed by either settings UI. A subsequent user edit writes only the profile row and reports “Saved,” while the narrower device row continues to win, so playback does not adopt the displayed choice and reopening the screen restores the override. Either edit/reset the winning scope or visibly explain that the profile change is shadowed instead of presenting it as the effective saved value.

Useful? React with 👍 / 👎.

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

Actionable comments posted: 7

🧹 Nitpick comments (5)
iosApp/Tests/SettingsConformanceTests.swift (1)

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

Silence the SwiftLint optional_data_string_conversion warning.

-        let original = String(decoding: try fixtureData("conformance.json"), as: UTF8.self)
+        let data = try fixtureData("conformance.json")
+        let original = try XCTUnwrap(String(data: data, encoding: .utf8))
🤖 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 `@iosApp/Tests/SettingsConformanceTests.swift` at line 593, Update the
conformance fixture conversion in the test around fixtureData so it avoids
SwiftLint’s optional_data_string_conversion warning while preserving the decoded
conformance JSON string.

Source: Linters/SAST tools

iosApp/iosApp/Screens/Player/AppleQualityAxes.swift (1)

45-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Doc contradicts the value.

The comment says original is deliberately absent, but it is the last element of resolutionMembers. Either drop it from the list or reword the comment (it is presumably kept so a server-authored original validates as a member).

🤖 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 `@iosApp/iosApp/Screens/Player/AppleQualityAxes.swift` around lines 45 - 48,
Resolve the contradiction in resolutionMembers by either removing "original"
from the array or updating the comment to state that it remains accepted for
server-authored values. Keep the documentation aligned with the chosen
validation behavior and the existing ApplePlaybackQuality.normalizeStoredId
handling.
iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift (1)

194-200: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Warning styling relies on colour alone and a hardcoded point size.

warningFooter conveys failure purely through .red with a fixed size: 19, so it neither scales with the tvOS text-size setting nor reads as an error for colour-blind users. Consider reusing the shared footer component with a semantic style plus a leading Image(systemName: "exclamationmark.triangle").

🤖 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 `@iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift` around
lines 194 - 200, Update warningFooter(_:) to reuse the shared footer component
with its semantic warning/error styling instead of a fixed 19-point red Text.
Include a leading Image(systemName: "exclamationmark.triangle") so the warning
remains distinguishable without relying on colour and respects tvOS text-size
settings.
iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift (1)

15-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider hoisting the "__custom__" sentinel into SiloQualityPresets.

The same literal and semantics are also defined as customPresetTag in iosApp/iosApp/Screens/Settings/PlaybackSettingsView.swift (Line 204). One definition next to the preset table keeps the two platform pickers from drifting on a value that must never collide with a preset id.

🤖 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 `@iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift` around lines
15 - 31, Move the "__custom__" sentinel definition from TVSettingsComponents’
customQualityId into SiloQualityPresets alongside customPresetTag, then update
quality(including:) and the other picker reference to reuse that shared symbol.
Remove the duplicate literal while preserving the existing custom-entry no-op
behavior and preset-id collision protection.
iosApp/Tests/ProfileAndQualitySettingsTests.swift (1)

436-457: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Comment describes a scenario this test doesn't set up.

Only subtitleMode is changed, so the write batch has a single key — there is no "failed language write above" and no batch for it to abort. The assertion is still valid as a retry/mutation-id check, but the rationale is misleading about what it covers. Either drop the batch-abort narrative or also change subtitleLanguage before the failing save so the batch really has a preceding 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 `@iosApp/Tests/ProfileAndQualitySettingsTests.swift` around lines 436 - 457,
The testRetryingTheSameWriteReusesItsMutationId test only modifies subtitleMode,
so remove the misleading batch-abort and failed-language-write rationale from
its comments. Keep the two-write count and mutation-ID assertions focused on
retrying the same content, unless you explicitly add a subtitleLanguage change
to create the described multi-key batch scenario.
🤖 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 `@iosApp/iosApp/Networking/ContinuumAPI`+Settings.swift:
- Around line 126-130: Update the mutation request flow around trimmedMutationId
so an empty or whitespace-only mutationId fails fast before sending the write,
rather than omitting X-Silo-Mutation-Id. Preserve the existing trimmed value for
non-empty IDs and continue assigning it to the header.

In `@iosApp/iosApp/Screens/Player/PlayerSettings.swift`:
- Around line 793-856: Update legacySnapshot() to include .dolbyVisionEnabled,
.dvProfile7HDR10Fallback, and .seekCacheEnabled, reading each value through the
existing cached boolean helpers and matching their established legacy defaults.
Ensure all three keys are present in the returned snapshot so
importLegacySettingsIfNeeded migrates the stored local values instead of falling
back to contract defaults.

In `@iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift`:
- Around line 634-647: The retry task cancellation in scheduleRetryLocked allows
flushNow() to cancel an already-running drain and consume another retry attempt.
Update the retry registration and flushNow() coordination so an in-flight drain
is not cancelled—use the existing generation-check pattern or avoid cancellation
while isDraining—while still invalidating pending retry work and preserving
queued operations for a subsequent drain.
- Around line 562-599: Update the drain loop around pending, inFlight, and
SettingKey.playerDeviceSettings so it processes all snapshot keys: iterate the
known player keys first to preserve their stable order, then process any
remaining snapshot keys not included in that list. Reuse the existing send,
inFlight cleanup, outcome handling, retryable updates, and persistLocked flow
for the additional keys so none are silently dropped.

In `@iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift`:
- Around line 235-242: Update the save flow around the firstFailure early return
so a successfully landed language write always calls
ProfilePrefsStore.shared.setPreferredSubtitleLanguage(language), including when
a sibling mode or forced write fails. Preserve the existing failure saveState
handling, and only update the store when the language write itself succeeded.

In `@iosApp/iosApp/Screens/Settings/SubtitleSettingsView.swift`:
- Around line 113-124: Update the footer logic around
settingsServerUpgradeRequired and prefSaveState so saveStateView is not rendered
when settingsServerUpgradeRequired is true and the save state is
.serverUpgradeRequired; keep saveStateView rendering for all other states and
preserve the existing footer message.

In `@iosApp/Tests/PlayerSettingsFlushTests.swift`:
- Around line 250-251: Update the test cleanup around the UserDefaults suite
creation to retain the UUID-suffixed suite name and remove that exact domain in
the defer block; ensure cleanup targets the same suite passed to
UserDefaults(suiteName:) rather than the bare settings-journal-scope name.

---

Nitpick comments:
In `@iosApp/iosApp/Screens/Player/AppleQualityAxes.swift`:
- Around line 45-48: Resolve the contradiction in resolutionMembers by either
removing "original" from the array or updating the comment to state that it
remains accepted for server-authored values. Keep the documentation aligned with
the chosen validation behavior and the existing
ApplePlaybackQuality.normalizeStoredId handling.

In `@iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift`:
- Around line 15-31: Move the "__custom__" sentinel definition from
TVSettingsComponents’ customQualityId into SiloQualityPresets alongside
customPresetTag, then update quality(including:) and the other picker reference
to reuse that shared symbol. Remove the duplicate literal while preserving the
existing custom-entry no-op behavior and preset-id collision protection.

In `@iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift`:
- Around line 194-200: Update warningFooter(_:) to reuse the shared footer
component with its semantic warning/error styling instead of a fixed 19-point
red Text. Include a leading Image(systemName: "exclamationmark.triangle") so the
warning remains distinguishable without relying on colour and respects tvOS
text-size settings.

In `@iosApp/Tests/ProfileAndQualitySettingsTests.swift`:
- Around line 436-457: The testRetryingTheSameWriteReusesItsMutationId test only
modifies subtitleMode, so remove the misleading batch-abort and
failed-language-write rationale from its comments. Keep the two-write count and
mutation-ID assertions focused on retrying the same content, unless you
explicitly add a subtitleLanguage change to create the described multi-key batch
scenario.

In `@iosApp/Tests/SettingsConformanceTests.swift`:
- Line 593: Update the conformance fixture conversion in the test around
fixtureData so it avoids SwiftLint’s optional_data_string_conversion warning
while preserving the decoded conformance JSON string.
🪄 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: 13bb39d6-ef5d-4a20-a6f1-dab2ca5646bf

📥 Commits

Reviewing files that changed from the base of the PR and between b9bdfb0 and 46ecf49.

⛔ Files ignored due to path filters (1)
  • iosApp/iosApp/Networking/SettingKeys.generated.swift is excluded by !**/*.generated.*
📒 Files selected for processing (30)
  • iosApp/Tests/Fixtures/SettingsContract/SOURCE
  • iosApp/Tests/Fixtures/SettingsContract/conformance.json
  • iosApp/Tests/Fixtures/SettingsContract/manifest.json
  • iosApp/Tests/PlayerSettingsFlushTests.swift
  • iosApp/Tests/ProfileAndQualitySettingsTests.swift
  • iosApp/Tests/SettingValuesAPITests.swift
  • iosApp/Tests/SettingsConformanceTests.swift
  • iosApp/Tests/SettingsContractResolve.swift
  • iosApp/iosApp/Networking/ContinuumAPI+Settings.swift
  • iosApp/iosApp/Networking/ContinuumAPI.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Networking/ProfileSettingsWriter.swift
  • iosApp/iosApp/Networking/SettingValueModels.swift
  • iosApp/iosApp/Networking/SiloQualityPresets.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift
  • iosApp/iosApp/Screens/Player/AppleQualityAxes.swift
  • iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift
  • iosApp/iosApp/Screens/Player/PlayerSettings.swift
  • iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Settings/PlaybackSettingsView.swift
  • iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift
  • iosApp/iosApp/Screens/Settings/SettingsView.swift
  • iosApp/iosApp/Screens/Settings/SettingsViewModel.swift
  • iosApp/iosApp/Screens/Settings/SubtitleSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVPlaybackSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift
  • iosApp/project.yml

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

ℹ️ 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 +281 to +285
let preferredQuality = normalizedQualityPreference(
preferredQualityOverride ?? PlayerSettings.shared.preferredQuality
)
let bandwidthCapKbps = PlayerSettings.shared.maxBitrateKbps.flatMap {
$0 > 0 ? $0 : 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.

P2 Badge Let in-player quality overrides replace the saved cap

When a saved preset has a low bitrate cap and the user selects a higher rung—or Auto—from the in-player quality switcher, preferredQualityOverride replaces only the resolution while this still reads the persisted cap. Protocol V3 therefore sends the new quality with the old lower cap, and the legacy path likewise clamps shouldForceTranscode and targetBitrateKbps to that cap, so the switch cannot actually raise quality or return to unrestricted Auto. Derive the cap from the explicit compound override, or otherwise let that override replace both quality axes.

Useful? React with 👍 / 👎.

let atResolution = ApplePlaybackQuality.tiers.filter {
split($0.id).resolution == resolution
}
guard !atResolution.isEmpty else { return ApplePlaybackQuality.autoId }

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 2160p instead of collapsing it to Auto

When the new shared 4K preset stores (2160p, nil), no local Apple tier matches it and this guard returns Auto. normalizedQualityPreference then converts it to nil, so on a multi-version title selectVersion can reuse a previously watched 1080p file and protocol V3 receives auto; the user's 4K choice is therefore indistinguishable from Auto during playback. Preserve a 2160p playback identifier through the join and protocol mapping.

AGENTS.md reference: AGENTS.md:L16-L17

Useful? React with 👍 / 👎.

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift (1)

604-617: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Guard pre-scope writes
If any setter can call enqueue before currentScopeIdentifier exists, this path drops the edit: save() no-ops without a storage key, and the first transition to a real scope clears pending. Add a deferral/log or keep these setters unreachable until scope is established.

🤖 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 `@iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift` around lines 604 -
617, Ensure writes enqueued before a scope identifier exists are not silently
discarded by persistLocked. Defer or retain those pending writes until a real
scope is established, or prevent the relevant setters from calling enqueue
before then; preserve them through the first scope transition and add logging if
deferral is used.
🧹 Nitpick comments (2)
iosApp/Tests/ProfileAndQualitySettingsTests.swift (1)

573-584: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider replacing the fixed 20 ms interleave windows with polling.

Both tests rely on Task.sleep(for: .milliseconds(20)) landing inside the 100 ms write delay to guarantee the first save is suspended when the second edit arrives. On a loaded CI machine that ordering is not guaranteed, and the failure presents as a confusing ordering assertion rather than a timeout. testEditDuringShadowRefreshStillSavesNewestValue already polls on effectiveCalls().count; the same shape (poll until transport.writes().count == 1) would make these deterministic.

Also applies to: 697-709

🤖 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 `@iosApp/Tests/ProfileAndQualitySettingsTests.swift` around lines 573 - 584,
Replace the fixed 20 ms sleeps in
testOverlappingEditsToOneProfileKeyLandNewestLast and
testEditDuringShadowRefreshStillSavesNewestValue with polling that waits until
transport.writes().count equals 1, using the existing polling pattern from
effectiveCalls(). Preserve the test sequence so the second edit occurs only
after the first write has started, with an explicit timeout to avoid indefinite
waiting.
iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift (1)

60-69: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

tvOS "Override active" footer loses the cautionary styling iOS has.

On iOS, the same message uses .continuumWarning styling to visually flag that a narrower scope is winning (SubtitleSettingsView.swift lines 121-124). Here it renders via plain TVSettingsFooter, identical in appearance to ordinary explanatory text — and TVSettingsWarningFooter isn't a fit either, since its doc scopes it to "server and persistence failures" and uses .continuumError. Confirm whether this is an intentional platform difference or whether tvOS needs an equivalent cautionary-styled footer.

🤖 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 `@iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift` around
lines 60 - 69, Update the tvOS override-message branch in the settings view to
use a cautionary-styled footer equivalent to iOS’s `.continuumWarning`, rather
than plain `TVSettingsFooter` or the error-scoped `TVSettingsWarningFooter`.
Preserve the existing message text and conditional behavior for
`viewModel.prefs.subtitleProfileOverrideMessage`.
🤖 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 `@iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift`:
- Around line 141-144: Update the Auto branch in the quality-selection logic
around exceedsBitrateCap so an unknown selectedVersion bitrate is treated as not
exceeding the cap, while retaining the existing positive capKbps requirement and
behavior for known bitrates.

In `@iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift`:
- Around line 207-209: Update the bandwidthCapKbps handling in replanProtocolV3
so a quality_changed replan refreshes the cap from the current quality
preference before building the request, while other replans continue reusing the
captured cap for recovery. Keep the refreshed cap synchronized with the
clientQualityId update and preserve the existing startSession capture behavior.

In `@iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift`:
- Around line 769-772: Update the scope-change branch in PlayerSettingsFlusher
so the log for the .settled result no longer reports kept: true; mark the write
as not kept, while preserving the existing journal scope check and return
behavior.

---

Outside diff comments:
In `@iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift`:
- Around line 604-617: Ensure writes enqueued before a scope identifier exists
are not silently discarded by persistLocked. Defer or retain those pending
writes until a real scope is established, or prevent the relevant setters from
calling enqueue before then; preserve them through the first scope transition
and add logging if deferral is used.

---

Nitpick comments:
In `@iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift`:
- Around line 60-69: Update the tvOS override-message branch in the settings
view to use a cautionary-styled footer equivalent to iOS’s `.continuumWarning`,
rather than plain `TVSettingsFooter` or the error-scoped
`TVSettingsWarningFooter`. Preserve the existing message text and conditional
behavior for `viewModel.prefs.subtitleProfileOverrideMessage`.

In `@iosApp/Tests/ProfileAndQualitySettingsTests.swift`:
- Around line 573-584: Replace the fixed 20 ms sleeps in
testOverlappingEditsToOneProfileKeyLandNewestLast and
testEditDuringShadowRefreshStillSavesNewestValue with polling that waits until
transport.writes().count equals 1, using the existing polling pattern from
effectiveCalls(). Preserve the test sequence so the second edit occurs only
after the first write has started, with an explicit timeout to avoid indefinite
waiting.
🪄 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: ac675ce8-9877-4155-a808-e83679633446

📥 Commits

Reviewing files that changed from the base of the PR and between 46ecf49 and e64a09a.

📒 Files selected for processing (13)
  • iosApp/Tests/PlayerSettingsFlushTests.swift
  • iosApp/Tests/ProfileAndQualitySettingsTests.swift
  • iosApp/Tests/SettingValuesAPITests.swift
  • iosApp/iosApp/Networking/ContinuumAPI+Settings.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift
  • iosApp/iosApp/Screens/Player/AppleQualityAxes.swift
  • iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift
  • iosApp/iosApp/Screens/Player/PlayerSettings.swift
  • iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift
  • iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift
  • iosApp/iosApp/Screens/Settings/SubtitleSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift

@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: 897704da2c

ℹ️ 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".

// MARK: - Sending

private func send(_ key: SettingKey, _ write: PendingSettingWrite) async -> FlushOutcome {
if let journal, write.scopeIdentifier != journal.scopeIdentifier {

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 Bind each queued write to its captured session

When a user opens the profile picker while a drain is active, this one-time comparison can pass for the old scope, after which transport.putValue suspends and ContinuumAPI.putValue resolves its profile header from the newly selected profile; the old setting can therefore be written under the new X-Profile-Id. Fresh evidence after the prior comment is that the current fix still validates the scope before, rather than atomically with, the asynchronous request targeting. Pass the captured server/profile/device identity through the transport or cancel the old drain during the transition.

AGENTS.md reference: AGENTS.md:L19-L21

Useful? React with 👍 / 👎.

private func pendingSubtitleWrites() -> [SubtitleWrite] {
let language = Self.outboundLanguage(subtitleLanguage)
var writes: [SubtitleWrite] = []
if subtitleLanguage != savedBaseline.subtitleLanguage {

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 Queue a revert even when the prior write fails

If a subtitle PUT is suspended while the user changes the control back to its saved baseline, and that PUT then reports a retryable transport failure, the server may still have applied the first value even though savedBaseline remains unchanged. The next serialized pass reaches this comparison, considers the reverted value already saved, and sends nothing, leaving the UI and server divergent. Capture the queued revert independently of the baseline, as the metadata-language path already does.

Useful? React with 👍 / 👎.

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

Caution

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

⚠️ Outside diff range comments (1)
iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift (1)

156-180: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Unknown-bitrate-as-"exceeds-cap" still forces unnecessary transcodes (now on original/2160p too).

exceedsBitrateCap treats a missing/zero source bitrate as exceeding the cap (guard let sourceBitrateKbps = sourceBitrateKbps(for: version) else { return true }). This was previously flagged for the Auto path; the branch now also covers originalId (Line 162) and the new ultraHDId (Line 166-169), so a source with unknown bitrate metadata plus any positive capKbps is forced into transcode even though it might already direct-play fine.

🐛 Proposed narrowing
     static func shouldForceTranscode(
         preferredQualityId: String?,
         selectedVersion: FileVersion,
         capKbps: Int? = nil
     ) -> Bool {
         let id = normalizeStoredId(preferredQualityId)
         if id == autoId || id == originalId {
             guard let capKbps, capKbps > 0 else { return false }
-            return exceedsBitrateCap(selectedVersion, ceilingKbps: capKbps)
+            guard let sourceBitrateKbps = sourceBitrateKbps(for: selectedVersion) else {
+                return false
+            }
+            return sourceBitrateKbps > capKbps
         }
         if id == ultraHDId {
-            let exceedsBandwidth = capKbps.flatMap { $0 > 0 ? $0 : nil }.map {
-                exceedsBitrateCap(selectedVersion, ceilingKbps: $0)
-            } ?? false
+            let exceedsBandwidth = capKbps.flatMap { $0 > 0 ? $0 : nil }.map { cap in
+                sourceBitrateKbps(for: selectedVersion).map { $0 > cap } ?? false
+            } ?? false
             return exceedsBandwidth || exceedsResolutionCap(
                 selectedVersion,
                 targetResolution: ultraHDId
             )
         }
🤖 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 `@iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift` around lines 156 -
180, Update shouldForceTranscode so unknown or zero source bitrate does not
force transcoding for autoId, originalId, or ultraHDId when evaluating capKbps.
Adjust exceedsBitrateCap or the relevant callers to treat unavailable bitrate as
not exceeding the cap, while preserving resolution-cap checks and known-bitrate
behavior.
🧹 Nitpick comments (1)
iosApp/Tests/ProfileAndQualitySettingsTests.swift (1)

726-740: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate waitUntil helper — extract to shared test support.

This is byte-for-byte the same helper already defined in iosApp/Tests/PlayerSettingsFlushTests.swift (lines 1249-1264). The file also still has a manual for _ in 0..<100 { ...; Task.sleep } loop (lines 673-676) doing the same thing inline. Worth pulling into a shared XCTestCase extension in the test target so future Apple test files reuse one implementation instead of re-deriving it.

♻️ Suggested extraction
// iosApp/Tests/Support/XCTestCase+Waiting.swift
extension XCTestCase {
    func waitUntil(
        _ description: String,
        timeout: Duration = .seconds(5),
        _ condition: `@escaping` () -> Bool,
        file: StaticString = `#filePath`,
        line: UInt = `#line`
    ) async throws {
        let deadline = ContinuousClock.now + timeout
        while ContinuousClock.now < deadline {
            if condition() { return }
            try await Task.sleep(for: .milliseconds(10))
        }
        XCTFail("timed out waiting for \(description)", file: file, line: line)
    }
}
-    private func waitUntil(
-        _ description: String,
-        timeout: Duration = .seconds(5),
-        _ condition: `@escaping` () -> Bool,
-        file: StaticString = `#filePath`,
-        line: UInt = `#line`
-    ) async throws {
-        let deadline = ContinuousClock.now + timeout
-        while ContinuousClock.now < deadline {
-            if condition() { return }
-            try await Task.sleep(for: .milliseconds(10))
-        }
-        XCTFail("timed out waiting for \(description)", file: file, line: line)
-    }
🤖 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 `@iosApp/Tests/ProfileAndQualitySettingsTests.swift` around lines 726 - 740,
Extract the duplicated waitUntil helper from ProfileAndQualitySettingsTests and
PlayerSettingsFlushTests into a shared XCTestCase extension under test support,
then remove both local definitions so tests use the shared implementation.
Replace the manual polling loop in ProfileAndQualitySettingsTests with
waitUntil, preserving its timeout and condition behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift`:
- Around line 156-180: Update shouldForceTranscode so unknown or zero source
bitrate does not force transcoding for autoId, originalId, or ultraHDId when
evaluating capKbps. Adjust exceedsBitrateCap or the relevant callers to treat
unavailable bitrate as not exceeding the cap, while preserving resolution-cap
checks and known-bitrate behavior.

---

Nitpick comments:
In `@iosApp/Tests/ProfileAndQualitySettingsTests.swift`:
- Around line 726-740: Extract the duplicated waitUntil helper from
ProfileAndQualitySettingsTests and PlayerSettingsFlushTests into a shared
XCTestCase extension under test support, then remove both local definitions so
tests use the shared implementation. Replace the manual polling loop in
ProfileAndQualitySettingsTests with waitUntil, preserving its timeout and
condition behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e3a0b368-fd12-4465-a863-45304fdb8934

📥 Commits

Reviewing files that changed from the base of the PR and between e64a09a and 897704d.

📒 Files selected for processing (8)
  • iosApp/Tests/PlayerSettingsFlushTests.swift
  • iosApp/Tests/ProfileAndQualitySettingsTests.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift
  • iosApp/iosApp/Screens/Player/AppleQualityAxes.swift
  • iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Player/Sheets/PlayerSettingsSheet.swift
  • iosApp/iosApp/Screens/Player/tvOS/TVPlayerInfoHUD.swift

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

ℹ️ 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".

]

static let settingsOptions: [ApplePlaybackQualityOption] = [auto] + tiers
static let settingsOptions: [ApplePlaybackQualityOption] = [auto, original, ultraHD] + tiers

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 Reload when Original or 4K raises source quality

On legacy non-V3 playback, these newly exposed options do not actually switch to a better file when the current lower-resolution version is already direct-playing or remuxing. For example, after a saved 720p preference selects a 720p alternate, choosing Original or 4K makes shouldForceTranscode return false, and PlayerViewModel.switchQuality takes its direct/remux early return at lines 4205-4210, changing only activeQualityId; playback remains on the 720p file while the UI reports Original or 4K. Re-run version selection when the requested tier can raise the source quality.

Useful? React with 👍 / 👎.

Comment on lines +1474 to +1475
if useCopyVideo {
logger.warning("Video copy rejected, falling back to 1080p transcode")

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 Original from falling back to a transcode

When legacy playback prepares an HLS copy for the Original preset and an older server rejects that copy request with 422, this broadened branch sends a 1080p/H.264 transcode fallback. That directly violates the preset's “Never transcode” contract; Original should surface the copy failure rather than silently reduce and re-encode the video. Fresh evidence beyond the earlier Original mapping issue is this explicit non-copy fallback after Original is now preserved through quality mapping.

Useful? React with 👍 / 👎.

Comment on lines +51 to +55
_ = try await api.putValue(
key: key,
scope: .profile,
value: value,
mutationId: mutationId

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 Bind profile preference writes to the edited profile

When an onChange save is still queued or entering this async call while the user switches profiles, omitting profileId makes ContinuumAPI.putValue resolve X-Profile-Id from whichever session is active when profileHeaders runs. The old editor captured activeProfile.id before suspending, but the new transport can therefore apply the previous profile's subtitle or metadata edit to the newly selected profile. Capture the editor's profile identity when scheduling the logical write and pass it explicitly through this transport.

Useful? React with 👍 / 👎.

Comment on lines +394 to +395
guard let self, self.hasPendingWrites else { return }
Task { await self.flushHoldingTheProcessOpen() }

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 the process alive for already-draining writes

If the app backgrounds after the debounce drain has moved its snapshot from pending into inFlight, this guard returns because hasPendingWrites checks only pending. No iOS background-task assertion is then started for the request already awaiting its response, so it can be suspended or terminated despite the lifecycle handling specifically intended to let such writes land; the journal only recovers it on a later launch. Treat an active drain or nonempty inFlight collection as work requiring flushHoldingTheProcessOpen() too.

Useful? React with 👍 / 👎.

// any of them to a contract member.
let legacyQualityId = defaults.string(forKey: Self.cacheKey(Keys.preferredQuality))
?? defaults.string(forKey: Keys.preferredQuality)
let legacyResolution = SiloQualityPresets.normalizeResolution(legacyQualityId)

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 Migrate the legacy 328p tier through AppleQualityAxes

For an upgrading device whose old stored tier is 328p (or its 420p alias), this normalization produces resolution auto, while the bitrate calculation below correctly recovers 700 kbps. The migrated pair is therefore auto/700 rather than the intended contract-compatible 480p/700, changing the resolution constraint and displaying a custom Auto preset. Fresh evidence after the earlier legacy-bitrate finding is that the remaining resolution half still bypasses AppleQualityAxes.split, whose explicit 328p mapping already returns 480p.

Useful? React with 👍 / 👎.

Comment on lines 950 to 951
if legacyValue == entry.value {
continue

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 Compare numeric setting values semantically during migration

For the default playback speed, legacySnapshot constructs .double(1.0), but SettingJSONValue.init(from:) attempts integer decoding first, so the server's integral JSON number decodes as .int(1). Synthesized enum equality treats those as different here, causing every such device to migrate an explicit player.playback_speed = 1 row even though it matched the inherited default; the device then remains pinned to 1× if a later contract revision changes that default. Use numeric-equivalent comparison rather than case-sensitive enum equality.

Useful? React with 👍 / 👎.

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift (1)

1474-1479: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider surfacing a readable error when Original refuses the copy fallback.

Rethrowing the raw 422 means the user sees a transport-level HTTP error, while the sibling branch below produces explanatory APIError.unsupportedMedia messages. Wrapping this with a short explanation ("Original quality can't be re-encoded on this server…") would keep the failure actionable.

🤖 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 `@iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift` around lines 1474 -
1479, Update the useCopyVideo branch in the playback session error handling to
throw a readable APIError.unsupportedMedia message when
ApplePlaybackQuality.allowsLegacyCopyFallbackToTranscode returns false, instead
of rethrowing the raw 422 error. Keep the existing fallback behavior unchanged
when the quality is allowed.
🤖 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 `@iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift`:
- Around line 560-591: Update writeMetadataLanguage so an in-flight write for a
profile that is no longer bound settles saveState to a terminal non-saving state
before returning from both the success and failure paths. Preserve the existing
guard behavior for current-profile writes and use the same settled-state
convention as saveSubtitlePrefs().

---

Nitpick comments:
In `@iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift`:
- Around line 1474-1479: Update the useCopyVideo branch in the playback session
error handling to throw a readable APIError.unsupportedMedia message when
ApplePlaybackQuality.allowsLegacyCopyFallbackToTranscode returns false, instead
of rethrowing the raw 422 error. Keep the existing fallback behavior unchanged
when the quality is allowed.
🪄 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: b4eb8dc3-e353-4152-9d25-5b942fc9bfe5

📥 Commits

Reviewing files that changed from the base of the PR and between aa3f626 and ed3147d.

📒 Files selected for processing (15)
  • iosApp/Tests/PlayerSettingsFlushTests.swift
  • iosApp/Tests/ProfileAndQualitySettingsTests.swift
  • iosApp/Tests/SettingValuesAPITests.swift
  • iosApp/Tests/SettingsConformanceTests.swift
  • iosApp/Tests/SettingsContractResolve.swift
  • iosApp/iosApp/Networking/ProfileSettingsWriter.swift
  • iosApp/iosApp/Networking/SettingValueModels.swift
  • iosApp/iosApp/Screens/Player/ApplePlaybackQuality.swift
  • iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift
  • iosApp/iosApp/Screens/Player/PlayerSettings.swift
  • iosApp/iosApp/Screens/Player/PlayerSettingsFlusher.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift
  • iosApp/iosApp/Screens/Settings/SettingsViewModel.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • iosApp/Tests/SettingValuesAPITests.swift

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

ℹ️ 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 +706 to +708
maxBitrateKbps = effectiveByKey[.maxBitrateKbps]?.value.intValue.flatMap {
$0 > 0 ? $0 : 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 Restore the migrated bitrate cap after importing it

On the first canonical refresh for an upgrading device whose legacy quality included a bitrate cap, this assigns the server's pre-migration default null to maxBitrateKbps; the importer then sends the recovered cap but never reapplies its snapshot or refetches the effective values. The client therefore remains locally uncapped until another successful refresh and can start playback above the user's saved limit. Fresh evidence beyond the earlier legacy-migration comment is that the cap is now recovered and written correctly, but this assignment still discards it from the active settings after that write.

Useful? React with 👍 / 👎.

Comment on lines +856 to +858
case .serverUpgradeRequired:
log(key, "server does not serve the canonical settings API", kept: true)
return .retryOnNextTrigger

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 Resolve resets instead of retaining them on old servers

When a user selects “Reset Playback Overrides” against a server without the canonical settings routes, every DELETE reaches this branch and remains queued while refreshFromServer() silently keeps the existing cached values. The reset therefore visibly does nothing, and the retained deletes may execute unexpectedly after the server is later upgraded. Apply the local fallback or surface that reset cannot complete rather than persisting these reset operations indefinitely.

Useful? React with 👍 / 👎.

Comment on lines +58 to +62
.init(
id: "original",
label: "Original",
description: "Never transcode. Needs bandwidth to match the file.",
resolution: resolutionOriginal,

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 Select the highest source for the Original preset

When a multi-version title has a remembered lower-resolution lastFileId, choosing this new Original preset still starts that remembered file instead of the best source: selectVersion cannot match original because its resolution rank is zero, so it falls through to lastFileId ahead of the ranked list. The lower-resolution file can then direct-play while the UI reports Original. Fresh evidence beyond the earlier Original mapping and in-player reload comments is that initial playback through the saved preset follows this separate fallback path.

Useful? React with 👍 / 👎.

Comment on lines +640 to +644
let scopeIdentifier = journal.scopeIdentifier
var owed = pending.filter { $0.value.scopeIdentifier == scopeIdentifier }
for (key, write) in inFlight
where write.scopeIdentifier == scopeIdentifier && owed[key] == nil {
owed[key] = write

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 Clear settled deletes from their original journal partition

When the active profile changes while a reset DELETE is in flight, this persistence pass filters against the newly current journal scope, so the successfully settled operation is never removed from the old profile's on-disk partition. Returning to that profile restores and sends the stale DELETE again; because DELETE carries no mutation ID, it can erase a newer device-scoped value created after the original reset. Fresh evidence beyond the prior scope-transition comments is that the request targeting is now captured correctly, but journal retirement still follows the mutable current scope rather than the write's captured scope.

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: f7c1490459

ℹ️ 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 +332 to +334
} catch {
failures[identity] = error
let stillEditingWrittenProfile = boundProfileId == write.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 Disable profile edits that cannot take effect

When load() identifies a pre-contract server, the subtitle controls remain enabled and every onChange reaches this failure path. The editor only retains the attempted value in memory for another retry; it updates neither a playback preference store nor UserDefaults, and the writer has no legacy fallback, so language, behavior, and forced-subtitle edits do not affect playback and disappear when the editor is recreated even though the UI accepts them. Disable these controls for old servers or implement the promised device-local/legacy fallback.

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: f335a1275b

ℹ️ 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 +896 to +898
if let appearance = try? SettingJSONValue.encoding(legacyAppearance) {
snapshot[.subtitleAppearance] = appearance
}

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 Skip default subtitle migration on clean installs

On a fresh installation, where no legacy subtitle appearance was ever stored, SubtitleAppearance.decode(from: nil) still produces the Apple default and these lines unconditionally add it to the migration snapshot. During the first canonical refresh, any different profile/default appearance is therefore treated as an old device preference and written at profile_device, silently shadowing the server-driven style on every newly installed Apple device. Gate this import on evidence of a pre-contract installation while still preserving the shipped default for actual upgrades.

AGENTS.md reference: AGENTS.md:L19-L21

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit 67047b9 into main Jul 30, 2026
1 check passed
@Quick104
Quick104 deleted the feat/settings-contract branch July 30, 2026 14:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant