Skip to content

feat: add synced navigation and card customization - #120

Merged
Quick104 merged 4 commits into
mainfrom
codex/ui-customization-apple
Aug 4, 2026
Merged

Quick104 merged 4 commits into
mainfrom
codex/ui-customization-apple

Conversation

@Quick104

@Quick104 Quick104 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Part of Silo-Server/silo-server#376.

Apple clients had fixed navigation and card presentation, and their preferences could not follow a profile across like devices.

Depends on Silo-Server/silo-server#538.

Approach

  • Add revision-5 settings support for client-family navigation, profile-wide shortcuts, and card presentation.
  • Add Balanced, Compact, Cinema, and Artwork Only presets plus title/metadata visibility and poster sizing across shared card/grid surfaces.
  • Add a customization editor for iOS/macOS and a focus-safe tvOS editor/top menu with reorder, visibility, library, section, and collection destinations.
  • Bind durable settings/outbox work to captured server, account, profile, PIN, and client-family authority across refreshes and identity transitions.
  • Serialize server, sign-in, sign-out, pairing, remote-control, and refresh transitions so requests and persisted credentials cannot cross account or server generations.
  • Preserve backward-compatible legacy behavior when the connected server does not advertise revision-5/atomic shortcut capabilities.

Validation

  • Settings-contract fixtures are byte-identical to server commit 5e185e6e592613fb84529e192ce13c7551374ff1.
  • XCTest passes 150/150 combined customization, settings-contract, auth-transition, pairing, diagnostics, and persistence tests with no failures or skips.
  • iOS Simulator, tvOS Simulator, and macOS builds pass with task-scoped NVMe DerivedData.
  • git diff --check passes.
  • The required external autoreview ran successfully during review closeout; its two accepted refresh/reachability findings were fixed and covered by regression tests. A later scoped rerun returned clean. The final aggregate rerun failed closed before engine invocation because the added XCTest fixtures exercise accessToken/refreshToken fields and match its secret-like-content scanner; no exclusion or bypass was used. Independent fixed-point reviews found no remaining in-scope P1/P2 issues after the final teardown and sign-out fixes.

Build success is not physical Apple TV remote proof. The tvOS implementation uses the documented stable focus graph, but no physical D-pad runtime session was available for this PR.

AI Disclosure

  • Tool(s): OpenAI Codex
  • Model(s): gpt-5.6-sol
  • Involvement: fully AI-generated
  • Adversarial review: findings were verified and resolved across authority capture, temporary/persistent refresh routing, durable outbox reconciliation, capability downgrade behavior, collision-free shortcut identity, per-destination routing, item limits, tvOS focus/navigation state, generation-safe temporary teardown, and refusal-aware sign-out navigation.

Checklist

  • I ran focused tests and all affected Apple platform builds.
  • I verified the vendored contract against the exact server commit.
  • I ran the required adversarial autoreview closeout and documented its fail-closed scanner disposition above.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR advances the settings contract to revision 5. It adds profile-client resolution, identity-safe networking, synchronized UI customization, customizable navigation, responsive cards, accessibility labels, and persistence validation.

Changes

Settings contract and resolution

Layer / File(s) Summary
Revision-5 contract and profile-client resolution
iosApp/Tests/Fixtures/SettingsContract/*, iosApp/Tests/SettingsConformanceTests.swift, iosApp/Tests/SettingsContractResolve.swift, iosApp/iosApp/Networking/SettingValueModels.swift
Adds profile-client scopes, client-family matching, customization settings, metadata overrides, capability flags, and conformance cases.

Identity-safe networking

Layer / File(s) Summary
Identity-safe requests and authentication transitions
iosApp/iosApp/Networking/{HTTPClient,TokenStore,ContinuumAPI+Settings,ServerRegistry}.swift, iosApp/iosApp/Screens/Auth/*, iosApp/iosApp/Pairing/Receiver/*, iosApp/iosApp/Control/tvOS/*
Captures request identity, coordinates refreshes and transitions, prevents stale credential writes, and validates server, profile, and temporary-auth changes.
Networking and transition validation
iosApp/Tests/SettingValuesAPITests.swift, iosApp/Tests/PairingCoordinatorTests.swift
Tests refresh coordination, identity boundaries, cancellation, client-family headers, shortcut writes, and pairing persistence.

UI customization and navigation

Layer / File(s) Summary
Persisted customization store
iosApp/iosApp/Navigation/UICustomizationPreferences.swift
Adds models, capability gating, identity-scoped caching, optimistic mutations, ordered writes, retries, resets, and reconciliation.
Custom destination projection
iosApp/iosApp/ContentView.swift, iosApp/iosApp/Screens/Browse/LibrariesTabView.swift, iosApp/iosApp/tvOS/Navigation/*, iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryPillRow.swift
Projects customized destinations and library shortcuts, filters unavailable libraries, scopes caches, and coordinates tvOS focus generations.
Customization settings screens
iosApp/iosApp/Screens/Settings/{InterfaceCustomizationView,SettingsView,ProfilePrefsEditor}.swift, iosApp/iosApp/tvOS/Screens/Settings/*
Adds iOS and tvOS controls for card presentation, menu editing, shortcuts, pins, overrides, capability states, and disabled pickers.

Card presentation and accessibility

Layer / File(s) Summary
Responsive card rendering
iosApp/iosApp/Components/*, iosApp/iosApp/Screens/{Browse,Calendar,Collections,Detail,Home,Personal,Requests}/*, iosApp/iosApp/tvOS/Screens/*
Applies poster-size scaling and caption preferences across grids, rails, cards, and library views.
Accessibility labels
iosApp/iosApp/Components/{MediaCard,EpisodeThumbCard}.swift, iosApp/iosApp/Screens/{Calendar,Collections,Detail,Home,Requests}/*, iosApp/iosApp/tvOS/Screens/*
Adds consolidated labels containing titles, episode data, years, watched state, playback state, and collection metadata.

Validation

Layer / File(s) Summary
Customization persistence and concurrency validation
iosApp/Tests/UICustomizationPreferencesTests.swift
Tests projection, validation, caching, retries, mutation ordering, capability gating, identity changes, failures, rollback, and durable recovery.

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

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.41% 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 clearly and concisely describes the pull request's main changes: synced navigation and card customization.
✨ 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 codex/ui-customization-apple

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

ℹ️ 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 iosApp/iosApp/ContentView.swift Resolved

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

🧹 Nitpick comments (12)
iosApp/Tests/UICustomizationPreferencesTests.swift (1)

711-713: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace the assertion-side fixed sleeps with a polling wait.

The probes already provide deterministic waits for transport events. The remaining Task.sleep calls wait for store-side quiescence after those events, which depends on machine load. Under a loaded CI runner these windows can expire before the store settles, so the tests can fail intermittently.

Affected sites: lines 713, 862, 1088, 1202, 1297, 1351, and 2351. Keep the sleep at line 708, because it intentionally delays the release of a gated write to prove ordering.

A small polling helper keeps each assertion unchanged and removes the timing dependency.

♻️ Proposed helper and one converted call site

Add the helper to the test file:

`@MainActor`
private func waitUntil(
    timeout: TimeInterval = 2,
    _ condition: () -> Bool
) async {
    let deadline = Date().addingTimeInterval(timeout)
    while !condition(), Date() < deadline {
        try? await Task.sleep(nanoseconds: 2_000_000)
    }
}

Then convert the assertion-side waits:

     await transport.waitForCompletedWrites(2)
     await release.value
-    try await Task.sleep(nanoseconds: 20_000_000)
+    await waitUntil { !preferences.isSaving }
🤖 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/UICustomizationPreferencesTests.swift` around lines 711 - 713,
In UICustomizationPreferencesTests, add the proposed MainActor waitUntil polling
helper and replace the fixed Task.sleep calls at the affected assertion-side
sites with condition-based polling, preserving each existing assertion. Keep the
intentional gated-write sleep at line 708 unchanged, and use the existing
transport/store state predicates to wait until quiescence rather than relying on
fixed timing.
iosApp/iosApp/Networking/AuthTokenModels.swift (1)

45-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Collapse the duplicate initializers and keep the credential labeled.

Both initializers have the same body. The labeled one only restores what the synthesized memberwise initializer already provided before any explicit initializer was declared. So the pair exists to support one unlabeled call site, RefreshRequest(refreshValue) in HTTPClient.performScopedRefresh.

Delete both initializers and label that call site. The memberwise initializer returns, the duplication disappears, and an unlabeled credential argument no longer appears at a call site.

♻️ Proposed refactor
 struct RefreshRequest: Codable {
     let refreshToken: String
-
-    init(refreshToken value: String) {
-        refreshToken = value
-    }
-
-    init(_ value: String) {
-        refreshToken = value
-    }
 }

Then update the scoped refresh call site in iosApp/iosApp/Networking/HTTPClient.swift:

-            request.httpBody = try encoder.encode(RefreshRequest(refreshValue))
+            request.httpBody = try encoder.encode(RefreshRequest(refreshToken: refreshValue))
🤖 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/Networking/AuthTokenModels.swift` around lines 45 - 55, Remove
both explicit initializers from RefreshRequest so its synthesized memberwise
initializer remains available with the refreshToken label. Update
HTTPClient.performScopedRefresh to construct RefreshRequest using the labeled
refreshToken argument instead of the unlabeled call.
iosApp/Tests/SettingsContractResolve.swift (1)

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

Consider hoisting the client-family vocabulary to a named constant.

The literal ["tv", "mobile", "tablet", "desktop", "web"] sits inside the per-row filter closure. A future family added to the server contract must then be found inside this closure. A file-level constant names the vocabulary once and documents that an unrecognized family fails closed.

Note the behavior this list adds beyond the equality check: a stored row whose client_family equals the context family still fails to resolve when the family is outside the list. That is stricter than the server for a family this build does not know. Keep it if the strictness is intended for the fixture runner.

♻️ Proposed refactor
+/// Client families the vendored contract defines. A family outside this set
+/// fails closed rather than resolving a profile_client row.
+private let supportedClientFamilies: Set<String> = ["tv", "mobile", "tablet", "desktop", "web"]
+
 private func pickForScope(
         case SettingsContractSource.profileClient:
             return (row.profileId ?? "") == profileId
                 && (row.clientFamily ?? "") == clientFamily
-                && ["tv", "mobile", "tablet", "desktop", "web"].contains(clientFamily)
+                && supportedClientFamilies.contains(clientFamily)
🤖 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/SettingsContractResolve.swift` around lines 358 - 361, Hoist the
client-family vocabulary used by the profileClient resolution case into a named
file-level constant, then reuse that constant in the per-row filter instead of
the inline array. Preserve the existing equality checks and fail-closed behavior
for unrecognized families.
iosApp/Tests/SettingValuesAPITests.swift (1)

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

Localize which rejection failed.

testScopedRefreshRejectsChangedServerAccountAndTemporaryScope covers four independent rejections: a changed server URL, a stale previous refresh value, temporary credential provenance, and a cross-server write. A failure reports only the method name, so the failing scenario is not identifiable from the test name alone.

Wrap each scenario in XCTContext.runActivity(named:), the way SettingsConformanceTests.testEveryCaseResolvesToItsExpectedEffectiveValues names each conformance case. Splitting into four methods works too, at the cost of repeating the TokenStore setup.

🤖 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/SettingValuesAPITests.swift` around lines 746 - 850, Update
testScopedRefreshRejectsChangedServerAccountAndTemporaryScope to wrap each of
its four rejection scenarios—changed server URL, stale refresh value, temporary
credential provenance, and cross-server write—in a separately named
XCTContext.runActivity block, preserving the existing setup and assertions.
iosApp/iosApp/Networking/HTTPClient.swift (1)

20-43: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Name the initializer parameters after the properties they set.

The external labels do not match the stored properties, and one internal name carries no meaning:

  • accessValue sets accessToken.
  • refreshValue value sets refreshToken.
  • profileValue otherValue sets profileToken.

TokenStore.captureRequestAuth is the only constructor. Rename the parameters to the property names, and the synthesized memberwise initializer covers the whole type. The explicit initializer then disappears, and the call site reads as the credential set it builds.

♻️ Proposed refactor
 struct CapturedHTTPRequestAuth: Sendable {
     let serverURL: String
     let accessToken: String?
     let refreshToken: String?
     let profileId: String
     let profileToken: String?
     let credentialOwner: CapturedHTTPRequestCredentialOwner
-
-    init(
-        serverURL: String,
-        accessValue: String?,
-        refreshValue value: String?,
-        profileId: String,
-        profileValue otherValue: String?,
-        credentialOwner: CapturedHTTPRequestCredentialOwner
-    ) {
-        self.serverURL = serverURL
-        accessToken = accessValue
-        refreshToken = value
-        self.profileId = profileId
-        profileToken = otherValue
-        self.credentialOwner = credentialOwner
-    }
 }

Then update both construction sites in iosApp/iosApp/Networking/TokenStore.swift to use accessToken:, refreshToken:, and profileToken:.

🤖 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/Networking/HTTPClient.swift` around lines 20 - 43, Remove the
explicit initializer from CapturedHTTPRequestAuth and rely on its synthesized
memberwise initializer, preserving the existing property order and
credentialOwner parameter. Update both construction sites in
TokenStore.captureRequestAuth to use accessToken:, refreshToken:, and
profileToken: labels with matching values.
iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift (1)

826-856: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

availableLibraries: is ignored by the callee.

resolvedPrimaryMenuItems declares its parameter as availableLibraries _: [Library] = [] and never reads it (iosApp/iosApp/Navigation/UICustomizationPreferences.swift Lines 953-976). The gating here works only because availableRoot(for:) and the .library arm re-check libraries. Passing the argument implies the store filters, which it does not. Either drop the argument at this call site or implement the filtering in the store so both platforms share one decision.

🤖 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/Navigation/TVMainTabView.swift` around lines 826 - 856,
Update the visibleRoots property’s resolvedPrimaryMenuItems call to stop passing
the misleading availableLibraries argument, since resolvedPrimaryMenuItems does
not use it. Keep the existing availability checks in availableRoot(for:) and the
.library case unchanged.
iosApp/iosApp/ContentView.swift (1)

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

Downloads is appended after the projected menu, so an authored position is ignored.

projectedMainTabDestinations cannot produce .app(.downloads), so the !destinations.contains check never suppresses the append. The Downloads tab therefore always lands last, even when the user orders the menu. This is acceptable for now, but the contains-check is dead code and hides that intent.

🤖 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/ContentView.swift` around lines 1061 - 1075, Update
visibleDestinations so the Downloads append no longer performs the unreachable
destinations.contains check, while preserving the existing
DownloadManager.shared.downloadsEnabled guard and trailing placement. Keep
projectedMainTabDestinations ordering unchanged and make the fallback-only
intent explicit.
iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryPillRow.swift (1)

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

Consider moving these cross-platform helpers out of the tvOS folder, and drop the unused parameter.

Two points on this segment:

  1. The doc comment states the policy is kept pure so the cross-platform unit-test target can compile it. tvCustomizationMutationIsEnabled and resolvedLibraryRootPill are therefore no longer tvOS-only code, but they live under iosApp/iosApp/tvOS/. Moving the pure policy functions to a shared folder keeps the platform folders meaningful.
  2. When isDirectLibraryShortcut is true, categorySelection is never read. shortcutPillSelection in iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift (Lines 902-906) still computes pillSelections[categoryType] ?? .recommended for that call, and it also has to pass categoryType through only for that dead argument. Two focused functions, or an enum parameter, remove the dead path.

As per coding guidelines: "Keep platform-specific Swift code under the existing iOS, tvOS, or macOS folders."

🤖 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/Libraries/TVLibraryPillRow.swift` around lines 65
- 76, Move the pure policy helpers tvCustomizationMutationIsEnabled and
resolvedLibraryRootPill from the tvOS folder into the shared location used by
the cross-platform unit tests, while keeping platform-specific code in its
existing platform folders. Refactor resolvedLibraryRootPill to remove the unused
categorySelection parameter when handling direct-library shortcuts, and update
shortcutPillSelection plus all call sites to stop computing and passing that
dead value while preserving the existing recommended fallback.

Source: Coding guidelines

iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift (2)

4-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Share the customization-editor support logic between the iOS and tvOS editors. The two editors duplicate four pieces of the same contract: the library-shortcut predicate, the library-authority snapshot plumbing, the library sort, and the menu weave that preserves non-renderable synced entries. The root cause is that the iOS helper sits inside #if !os(tvOS), so the tvOS editor cannot reuse it and reimplements each rule. The weave in particular encodes a cross-client rule — section and collection entries must survive an unrelated reorder — and two copies of that rule will diverge.

  • iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift#L4-L13: move availablePrimaryMenuLibraryShortcuts out of the #if !os(tvOS) block into a platform-neutral file so both editors call it.
  • iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift#L390-L397: replace the inline predicate in availableLibraryShortcuts with a call to the shared availablePrimaryMenuLibraryShortcuts.
  • iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift#L327-L349: extract persistVisibleDestinations and librarySort into the shared helper, together with currentLibraryAuthority, libraries, and refreshLibraries from lines 251-274.
  • iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift#L484-L510: replace persistVisibleItems and librarySort with the shared helper, and replace the identical currentLibraryAuthority, libraries, and refreshLibraries at lines 219-242.
🤖 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/Settings/InterfaceCustomizationView.swift` around lines
4 - 13, Share the customization-editor contract through a platform-neutral
helper: in iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift lines
4-13, move availablePrimaryMenuLibraryShortcuts outside the iOS-only block; in
iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift lines 390-397,
replace availableLibraryShortcuts’ inline predicate with that helper. Extract
persistVisibleDestinations, librarySort, currentLibraryAuthority, libraries, and
refreshLibraries from InterfaceCustomizationView.swift lines 251-274 and 327-349
into the shared helper, then replace the corresponding persistVisibleItems,
librarySort, currentLibraryAuthority, libraries, and refreshLibraries
implementations in TVGeneralSettingsView.swift lines 219-242 and 484-510 with
the shared logic, preserving non-renderable synced entries during weaving.

351-367: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Model AppleDeviceIdentity.clientFamily as a typed enum.

The Apple producer uses mobile, tablet, desktop, and tv. Define an enum with these raw values, return enum cases from AppleDeviceIdentity, and switch exhaustively in InterfaceCustomizationView. Keep wire-facing fields as String; the server contract also accepts web.

🤖 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/Settings/InterfaceCustomizationView.swift` around lines
351 - 367, Introduce a typed enum for AppleDeviceIdentity.clientFamily with raw
values mobile, tablet, desktop, and tv, while retaining String types for
wire-facing fields and allowing the server’s web value. Update
AppleDeviceIdentity to return enum cases and revise familyLabel and
familySettingsName in InterfaceCustomizationView to switch exhaustively,
including tv.
iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift (1)

554-576: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add a focusable dismiss control for the read-only picker.

The focus guards are correct. .disabled(!allowsSelection) makes every TVSettingsPickerOptionRow non-focusable, and the guards at lines 554, 562, 585, and 606 stop focusedOptionID from being driven into that disabled subtree. Without the guard at line 585 the sheet would loop: the assignment would be rejected, focusedOptionID would return to nil, and .onChange would set it again.

The remaining gap is that the sheet then has no focusable control. dismiss() is called only from the row select action at line 545, which is unreachable while selection is disabled, so dismissal depends on the implicit Menu gesture for fullScreenCover. The disabled ScrollViewReader also blocks scrolling, so a long option list cannot be inspected in read-only mode.

TVMenuCustomizationSheet in iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift at line 344 adds an explicit Button("Done") for this reason. Apply the same pattern here, and move .disabled(!allowsSelection) from the ScrollViewReader to the option rows so scrolling still works.

As per coding guidelines: "For tvOS focus work, prefer a stable native focus graph or a single composite focus owner".

🤖 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
554 - 576, Update the picker sheet’s view containing the ScrollViewReader and
TVSettingsPickerOptionRow elements to add an explicit focusable “Done” Button
that calls dismiss(), following the pattern used by TVMenuCustomizationSheet.
Remove .disabled(!allowsSelection) from the ScrollViewReader and apply it to the
option rows instead, preserving the existing focus guards while allowing
read-only lists to scroll and providing a reachable dismissal control.

Source: Coding guidelines

iosApp/iosApp/tvOS/Navigation/TVTopMenuBar.swift (1)

333-357: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Define the center-lane inset and center short root lists.

Replace the hardcoded 150 inset with a named ContinuumTheme.Skyline constant. When the root content is narrower than the viewport, make the inner container fill the viewport and center its content; the current ScrollView leading-aligns it.

🤖 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/Navigation/TVTopMenuBar.swift` around lines 333 - 357,
Replace the hardcoded horizontal padding with the appropriate named inset
constant from ContinuumTheme.Skyline. Update the inner root-list container
around the ScrollView/HStack so content shorter than the available viewport
expands to the viewport width and centers its contents, while preserving
horizontal scrolling for longer root lists.
🤖 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/Components/MediaCard.swift`:
- Line 38: Update episodeRailAccessibilityLabel so the season label uses
“Specials” when seasonNumber is 0, matching the mapping in TVDetailHero, while
preserving the existing season/episode format for regular episodes. Apply this
shared helper behavior for both phone and tvOS episode rails.

In `@iosApp/iosApp/Navigation/UICustomizationPreferences.swift`:
- Around line 756-777: Isolate the reconciliation logic for .navPrimaryMenu,
.navShortcuts, and .uiCardPresentation into independent decode/error-handling
boundaries so one malformed or unknown value cannot prevent the remaining keys
from reconciling or the final clearReconciledSyncErrors() and saveCache(for:)
calls. In the primary-menu branch, decode and validate row.value before
assigning storedPrimaryMenuSource, and preserve the prior value only when that
key’s decode fails; report each key-specific failure through the existing
error-reporting mechanism without aborting the overall reconciliation.

In `@iosApp/iosApp/Networking/ContinuumAPI`+Settings.swift:
- Around line 79-80: Update the putValue documentation comment to reference the
renamed getEffectiveValues(keys:libraryIds:seriesIds:profileId:requestIdentity:)
symbol, replacing the outdated link that omits requestIdentity while preserving
the existing documentation context.

In `@iosApp/iosApp/Networking/HTTPClient.swift`:
- Around line 814-847: Update performScopedRefresh and the surrounding
refresh-flight handling to route terminal scoped refresh failures through the
same token-clearing, expiry-notification, and ConnectionMonitor failure paths
used by ordinary flights, while retaining each flow’s existing token-save
method. Ensure ordinary requests joining a failed scoped flight receive the
shared refresh failure instead of a generic error, and add coverage for this
joined-flight scenario.

In `@iosApp/iosApp/Screens/Browse/LibrariesTabView.swift`:
- Around line 272-280: Update the selection persistence around
resolvedLibraryIdForRoot and the picker sheet’s storedLibraryId write so only
the aggregate root (category == nil) updates the shared AppStorage value;
category-specific roots must keep their selection local without overwriting
storedLibraryId.

In `@iosApp/iosApp/Shared/AppleDeviceIdentity.swift`:
- Around line 19-24: Update AppleDeviceIdentity.init to require a non-optional
explicit clientFamily by removing its default value and fallback to
defaultClientFamily(for:). Update all affected test initializers to pass
"mobile" for the iPhone fixtures, preserving correct profile_client scope
resolution.

In `@iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift`:
- Around line 250-255: Update the visibleRoots change handling near the
primaryMenu and shortcuts onChange callbacks to capture focus ownership before
calling closePanel(), then explicitly increment contentFocusRequest or re-arm
the TVTopMenuBar focus as appropriate after the menu update. Do not determine
ownership after closePanel(), since it may already re-arm the bar; preserve
ensureSelectedRootIsVisible() for selecting visible roots.

In `@iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift`:
- Around line 128-130: Update visibleMenuCount and
TVMenuCustomizationSheet.visibleItems to share a static filtering helper that
removes unavailable-library items plus .section and .collection entries; count
the helper’s filtered result for the “Customize Top Menu” label so it matches
the rows rendered by the sheet.

---

Nitpick comments:
In `@iosApp/iosApp/ContentView.swift`:
- Around line 1061-1075: Update visibleDestinations so the Downloads append no
longer performs the unreachable destinations.contains check, while preserving
the existing DownloadManager.shared.downloadsEnabled guard and trailing
placement. Keep projectedMainTabDestinations ordering unchanged and make the
fallback-only intent explicit.

In `@iosApp/iosApp/Networking/AuthTokenModels.swift`:
- Around line 45-55: Remove both explicit initializers from RefreshRequest so
its synthesized memberwise initializer remains available with the refreshToken
label. Update HTTPClient.performScopedRefresh to construct RefreshRequest using
the labeled refreshToken argument instead of the unlabeled call.

In `@iosApp/iosApp/Networking/HTTPClient.swift`:
- Around line 20-43: Remove the explicit initializer from
CapturedHTTPRequestAuth and rely on its synthesized memberwise initializer,
preserving the existing property order and credentialOwner parameter. Update
both construction sites in TokenStore.captureRequestAuth to use accessToken:,
refreshToken:, and profileToken: labels with matching values.

In `@iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift`:
- Around line 4-13: Share the customization-editor contract through a
platform-neutral helper: in
iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift lines 4-13, move
availablePrimaryMenuLibraryShortcuts outside the iOS-only block; in
iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift lines 390-397,
replace availableLibraryShortcuts’ inline predicate with that helper. Extract
persistVisibleDestinations, librarySort, currentLibraryAuthority, libraries, and
refreshLibraries from InterfaceCustomizationView.swift lines 251-274 and 327-349
into the shared helper, then replace the corresponding persistVisibleItems,
librarySort, currentLibraryAuthority, libraries, and refreshLibraries
implementations in TVGeneralSettingsView.swift lines 219-242 and 484-510 with
the shared logic, preserving non-renderable synced entries during weaving.
- Around line 351-367: Introduce a typed enum for
AppleDeviceIdentity.clientFamily with raw values mobile, tablet, desktop, and
tv, while retaining String types for wire-facing fields and allowing the
server’s web value. Update AppleDeviceIdentity to return enum cases and revise
familyLabel and familySettingsName in InterfaceCustomizationView to switch
exhaustively, including tv.

In `@iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift`:
- Around line 826-856: Update the visibleRoots property’s
resolvedPrimaryMenuItems call to stop passing the misleading availableLibraries
argument, since resolvedPrimaryMenuItems does not use it. Keep the existing
availability checks in availableRoot(for:) and the .library case unchanged.

In `@iosApp/iosApp/tvOS/Navigation/TVTopMenuBar.swift`:
- Around line 333-357: Replace the hardcoded horizontal padding with the
appropriate named inset constant from ContinuumTheme.Skyline. Update the inner
root-list container around the ScrollView/HStack so content shorter than the
available viewport expands to the viewport width and centers its contents, while
preserving horizontal scrolling for longer root lists.

In `@iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryPillRow.swift`:
- Around line 65-76: Move the pure policy helpers
tvCustomizationMutationIsEnabled and resolvedLibraryRootPill from the tvOS
folder into the shared location used by the cross-platform unit tests, while
keeping platform-specific code in its existing platform folders. Refactor
resolvedLibraryRootPill to remove the unused categorySelection parameter when
handling direct-library shortcuts, and update shortcutPillSelection plus all
call sites to stop computing and passing that dead value while preserving the
existing recommended fallback.

In `@iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift`:
- Around line 554-576: Update the picker sheet’s view containing the
ScrollViewReader and TVSettingsPickerOptionRow elements to add an explicit
focusable “Done” Button that calls dismiss(), following the pattern used by
TVMenuCustomizationSheet. Remove .disabled(!allowsSelection) from the
ScrollViewReader and apply it to the option rows instead, preserving the
existing focus guards while allowing read-only lists to scroll and providing a
reachable dismissal control.

In `@iosApp/Tests/SettingsContractResolve.swift`:
- Around line 358-361: Hoist the client-family vocabulary used by the
profileClient resolution case into a named file-level constant, then reuse that
constant in the per-row filter instead of the inline array. Preserve the
existing equality checks and fail-closed behavior for unrecognized families.

In `@iosApp/Tests/SettingValuesAPITests.swift`:
- Around line 746-850: Update
testScopedRefreshRejectsChangedServerAccountAndTemporaryScope to wrap each of
its four rejection scenarios—changed server URL, stale refresh value, temporary
credential provenance, and cross-server write—in a separately named
XCTContext.runActivity block, preserving the existing setup and assertions.

In `@iosApp/Tests/UICustomizationPreferencesTests.swift`:
- Around line 711-713: In UICustomizationPreferencesTests, add the proposed
MainActor waitUntil polling helper and replace the fixed Task.sleep calls at the
affected assertion-side sites with condition-based polling, preserving each
existing assertion. Keep the intentional gated-write sleep at line 708
unchanged, and use the existing transport/store state predicates to wait until
quiescence rather than relying on fixed timing.
🪄 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: 8ad90da0-1e3f-46b1-bb7d-965eec7353c3

📥 Commits

Reviewing files that changed from the base of the PR and between bacdc2f and df12e5c.

⛔ Files ignored due to path filters (1)
  • iosApp/iosApp/Networking/SettingKeys.generated.swift is excluded by !**/*.generated.*
📒 Files selected for processing (50)
  • iosApp/Tests/Fixtures/SettingsContract/SOURCE
  • iosApp/Tests/Fixtures/SettingsContract/conformance.json
  • iosApp/Tests/Fixtures/SettingsContract/manifest.json
  • iosApp/Tests/SettingValuesAPITests.swift
  • iosApp/Tests/SettingsConformanceTests.swift
  • iosApp/Tests/SettingsContractResolve.swift
  • iosApp/Tests/UICustomizationPreferencesTests.swift
  • iosApp/iosApp/Components/AdaptiveLayout.swift
  • iosApp/iosApp/Components/EpisodeThumbCard.swift
  • iosApp/iosApp/Components/ErrorState.swift
  • iosApp/iosApp/Components/MediaCard.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Downloads/DownloadSessionDelegate.swift
  • iosApp/iosApp/Navigation/UICustomizationPreferences.swift
  • iosApp/iosApp/Networking/AuthTokenModels.swift
  • iosApp/iosApp/Networking/ContinuumAPI+Settings.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Networking/SettingValueModels.swift
  • iosApp/iosApp/Networking/TokenStore.swift
  • iosApp/iosApp/Pairing/PairingDeviceAPI.swift
  • iosApp/iosApp/Screens/Browse/CatalogGrid.swift
  • iosApp/iosApp/Screens/Browse/LibrariesTabView.swift
  • iosApp/iosApp/Screens/Calendar/CalendarEventCard.swift
  • iosApp/iosApp/Screens/Collections/CollectionDetailView.swift
  • iosApp/iosApp/Screens/Collections/CollectionsView.swift
  • iosApp/iosApp/Screens/Detail/AudiobookDetailContent.swift
  • iosApp/iosApp/Screens/Detail/Phone/PhoneEpisodeRail.swift
  • iosApp/iosApp/Screens/Detail/Phone/PhoneSimilarRail.swift
  • iosApp/iosApp/Screens/Home/Feed/HomeFeedKit.swift
  • iosApp/iosApp/Screens/Home/Feed/HomeFeedRow.swift
  • iosApp/iosApp/Screens/Personal/FavoritesView.swift
  • iosApp/iosApp/Screens/Personal/WatchlistView.swift
  • iosApp/iosApp/Screens/Requests/Components/RequestMediaCard.swift
  • iosApp/iosApp/Screens/Requests/Hub/RequestsHubView.swift
  • iosApp/iosApp/Screens/Settings/InterfaceCustomizationView.swift
  • iosApp/iosApp/Screens/Settings/ProfilePrefsEditor.swift
  • iosApp/iosApp/Screens/Settings/SettingsView.swift
  • iosApp/iosApp/Shared/AppleDeviceIdentity.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift
  • iosApp/iosApp/tvOS/Navigation/TVCascadeSelector.swift
  • iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift
  • iosApp/iosApp/tvOS/Navigation/TVTopMenuBar.swift
  • iosApp/iosApp/tvOS/Screens/Components/TVCatalogGrid.swift
  • iosApp/iosApp/tvOS/Screens/Components/TVCollectionPosterCard.swift
  • iosApp/iosApp/tvOS/Screens/Components/TVMediaCard.swift
  • iosApp/iosApp/tvOS/Screens/Detail/TVEpisodeRail.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryCollectionsView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryPillRow.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.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: 113bdcace4

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

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

Caution

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

⚠️ Outside diff range comments (2)
iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift (1)

419-427: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Include wildcard patterns for libraryShortcut associated values. Replace both .root(.libraryShortcut) patterns with .root(.libraryShortcut(_, _)); the current patterns do not compile.

🤖 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/Navigation/TVMainTabView.swift` around lines 419 - 427,
Update the panel matching in panelIntrinsicWidth(for:) so every
.root(.libraryShortcut) pattern includes both associated-value wildcards as
.root(.libraryShortcut(_, _)), including both occurrences, while preserving the
existing width behavior.
iosApp/iosApp/Screens/Auth/AuthService.swift (1)

104-117: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Broken Authentication (CWE-362): Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')

Reachability: External · Exploitability: Difficult

Reachability path
● Entry
  iosApp/iosApp/ContentView.swift:895
  resolvedRequestedMainTabDestination
│
▼
● Hop
  iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift:870
  libraries
│
▼
● Hop
  iosApp/iosApp/Networking/ServerRegistry.swift:213
  commitSwitchTo: if os(iOS) || os(tvOS)
│
▼
● Sink
  iosApp/iosApp/Screens/Auth/AuthService.swift

Fail checkServer when server activation does not commit.

switchTo(serverId:) can exit without changing the active server. checkServer ignores this and returns the candidate status. The following authentication flow can then send credentials to the previous server and store its session in the previous server’s slot. Return Bool from switchTo and throw HTTPError.requestIdentityChanged when it returns false.

🤖 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/Auth/AuthService.swift` around lines 104 - 117, Update
ServerRegistry.switchTo(serverId:) to return a Bool indicating whether
activation committed, then in checkServer validate that result after requesting
the candidate server; throw HTTPError.requestIdentityChanged when it returns
false instead of returning the candidate status. Preserve the existing success
path when the active server is already or becomes the requested id.
🧹 Nitpick comments (11)
iosApp/iosApp/Networking/TokenStore.swift (1)

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

Remove the redundant memberwise initializer.

RefreshAccountIdentity declares an initializer that matches the synthesized memberwise initializer exactly: same parameters, same order, no defaults. Swift generates it automatically. TemporaryAuthScope's initializer at lines 66-86 is different, because it supplies a default for credentialGenerationID, so keep that one.

♻️ Proposed change
     let credentialGenerationID: UUID
-
-    init(
-        serverId: String,
-        serverURL: String,
-        credentialGenerationID: UUID
-    ) {
-        self.serverId = serverId
-        self.serverURL = serverURL
-        self.credentialGenerationID = credentialGenerationID
-    }
 }
🤖 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/Networking/TokenStore.swift` around lines 11 - 19, Remove the
explicit memberwise initializer for RefreshAccountIdentity, since Swift
synthesizes the identical initializer automatically. Keep TemporaryAuthScope’s
initializer unchanged because it provides a default credentialGenerationID.

Source: Linters/SAST tools

iosApp/iosApp/Screens/Auth/QRLoginViewModel.swift (2)

136-139: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

A cancelled installSession keeps polling.

installSession throws CancellationError() when the identity transition is denied or the task is cancelled. That error reaches the generic catch at line 136, which treats it as a transient network failure and keeps polling. The next poll usually returns consumed, so the user sees "This code has already been used." rather than a cancellation. Consider catching CancellationError explicitly and finalizing with a retry-oriented message.

🤖 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/Auth/QRLoginViewModel.swift` around lines 136 - 139,
Update the polling error handling around installSession to catch
CancellationError separately from transient failures. Finalize the session with
a retry-oriented cancellation message instead of continuing to poll, while
preserving the existing generic catch behavior for other errors.

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

Separate the missing-identity case from the missing-token message.

The guard now also fails when expectedAccount is nil, but the message still reads "Server approved the session but did not return tokens." That text describes a server response problem, not a lost client identity. Split the conditions so each state gets its own message.

♻️ Proposed change
                 guard let accessToken = response.accessToken,
-                      let refreshToken = response.refreshToken,
-                      let expectedAccount else {
+                      let refreshToken = response.refreshToken else {
                     finalize(.error(message: "Server approved the session but did not return tokens."))
                     return
                 }
+                guard let expectedAccount else {
+                    finalize(.error(message: "The active server changed during sign-in. Please try again."))
+                    return
+                }
🤖 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/Auth/QRLoginViewModel.swift` around lines 110 - 115,
Update the guard in the QR login response handling to validate
accessToken/refreshToken separately from expectedAccount. Keep the existing
missing-token error for absent server tokens, and add a distinct error path and
message for a nil expectedAccount before continuing the successful login flow.
iosApp/Tests/SettingValuesAPITests.swift (2)

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

Confirm the double release of the mixed refresh is intentional.

Line 755 registers releaseMixedRefresh() in a defer, and line 759 calls it directly. The second call finds pendingMixedRefresh already nil and returns, so the behavior is safe. The defer only matters when the wait at line 756 fails. A short comment would make that intent explicit for future readers.

🤖 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/SettingValuesAPITests.swift` around lines 755 - 759, Add a
concise comment around the defer and direct releaseMixedRefresh calls in the
mixed-refresh test to clarify that the direct call handles the successful path
while the deferred call cleans up when waitForCounter fails. Preserve the
existing release behavior and control flow.

1662-1681: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Restore ConnectionMonitor state from a teardown block.

ConnectionMonitor.shared is process-wide state. If getUnauthenticated throws at line 1667, the reset at line 1680 never runs and the monitor stays .unreachable for later tests in the same process. Register the restore as a teardown block so it runs on every exit path.

♻️ Proposed change
         let harness = try await makeRefreshHarness(testName: "CandidateReachabilityIsolation")
+        addTeardownBlock {
+            await MainActor.run { ConnectionMonitor.shared.noteServerResponded() }
+        }
         await MainActor.run { ConnectionMonitor.shared.noteServerUnreachable() }
@@
         XCTAssertTrue(
             activeStillUnreachable,
             "a candidate response must not mark the unrelated active server healthy"
         )
-        await MainActor.run { ConnectionMonitor.shared.noteServerResponded() }
     }
🤖 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/SettingValuesAPITests.swift` around lines 1662 - 1681, Update
testCandidateProbeDoesNotChangeActiveServerReachability to register restoration
of ConnectionMonitor.shared via the test teardown mechanism immediately after
marking it unreachable, ensuring noteServerResponded() runs even when
harness.http.getUnauthenticated throws. Remove the inline cleanup call or
otherwise avoid duplicate restoration while preserving the test’s assertions.
iosApp/Tests/UICustomizationPreferencesTests.swift (2)

2581-2582: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bound the isSaving spin loops with a deadline.

while preferences.isSaving { await Task.yield() } never terminates if a write stalls. The test then hangs instead of failing, which blocks the whole suite. Add a deadline-based helper that fails the test when saving does not finish.

♻️ Proposed helper
private func waitUntilNotSaving(
    _ preferences: UICustomizationPreferences,
    timeout: Duration = .seconds(2)
) async -> Bool {
    let deadline = ContinuousClock.now + timeout
    while ContinuousClock.now < deadline {
        if !preferences.isSaving { return true }
        await Task.yield()
    }
    return false
}
         preferences.useFamilySettings()
-        while preferences.isSaving { await Task.yield() }
+        guard await waitUntilNotSaving(preferences) else {
+            return XCTFail("device-override deletes did not finish saving")
+        }

Also applies to: 2641-2642

🤖 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/UICustomizationPreferencesTests.swift` around lines 2581 - 2582,
Replace the unbounded isSaving spin loops in the affected tests with a shared
deadline-based waitUntilNotSaving helper. Have the helper poll until saving
completes or the timeout expires, and make each test assert the returned success
value so stalled writes fail the test instead of hanging.

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

Make the targeted-read detection explicit.

DeviceOverrideDeleteProbe.effectiveValues treats any single-key request as a targeted read. If Self.keys ever shrinks to one key, a full refresh would be recorded as a targeted read and the assertions at lines 2597 and 2667 would silently change meaning. Compare against the customization key set instead of relying on keys.count == 1.

🤖 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/UICustomizationPreferencesTests.swift` around lines 3276 - 3297,
Update DeviceOverrideDeleteProbe.effectiveValues so targeted-read tracking is
triggered only when the requested single key is distinct from the full
customization key set, rather than solely when keys.count == 1. Preserve the
existing targetedReadKeys and targetedReadFailureKey behavior, while ensuring a
full refresh remains unclassified as targeted if Self.keys contains one key.
iosApp/iosApp/Control/tvOS/RemotePlaybackIdentityManager.swift (1)

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

prepare reports every activation failure as cancellation.

activate returns false for cancellation and also when another activation already holds activationGenerationPending or when the previous owners are misaligned. Throwing CancellationError() for all of these hides a real conflict from the phone, which receives a generic cancellation. Consider a distinct HandoffError case for the non-cancellation branch so the peer can distinguish "superseded by another handoff" from "cancelled".

🤖 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/Control/tvOS/RemotePlaybackIdentityManager.swift` around lines
131 - 146, Update the activation failure handling in prepare around activate to
distinguish cancellation from non-cancellation failures. Preserve
CancellationError for an actual cancellation, but throw the appropriate distinct
HandoffError case when activation is rejected because another activation is
pending or previous owners are misaligned, allowing the peer to distinguish
superseded handoffs from cancellation.
iosApp/iosApp/Networking/ServerRegistry.swift (1)

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

Extract the lease-release-and-return boilerplate.

switchTo and remove repeat await HTTPClient.shared.endIdentityTransition(transitionLease); return on six early-exit paths. RemotePlaybackIdentityManager already solved this with releaseIdentityTransition(_:returning:). A small equivalent helper here removes the duplication and makes a missed release impossible.

♻️ Proposed helper
private func releaseIdentityTransition<T>(
    _ lease: HTTPIdentityTransitionLease,
    returning result: T
) async -> T {
    await HTTPClient.shared.endIdentityTransition(lease)
    return result
}

Also applies to: 306-339

🤖 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/Networking/ServerRegistry.swift` around lines 171 - 189,
Extract a private generic async helper near the ServerRegistry transition
methods, equivalent to releaseIdentityTransition(_:returning:), that ends the
lease before returning a supplied result. Replace the repeated
endIdentityTransition(transitionLease) plus return paths in switchTo and remove
with this helper, preserving each path’s existing return value and ensuring
every early exit releases its lease.
iosApp/iosApp/Shared/AppleDeviceIdentity.swift (1)

19-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Delete the redundant memberwise initializer.

Every parameter label matches its property name, and no parameter has a default value. Swift synthesizes exactly this initializer for an internal struct with these four stored properties. SwiftLint flags it as unneeded_synthesized_initializer.

Removing it keeps AppleDeviceIdentity.current at Lines 26-31 and the test fixture in iosApp/Tests/MetricKitCaptureTests.swift compiling unchanged, and it preserves the required explicit clientFamily argument.

♻️ Proposed refactor
     let clientFamily: String
 
-    init(id: String, name: String, platform: String, clientFamily: String) {
-        self.id = id
-        self.name = name
-        self.platform = platform
-        self.clientFamily = clientFamily
-    }
-
     static let current = AppleDeviceIdentity(
🤖 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/Shared/AppleDeviceIdentity.swift` around lines 19 - 24, Remove
the explicit memberwise initializer from AppleDeviceIdentity; Swift will
synthesize the same internal initializer for its stored properties, preserving
existing AppleDeviceIdentity.current and test fixture calls with the required
clientFamily argument.

Source: Linters/SAST tools

iosApp/iosApp/Networking/HTTPClient.swift (1)

1010-1015: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared X-Silo-* device-header block.

Three functions now assemble the same device headers: attachLegacyAuthHeaders (Lines 1010-1015), attachOrdinaryAuthHeaders (Lines 1046-1051), and attachCapturedAuthHeaders (Lines 1071-1075). This PR added X-Silo-Client-Family to each copy. A future header addition must be applied in three places, and one miss changes request identity for only some paths.

Extract one helper and call it from all three. The credential attachment and the debug log stay per-path.

♻️ Proposed refactor
+    private static func attachDeviceHeaders(_ request: inout URLRequest) -> String {
+        let device = AppleDeviceIdentity.current
+        request.setValue(device.id, forHTTPHeaderField: "X-Silo-Device-Id")
+        request.setValue(device.name, forHTTPHeaderField: "X-Silo-Device-Name")
+        request.setValue(device.platform, forHTTPHeaderField: "X-Silo-Device-Platform")
+        request.setValue(device.clientFamily, forHTTPHeaderField: "X-Silo-Client-Family")
+        return "device=\(device.platform)/\(device.clientFamily)"
+    }

Then, in each of the three functions:

-        let device = AppleDeviceIdentity.current
-        request.setValue(device.id, forHTTPHeaderField: "X-Silo-Device-Id")
-        request.setValue(device.name, forHTTPHeaderField: "X-Silo-Device-Name")
-        request.setValue(device.platform, forHTTPHeaderField: "X-Silo-Device-Platform")
-        request.setValue(device.clientFamily, forHTTPHeaderField: "X-Silo-Client-Family")
-        attached.append("device=\(device.platform)/\(device.clientFamily)")
+        attached.append(Self.attachDeviceHeaders(&request))

Also applies to: 1046-1055

🤖 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/Networking/HTTPClient.swift` around lines 1010 - 1015, Extract
the duplicated X-Silo device-header setup from attachLegacyAuthHeaders,
attachOrdinaryAuthHeaders, and attachCapturedAuthHeaders into one shared helper,
and invoke that helper from all three functions. Keep each function’s credential
attachment and attached debug logging path-specific, while preserving the
existing device values and header names.
🤖 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/Control/tvOS/RemotePlaybackIdentityManager.swift`:
- Around line 221-230: Update TokenStore’s
endTemporaryScope(expectedGenerationID:) classification so an absent ending
generation atomically clears activeIdentity, while a different current
generation preserves it. Ensure RemotePlaybackIdentityManager.end() still
distinguishes these outcomes and clears activeIdentity only when teardown
confirms the ending scope or the absent-scope case.

In `@iosApp/iosApp/Screens/Auth/AuthService.swift`:
- Around line 300-312: Update AuthService.signOut() to return Bool, preserving a
true result for completed sign-outs and returning false when persistent sign-out
is refused because the captured auth is temporary or belongs to another server.
When activeServerId is set but captureOrdinaryRequestAuth() returns nil, clear
the local authentication state instead of returning early. Update callers,
including the AppRouter sign-out flows, to handle the result and respond
appropriately when sign-out is refused.

---

Outside diff comments:
In `@iosApp/iosApp/Screens/Auth/AuthService.swift`:
- Around line 104-117: Update ServerRegistry.switchTo(serverId:) to return a
Bool indicating whether activation committed, then in checkServer validate that
result after requesting the candidate server; throw
HTTPError.requestIdentityChanged when it returns false instead of returning the
candidate status. Preserve the existing success path when the active server is
already or becomes the requested id.

In `@iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift`:
- Around line 419-427: Update the panel matching in panelIntrinsicWidth(for:) so
every .root(.libraryShortcut) pattern includes both associated-value wildcards
as .root(.libraryShortcut(_, _)), including both occurrences, while preserving
the existing width behavior.

---

Nitpick comments:
In `@iosApp/iosApp/Control/tvOS/RemotePlaybackIdentityManager.swift`:
- Around line 131-146: Update the activation failure handling in prepare around
activate to distinguish cancellation from non-cancellation failures. Preserve
CancellationError for an actual cancellation, but throw the appropriate distinct
HandoffError case when activation is rejected because another activation is
pending or previous owners are misaligned, allowing the peer to distinguish
superseded handoffs from cancellation.

In `@iosApp/iosApp/Networking/HTTPClient.swift`:
- Around line 1010-1015: Extract the duplicated X-Silo device-header setup from
attachLegacyAuthHeaders, attachOrdinaryAuthHeaders, and
attachCapturedAuthHeaders into one shared helper, and invoke that helper from
all three functions. Keep each function’s credential attachment and attached
debug logging path-specific, while preserving the existing device values and
header names.

In `@iosApp/iosApp/Networking/ServerRegistry.swift`:
- Around line 171-189: Extract a private generic async helper near the
ServerRegistry transition methods, equivalent to
releaseIdentityTransition(_:returning:), that ends the lease before returning a
supplied result. Replace the repeated endIdentityTransition(transitionLease)
plus return paths in switchTo and remove with this helper, preserving each
path’s existing return value and ensuring every early exit releases its lease.

In `@iosApp/iosApp/Networking/TokenStore.swift`:
- Around line 11-19: Remove the explicit memberwise initializer for
RefreshAccountIdentity, since Swift synthesizes the identical initializer
automatically. Keep TemporaryAuthScope’s initializer unchanged because it
provides a default credentialGenerationID.

In `@iosApp/iosApp/Screens/Auth/QRLoginViewModel.swift`:
- Around line 136-139: Update the polling error handling around installSession
to catch CancellationError separately from transient failures. Finalize the
session with a retry-oriented cancellation message instead of continuing to
poll, while preserving the existing generic catch behavior for other errors.
- Around line 110-115: Update the guard in the QR login response handling to
validate accessToken/refreshToken separately from expectedAccount. Keep the
existing missing-token error for absent server tokens, and add a distinct error
path and message for a nil expectedAccount before continuing the successful
login flow.

In `@iosApp/iosApp/Shared/AppleDeviceIdentity.swift`:
- Around line 19-24: Remove the explicit memberwise initializer from
AppleDeviceIdentity; Swift will synthesize the same internal initializer for its
stored properties, preserving existing AppleDeviceIdentity.current and test
fixture calls with the required clientFamily argument.

In `@iosApp/Tests/SettingValuesAPITests.swift`:
- Around line 755-759: Add a concise comment around the defer and direct
releaseMixedRefresh calls in the mixed-refresh test to clarify that the direct
call handles the successful path while the deferred call cleans up when
waitForCounter fails. Preserve the existing release behavior and control flow.
- Around line 1662-1681: Update
testCandidateProbeDoesNotChangeActiveServerReachability to register restoration
of ConnectionMonitor.shared via the test teardown mechanism immediately after
marking it unreachable, ensuring noteServerResponded() runs even when
harness.http.getUnauthenticated throws. Remove the inline cleanup call or
otherwise avoid duplicate restoration while preserving the test’s assertions.

In `@iosApp/Tests/UICustomizationPreferencesTests.swift`:
- Around line 2581-2582: Replace the unbounded isSaving spin loops in the
affected tests with a shared deadline-based waitUntilNotSaving helper. Have the
helper poll until saving completes or the timeout expires, and make each test
assert the returned success value so stalled writes fail the test instead of
hanging.
- Around line 3276-3297: Update DeviceOverrideDeleteProbe.effectiveValues so
targeted-read tracking is triggered only when the requested single key is
distinct from the full customization key set, rather than solely when keys.count
== 1. Preserve the existing targetedReadKeys and targetedReadFailureKey
behavior, while ensuring a full refresh remains unclassified as targeted if
Self.keys contains one key.
🪄 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: dc2be6c6-f48b-43df-948e-b5caceffd114

📥 Commits

Reviewing files that changed from the base of the PR and between df12e5c and 113bdca.

📒 Files selected for processing (21)
  • iosApp/Tests/DeviceSnapshotBuilderTests.swift
  • iosApp/Tests/MetricKitCaptureTests.swift
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/Tests/SettingValuesAPITests.swift
  • iosApp/Tests/UICustomizationPreferencesTests.swift
  • iosApp/iosApp/Components/MediaCard.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Control/tvOS/RemotePlaybackIdentityManager.swift
  • iosApp/iosApp/Control/tvOS/TVControlReceiver.swift
  • iosApp/iosApp/Navigation/UICustomizationPreferences.swift
  • iosApp/iosApp/Networking/ContinuumAPI+Settings.swift
  • iosApp/iosApp/Networking/HTTPClient.swift
  • iosApp/iosApp/Networking/ServerRegistry.swift
  • iosApp/iosApp/Networking/TokenStore.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
  • iosApp/iosApp/Screens/Auth/AuthService.swift
  • iosApp/iosApp/Screens/Auth/QRLoginViewModel.swift
  • iosApp/iosApp/Screens/Browse/LibrariesTabView.swift
  • iosApp/iosApp/Shared/AppleDeviceIdentity.swift
  • iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • iosApp/iosApp/tvOS/Screens/Settings/TVGeneralSettingsView.swift
  • iosApp/iosApp/Components/MediaCard.swift
  • iosApp/iosApp/Screens/Browse/LibrariesTabView.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: 26fd42ca52

ℹ️ 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 +327 to +330
guard !Task.isCancelled else {
await HTTPClient.shared.endIdentityTransition(transitionLease)
return
}

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 Reopen the diagnostics gate when removal is cancelled

On iOS/tvOS, if the removal task is cancelled during either diagnostics purge, this early return runs after activeProfileWillChange() has invalidated profile eligibility and disarmed the tvOS exit sentinel, while activeProfileDidChange() is only called after the server-removal commit. Because the active server remains unchanged, no later identity event necessarily re-arms the gate, leaving breadcrumb and crash diagnostics disabled for the rest of the session. Once the gate is closed, either finish the transaction despite cancellation or restore eligibility before releasing the transition lease.

Useful? React with 👍 / 👎.

Comment on lines +987 to +989
.task(id: currentLibraryAuthority) {
await loadVisibleLibraries(for: currentLibraryAuthority)
}

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 Wait for the server transition before loading libraries

When an authenticated server is switched through ServerListView, ServerRegistry publishes the new activeServerId while its identity-transition lease is still held, so this task can call fetchUserLibraries() before request dispatch reopens. HTTPClient then rejects the fetch with requestIdentityChanged; meanwhile loadVisibleLibraries has already cleared the previous-authority snapshot, and the unchanged task ID means it will not retry until a later foreground transition. Profiles with an explicit customized menu consequently lose all category and pinned-library roots immediately after an otherwise successful online server switch. Apply the same waitForRequestDispatchOpen() barrier used by ContentView before starting this load.

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit af9569b into main Aug 4, 2026
1 check passed
@Quick104
Quick104 deleted the codex/ui-customization-apple branch August 4, 2026 14:01
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