Skip to content

Companion pairing: iOS↔tvOS LAN sign-in handoff - #7

Merged
Quick104 merged 50 commits into
mainfrom
feature/companion-pairing
Jun 15, 2026
Merged

Quick104 merged 50 commits into
mainfrom
feature/companion-pairing

Conversation

@Quick104

@Quick104 Quick104 commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds companion pairing — the iOS app discovers a waiting Apple TV on the same Wi-Fi, hands it the server address(es), and approves its sign-in, so the user types no URL and no password on the remote. It rides the server's existing device-authorization endpoints (/auth/device/{start,poll,approve}, GET /auth/device) — no new server endpoints.

Shared transport

  • PairingProtocol — versioned wire messages (platform-neutral; documented so silo-android can mirror it)
  • PairingFrame — length-prefixed JSON codec
  • PairingSession — NWConnection wrapper with TLS (fixed app PSK)
  • PairingDeviceAPI — device-auth calls against an explicit server URL, independent of the app's single active server

tvOS (Receiver)

  • TVPairingAdvertiser — advertises Bonjour _silopair._tcp
  • ReceiverPairingCoordinator — persist-on-success, cancellable poll loop
  • TVPairingReceiverView — wired into the Aurora onboarding "Set up with iPhone" card

iOS (Companion)

  • TVPairingBrowser — LAN discovery
  • CompanionPairingCoordinator — confirm-once, server-authoritative match code, per-server approval
  • SetUpTVBanner (auto-discovery banner mounted on root) + TVPairingView (modal flow)

Security model

  • Tokens never cross the LAN — the server mints + delivers them to the TV over HTTPS
  • The server-authoritative match code (fetched via lookup, shown on both screens) is the trust anchor — resists a channel MITM
  • Persist-on-success: the TV commits a server to its registry only after a successful sign-in
  • TLS uses a fixed in-app PSK = opportunistic confidentiality only (not an auth boundary)
  • Confirm-once multi-server is a documented accepted v1 risk (see spec §6)

Design + plan: docs/superpowers/specs/2026-06-14-companion-pairing-design.md, docs/superpowers/plans/2026-06-14-companion-pairing.md.

Test plan

  • Pure-logic unit tests pass (PairingProtocol round-trip, PairingFrame codec)
  • iOS (Silo) + tvOS (SiloTV) targets build green
  • Two-simulator end-to-end: Bonjour discovery → banner → TLS-PSK connect → handshake → match-code confirm → approve → sign-in (iPhone 17 Pro + Apple TV 4K sims)
  • On-device two-device LAN test: Local Network permission prompt, AWDL/peer-to-peer path, match-code mismatch, multi-server pick, cancel/drop teardown

Follow-ups (not blocking)

  • Add .notice milestone logging across both coordinators + advertiser/browser — the happy path currently logs nothing, and the companion logger is declared-but-unused (hurts on-device debugging)
  • Spec §12 open questions: banner scope across auth states; Local Network usage-description copy
  • Future hardening: SPAKE2/channel binding to remove reliance on the visual match-code compare

Cross-repo

  • silo-server — no new endpoints required; nice-to-have later: surface device name/platform in GET /auth/sessions
  • silo-android — PairingProtocol + the _silopair._tcp Bonjour type are platform-neutral and documented so Android phone↔TV can mirror the flow

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added audiobook playback with chapters, sleep timer, and playback rate controls.
    • Added Calendar tab showing upcoming releases and airings.
    • Added phone-to-Apple TV pairing flow for seamless setup.
    • Redesigned tvOS navigation with new top-bar interface.
  • Improvements

    • Enhanced playback controls and resume functionality for audiobooks.
    • Improved subtitle customization options in settings.
    • Refined media card layouts with square aspect support.
  • Documentation

    • Added comprehensive tvOS redesign specifications and design system documentation.

@coderabbitai

coderabbitai Bot commented Jun 14, 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 Apple-client docs and mockups, companion pairing code for iOS and tvOS, audiobook playback and detail surfaces, a new Calendar tab, tvOS Skyline marquee and focus updates, playback-core robustness changes, FFmpeg vendoring, and settings screen refactors.

Changes

Design, specs, and mockups

Layer / File(s) Summary
Realtime and Skyline design docs
docs/realtime-updates-spec.md, docs/skyline-design-guide.md, docs/skyline-implementation-prompt.md
Documents specify Apple realtime refresh behavior, Skyline navigation rules, focus marquee behavior, and implementation constraints.
Companion pairing plans and specs
docs/superpowers/plans/...companion-pairing*.md, docs/superpowers/specs/...companion-pairing*.md, docs/superpowers/specs/...apple-companion-pairing-implementation-summary.md, docs/superpowers/specs/...android-cross-platform-companion-pairing-design.md
Plans and specs define pairing protocol, transport, discovery, coordinator flows, testing, and the iOS pairing-card design.
Onboarding and redesign mockups
docs/tvos-onboarding/*, docs/tvos-redesign-mockups/*, .superpowers/brainstorm/...
Static assets add onboarding styles/scripts/pages, tvOS redesign mockups, and pairing-card concept HTML.

Apple TV companion pairing and first-run shell

Layer / File(s) Summary
Pairing contracts, transport, and tests
iosApp/iosApp/Pairing/Pairing*.swift, iosApp/iosApp/Networking/DeviceLoginModels.swift, iosApp/iosApp/Networking/TokenStore.swift, iosApp/iosApp/Pairing/PairingDeviceAPI.swift, iosApp/Tests/Pairing*Tests.swift, iosApp/Tests/CompanionDismissalKeyTests.swift, iosApp/iosApp/Info.plist, iosApp/iosApp/tvOS-Info.plist
Adds pairing message contracts, framing, session transport, explicit device-auth API calls, dismissal-key logic, token lookup, tests, and Bonjour/local-network plist entries.
tvOS receiver pairing flow
iosApp/iosApp/Pairing/Receiver/*, iosApp/iosApp/Screens/Auth/TVServerSetupView.swift
Adds tvOS advertising, receiver coordinator and view, and integrates pairing mode into the server-setup screen.
iOS companion discovery and approval
iosApp/iosApp/Pairing/Companion/*, iosApp/iosApp/ContentView.swift
Adds iOS TV discovery, companion coordinator, pairing card presentation, session-scoped dismissal, and top-level pairing-card wiring.
tvOS login and Aurora shell
iosApp/iosApp/tvOS/Aurora/*, iosApp/iosApp/Screens/Auth/TVLoginView.swift, iosApp/iosApp/Screens/Profiles/ProfileSelectionView.swift
Refactors tvOS auth and profile screens onto new Aurora backdrop, glass controls, and phone-first login layouts.

Audiobook playback and calendar surfaces

Layer / File(s) Summary
Audiobook and calendar data contracts
iosApp/iosApp/Networking/Models.swift, iosApp/iosApp/Networking/ContinuumAPI.swift, iosApp/iosApp/Networking/ResponseCache.swift, iosApp/iosApp/Screens/Audio/AudiobookPlaybackContext.swift, iosApp/iosApp/Screens/Audio/AudioPlaybackTimeline.swift, iosApp/iosApp/Screens/Calendar/Calendar*.swift, iosApp/iosApp/Shared/DateFormatters.swift, iosApp/Tests/DetailVersionSelectionTests.swift
Adds audiobook metadata and playback timeline types, calendar API and cache models, week/date helpers, and decoding/timeline tests.
Audiobook playback UI and routing
iosApp/iosApp/Screens/Audio/*, iosApp/iosApp/Screens/Detail/AudiobookDetailContent.swift, iosApp/iosApp/Screens/Detail/ItemDetailView*.swift, iosApp/iosApp/Screens/Browse/BrowseView.swift, iosApp/iosApp/ContentView.swift, iosApp/iosApp/Components/EpisodeThumbCard.swift, iosApp/iosApp/Screens/Player/NowPlayingController.swift
Adds audiobook player state, engine, mini/full-player UI, chapter navigation, audiobook detail playback actions, and audiobook-aware routing and now-playing metadata.
Calendar tab and navigation
iosApp/iosApp/Screens/Calendar/*, iosApp/iosApp/Navigation/TabRouter.swift, iosApp/iosApp/ContentView.swift
Adds the Calendar tab, week/filter controls, day shelves, event cards, focus handling, loading and empty states, and screen layouts for tvOS and non-tvOS.

tvOS Skyline feed and focus marquee

Layer / File(s) Summary
Skyline theme and marquee primitives
iosApp/iosApp/Components/MediaCard.swift, iosApp/iosApp/Theme/Colors.swift, iosApp/iosApp/Theme/ContinuumTheme.swift, iosApp/iosApp/tvOS/Components/TVFocusMarquee.swift, iosApp/iosApp/tvOS/Components/TVRootHeroBackdrop.swift
Adds square card geometry, Skyline theme tokens, marquee content/model/view types, and the updated hero backdrop rendering.
Feed focus routing and tvOS polish
iosApp/iosApp/Components/MediaRow.swift, iosApp/iosApp/Screens/Home/*, iosApp/iosApp/Screens/Search/SearchView.swift, iosApp/iosApp/Screens/Personal/*, iosApp/iosApp/Startup/StartupContentPrefetcher.swift
Reworks tvOS focus plumbing, audiobook row layout selection, home feed composition, reduced-motion carousel behavior, artwork prefetching, and focusable loading placeholders.

Playback core robustness and FFmpeg packaging

Layer / File(s) Summary
FFmpeg package and shim headers
iosApp/Vendor/ffmpeg-build/*
Adds a vendored FFmpeg Swift package manifest, license file, and shim headers for FFmpeg and FFmpeg-GPL targets.
Scheduler, decoder, and audio output changes
iosApp/iosApp/Screens/Player/CoreMedia/VideoFrameScheduler.swift, .../CompressedVideoPipeline.swift, .../AudioOutput.swift
Adds byte-based video backpressure, deferred decoder-reset handling, and AVAudioEngine reconfiguration recovery.
PlayerCore and playlist orchestration
iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift, iosApp/iosApp/Screens/Player/AVPlayerRoute/DVSegmentWriter.swift
Updates playlist target-duration emission, seek and audio-track restart handling, interruption behavior, decoder-reset application, and deferred teardown paths.

Settings surface refresh

Layer / File(s) Summary
Settings list and preference screens
iosApp/iosApp/Screens/Settings/SettingsView.swift, .../PlaybackSettingsView.swift, .../SubtitleSettingsView.swift
Refactors the main settings screen to grouped List sections and adds dedicated playback and subtitle preference screens for non-tvOS.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/companion-pairing

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

🧹 Nitpick comments (10)
iosApp/Vendor/ffmpeg-build/Package.swift (1)

3-12: ⚖️ Poor tradeoff

Archived upstream creates ongoing maintenance risk.

The upstream repository is archived, which means future dependency updates or checksum corrections will require manual intervention. The Libuavs3d checksum mismatch described here demonstrates this maintenance burden.

Consider documenting a process for monitoring mpvkit releases and updating checksums, or plan to migrate to an actively-maintained FFmpeg package source when feasible.

🤖 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/Vendor/ffmpeg-build/Package.swift` around lines 3 - 12, The vendored
ffmpeg-build dependency in Package.swift comes from an archived upstream
repository, creating ongoing maintenance risk when checksums need updating (as
demonstrated by the Libuavs3d issue). Expand the existing comment block to
document a process for monitoring mpvkit releases and proactively checking for
checksum updates, and also document the planned migration path or trigger
conditions for switching to an actively-maintained FFmpeg package source. This
will help future maintainers understand the maintenance burden and when action
is needed.
iosApp/iosApp/Pairing/PairingDeviceAPI.swift (1)

44-49: 💤 Low value

Consider a more type-safe pattern for empty-response endpoints.

The EmptyResponse() as! R force cast on line 85 is protected by the type check but is fragile—if the generic constraint changes or the check is removed, this would crash at runtime. Consider using a protocol-based approach or making approve return Void with a dedicated helper.

♻️ Alternative: Dedicated void-returning POST helper
 func approve(serverURL: String, bearer: String, userCode: String) async throws {
-    let _: EmptyResponse = try await post(serverURL, "/api/v1/auth/device/approve",
-                                          bearer: bearer, body: DeviceApproveRequest(code: userCode))
+    try await postVoid(serverURL, "/api/v1/auth/device/approve",
+                       bearer: bearer, body: DeviceApproveRequest(code: userCode))
 }

-private struct EmptyResponse: Codable {}
+private func postVoid<B: Encodable>(_ serverURL: String, _ path: String, bearer: String?, body: B) async throws {
+    guard let url = URL(string: serverURL.appending(path)) else { throw APIError.badURL }
+    var request = URLRequest(url: url)
+    request.httpMethod = "POST"
+    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+    request.httpBody = try encoder.encode(body)
+    applyHeaders(&request, bearer: bearer)
+    let (_, response) = try await session.data(for: request)
+    guard let http = response as? HTTPURLResponse else { throw APIError.http(-1) }
+    guard (200..<300).contains(http.statusCode) else { throw APIError.http(http.statusCode) }
+}

Also applies to: 85-85

🤖 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/Pairing/PairingDeviceAPI.swift` around lines 44 - 49, The
current implementation of the approve method relies on an unsafe force cast in
the generic post function (line 85), which is fragile and could crash if the
type constraint changes. Instead of using the EmptyResponse struct with the
generic post method, create a dedicated helper method that specifically handles
POST requests returning Void (similar to how post is implemented but without
needing to cast an empty response). Update the approve method to use this new
dedicated void-returning helper instead of calling the generic post function
with EmptyResponse, and remove the local EmptyResponse struct definition since
it will no longer be needed.
iosApp/Tests/PairingFrameTests.swift (1)

1-11: ⚖️ Poor tradeoff

Standalone test harness instead of XCTest.

This uses @main and precondition rather than the XCTest framework, making it a standalone verification script. This is valid for pure-logic unit tests and provides fast, dependency-free validation. If integration with Xcode's test navigator or CI test reporting is needed later, consider migrating to XCTestCase.

🤖 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/PairingFrameTests.swift` around lines 1 - 11, The current
standalone test harness using `@main` and precondition is noted as valid for
pure-logic unit tests, but the reviewer suggests considering a migration to
XCTestCase for better integration with Xcode's test navigator and CI test
reporting systems. To implement this, convert the PairingFrameTests struct from
a standalone `@main` entry point to an XCTestCase subclass, move each test
function (testSingleFrameRoundTrips, testTwoFramesInOneChunks,
testFrameSplitAcrossChunks, testOversizeLengthThrows) into individual test
methods prefixed with "test", replace precondition assertions with XCTest
assertion methods like XCTAssert and XCTAssertThrowsError, and remove the main()
function and print statement since XCTest will handle test execution and
reporting automatically. Update the import statement to import XCTest instead of
(or in addition to) Foundation.
iosApp/iosApp/Pairing/PairingProtocol.swift (1)

92-126: ⚡ Quick win

Consider validating the protocol version during decode.

The encoder always writes PairingProtocol.version (line 62), but the decoder never validates the incoming v field. If a future client sends a v2 message to a v1 receiver, the receiver will attempt to decode it without detecting the version mismatch, potentially causing confusing errors instead of a clear compatibility failure.

📋 Suggested version validation
 init(from decoder: Decoder) throws {
     let c = try decoder.container(keyedBy: CodingKeys.self)
+    let version = try c.decode(Int.self, forKey: .v)
+    guard version == PairingProtocol.version else {
+        throw DecodingError.dataCorrupted(
+            DecodingError.Context(
+                codingPath: decoder.codingPath,
+                debugDescription: "Protocol version mismatch: expected \(PairingProtocol.version), got \(version)"
+            )
+        )
+    }
     let kind = try c.decode(Kind.self, forKey: .type)
     switch kind {
🤖 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/Pairing/PairingProtocol.swift` around lines 92 - 126, In the
init(from decoder:) method, after creating the keyed container, add version
validation to check that the decoded `v` field matches the expected
PairingProtocol.version. Decode the version value from the container using the
appropriate CodingKey, compare it against PairingProtocol.version, and throw a
DecodingError if they do not match to prevent silent compatibility failures when
version mismatches occur between encoder and decoder.
iosApp/iosApp/Pairing/Companion/TVPairingView.swift (1)

99-101: 💤 Low value

Avoid double-cancel on user-initiated close.

When the user taps the Cancel button (line 33), close() cancels the coordinator, then onDisappear (line 42) cancels again. The second cancel attempts to send a message on an already-closed session, though this is currently handled by try? in CompanionPairingCoordinator.cancel().

♻️ Cleaner cancellation pattern
+@State private var didCancel = false
+
 private func close() {
-    Task { await coordinator?.cancel(); onClose() }
+    guard !didCancel else { onClose(); return }
+    didCancel = true
+    Task { await coordinator?.cancel(); onClose() }
 }
-.onDisappear { Task { await coordinator?.cancel() } }
+.onDisappear { 
+    guard !didCancel else { return }
+    Task { await coordinator?.cancel() } 
+}
🤖 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/Pairing/Companion/TVPairingView.swift` around lines 99 - 101,
The close() function cancels the coordinator, but when the user initiates the
close action, the onDisappear handler also attempts to cancel, resulting in a
double-cancel on an already-closed session. Refactor the close() function to
signal that cancellation has been completed so that onDisappear can skip the
redundant cancel operation. This can be achieved by introducing a state variable
to track whether the coordinator has already been cancelled, then check this
state in both the close() function and the onDisappear handler to ensure
cancel() is only called once.
iosApp/Tests/PairingProtocolTests.swift (1)

3-10: Consider refactoring test suite to use XCTest framework.

The standalone executable test pattern with @main is used consistently across all test files in the project. While this is a project-wide convention, it bypasses Xcode's test navigator, CI test reporting, and standard test tooling. Migrating to XCTest would improve tooling integration and follow iOS testing best practices.

🤖 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/PairingProtocolTests.swift` around lines 3 - 10, The
PairingProtocolTests currently uses a standalone executable pattern with `@main`
and a main() function, which bypasses Xcode's test tooling. Refactor
PairingProtocolTests from a struct with `@main` and main() to a class inheriting
from XCTestCase. Convert the existing test functions (testRoundTripsEveryCase,
testTypeDiscriminatorAndVersionArePresent, testUnknownTypeFailsToDecode) into
proper XCTest test methods by removing the explicit function calls from main(),
keeping the test logic intact, and removing the `@main` attribute and main()
function entirely to enable standard Xcode test discovery and CI integration.
iosApp/iosApp/Networking/Models.swift (1)

1170-1173: ⚡ Quick win

Inconsistent mutability: var in an otherwise-immutable request struct.

disableProgressPersistence is declared var, but all other fields in StartPlaybackRequest are let. Request structs are typically immutable. Unless this field is mutated after construction somewhere, it should be let for consistency.

♻️ Proposed fix
-    var disableProgressPersistence: Bool?
+    let disableProgressPersistence: Bool?
🤖 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/Models.swift` around lines 1170 - 1173, The
`disableProgressPersistence` property in the `StartPlaybackRequest` struct is
declared as `var` while all other fields use `let`, creating inconsistent
mutability in what should be an immutable request struct. Change the `var`
declaration to `let` for the `disableProgressPersistence` property to align with
the immutability pattern used throughout the rest of the `StartPlaybackRequest`
struct.
iosApp/iosApp/Screens/Audio/AudioPlayerViewModel.swift (1)

149-181: ⚡ Quick win

Cleanup operations swallow errors that might indicate session-stop failures.

Lines 170, 178 use try? to silence sync and session-stop errors during close(). While cleanup is best-effort, completely silent failures prevent observability into whether sessions are being properly released on the server.

Consider logging these errors (without blocking close) so server-side session leaks or sync issues can be diagnosed.

🤖 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/Audio/AudioPlayerViewModel.swift` around lines 149 -
181, The close() method uses try? to silence errors from the
ContinuumAPI.shared.syncProgress() and ContinuumAPI.shared.stopPlayback() calls,
preventing visibility into session-stop or sync failures. Instead of using try?,
wrap each API call in a do-catch block to log errors when they occur, while
still allowing close() to complete without blocking. This applies to both the
syncProgress call and the stopPlayback call so that potential server-side
session leaks or sync issues can be diagnosed through logged errors.
iosApp/iosApp/Screens/Audio/AudioChaptersSheet.swift (1)

89-91: 💤 Low value

Chapter-number fallback may display inconsistent numbering.

Line 90 falls back to chapter.index when the chapter isn't found in sortedChapters, but if chapters arrive out of index order (e.g., index 3 has an earlier startSeconds than index 2), the fallback displays a number inconsistent with the sorted visual order.

Consider logging a warning if the fallback is hit, or removing the fallback entirely and using a placeholder like "–" to surface the unexpected state.

🤖 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/Audio/AudioChaptersSheet.swift` around lines 89 - 91,
The chapterNumber function uses a fallback to chapter.index when the chapter is
not found in sortedChapters, which can display inconsistent numbering if
chapters arrive out of order. Either add warning-level logging when the fallback
is triggered to surface the unexpected state, or replace the fallback entirely
by returning a placeholder string like "–" instead of the inconsistent index
number. Choose the approach that best fits your error-handling strategy for this
scenario.
iosApp/iosApp/Screens/Audio/AudioFullPlayerView.swift (1)

39-44: 💤 Low value

Consider tracking the stop task to prevent duplicate close calls.

While less critical than the playback start task, if stop() is invoked multiple times (e.g., user rapidly taps stop, or navigation triggers multiple dismissals), concurrent player.close() calls could execute. Depending on AudioPlayerViewModel.close() implementation, this might cause issues.

♻️ Optional improvement
+@State private var stopTask: Task<Void, Never>?
+
 private func stop(player: AudioPlayerViewModel) {
+    stopTask?.cancel()
-    Task {
+    stopTask = Task {
         await player.close()
         minimize()
     }
 }
🤖 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/Audio/AudioFullPlayerView.swift` around lines 39 - 44,
The stop() function can be invoked multiple times concurrently, potentially
causing duplicate player.close() calls which could cause issues. Track the stop
task similar to how other async operations are managed in the
AudioFullPlayerView to ensure that only one close operation executes at a time.
Store the task in a property, check if a stop task is already in progress before
creating a new one, and cancel any existing stop task before creating a new one
to prevent concurrent executions of player.close().
🤖 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 `@docs/skyline-design-guide.md`:
- Around line 517-519: Remove the `All <Type>` merged scope and scope
persistence features from Phase 3 in the document, as these were previously
dropped in Rev 3 and should not be reintroduced. Keep only the cascading
selector (dwell trigger, sections flyout) and single-library sections panel in
the Phase 3 description to maintain consistency with the earlier decision to
drop merged scopes.

In `@docs/superpowers/plans/2026-06-14-companion-pairing.md`:
- Around line 848-851: The Task body that calls handlePushServer executes on a
background thread, and after the await statement, the write to isPolling
violates actor isolation rules for the `@MainActor-annotated` class. Wrap the
isPolling = false assignment with await MainActor.run to ensure the property
write happens back on the main actor and maintains proper actor isolation.

In `@docs/superpowers/specs/2026-06-14-companion-pairing-design.md`:
- Around line 69-73: The proposed ContinuumAPI.approveDevice(code:) and
ContinuumAPI.lookupDevice(code:) methods are problematic because ContinuumAPI is
tied to the app's active server, but the pairing flow needs to perform these
operations against an arbitrary chosen server URL without switching app state.
Instead of adding these methods to ContinuumAPI, create or use an
explicit-server API boundary pattern (similar to PairingDeviceAPI) that accepts
an explicit server URL parameter, allowing these operations to work against any
server without relying on or modifying the app's active server state.
- Around line 124-133: The envelope description at the beginning of the Messages
section states `{ type, v, payload }` which implies a nested structure, but this
contradicts the actual flat JSON format shown in the message table examples
below. Remove or clarify the envelope wording to accurately reflect that
messages are sent as flat JSON objects where the message type is a direct
property, not nested within a payload field. Ensure the descriptive text before
the Messages table aligns with the flat structure demonstrated in the table
itself.
- Around line 102-106: The ReceiverPairingCoordinator bullet point describes the
old persist-before-verify flow that contradicts the persist-on-success sections
elsewhere in the document. Update this description to reflect that PushServer
should remain pending until approval succeeds, rather than normalizing and
persisting the URL upfront. Restructure the sequence so that URL persistence and
token storage occur only after successful verification, aligning with the
correct flow pattern established in the rest of the design document.

In `@docs/tvos-redesign-mockups/README.md`:
- Around line 23-29: In the README.md documentation, locate the text describing
the sub-destination pills where it currently reads "Featured / Collections /
Genres / A–Z" and rename the first pill from "Featured" to "Browse" to align
with the updated Skyline specification that has already adopted this terminology
change.

In `@iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift`:
- Around line 132-148: The approveAndAdvance method waits indefinitely for
nextRelevant() to return a serverResult after approving the server, which can
cause the coordinator to hang if the TV crashes or disconnects. Add a timeout
mechanism (such as withThrowingTaskGroup or Task.sleep) to race the
nextRelevant() call against a deadline (for example, 30 seconds). If the
deadline is reached before a valid serverResult is received, catch the timeout
error and append the server to the failed array, allowing the queue to continue
processing. This ensures the coordinator has a recovery path instead of hanging
indefinitely.

In `@iosApp/iosApp/Screens/Audio/AudioPlaybackStore.swift`:
- Around line 24-33: The startLastRequest() method creates a fire-and-forget
Task without tracking it, allowing multiple concurrent calls to
player.start(...) if the method is invoked rapidly. To fix this, add a property
to store the current in-flight playback task (e.g., a Task variable), cancel any
existing task at the start of startLastRequest() before creating a new one, and
assign the new Task to the property so it can be tracked. This ensures only one
playback load attempt runs at a time, preventing concurrent execution and
resource leaks.

In `@iosApp/iosApp/Screens/Audio/AudioPlayerViewModel.swift`:
- Around line 109-115: The seek method in AudioPlayerViewModel is silently
catching errors from the loadTrack call using try?, which means users receive no
feedback when a seek operation fails. Replace the try? error suppression in the
seek(to globalTime: Double) method with proper error handling that catches any
errors thrown by loadTrack and assigns them to the error property, ensuring
users are informed when seek operations fail due to issues like missing playable
tracks or network failures.
- Around line 296-315: The syncNow() function silently ignores errors from both
the reportPlaybackProgress and syncProgress calls by using try?, which means
sync failures go unnoticed and users lose their place without knowing why.
Replace the try? error suppression with proper error handling that logs the
failures using an appropriate logging mechanism (such as a logger available in
the class). Capture the error thrown by each call and log it with sufficient
context to help diagnose why the sync failed, ensuring both
reportPlaybackProgress and syncProgress errors are handled consistently.

In `@iosApp/iosApp/Screens/Detail/AudiobookDetailContent.swift`:
- Around line 426-433: The part index adjustment logic in the partTitle method
contains a flaw in the conditional expression for displayIndex that causes
indices 0 and 1 to both display as "Part 1". The condition rawIndex <= 0 ?
rawIndex + 1 : rawIndex treats rawIndex 0 as a special case (adding 1) but
rawIndex 1 passes through unchanged, creating a collision. Fix this by
correcting the index transformation logic: either use a simple rawIndex + 1 to
convert zero-based indices to one-based consistently, or adjust the condition
from <= to < if the intent is to handle only negative indices specially and
offset all non-negative indices by adding 1.

In `@iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avdevice_shim.h`:
- Line 4: The include directive in the avdevice_shim.h header file uses an
incorrect mixed-case path `<Libavdevice/avdevice.h>` with a capital L, which
breaks on case-sensitive filesystems and is inconsistent with the lowercase
convention used in other FFmpeg shim headers (libavformat, libavutil,
libavcodec, etc.). Change the include path to use all lowercase
`<libavdevice/avdevice.h>` to match the standard convention and ensure
compatibility across all filesystem types.

In `@iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h`:
- Around line 95-97: The swift_log function has a format-string vulnerability
because it passes the msg parameter directly to av_log as if it were a format
string, which can be exploited if untrusted data is passed. Fix this by
modifying the av_log call in the swift_log function to use "%s" as the format
string literal and pass msg as an argument to that format string, ensuring msg
is treated as data rather than a format string.

In `@iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avdevice_shim.h`:
- Line 4: The include directive in avdevice_shim.h uses a capital 'L' in
'Libavdevice', which is inconsistent with all other shim headers in the same
directory that use lowercase 'lib' prefixes. Change the include path from
`<Libavdevice/avdevice.h>` to `<libavdevice/avdevice.h>` to match the casing
convention used in libavcodec, libavformat, libavfilter, libavutil,
libswresample, and libswscale headers. This fix must be applied to both the
FFmpeg/include/avdevice_shim.h and FFmpeg-GPL/include/avdevice_shim.h files to
ensure consistency and prevent build failures on case-sensitive filesystems.

---

Nitpick comments:
In `@iosApp/iosApp/Networking/Models.swift`:
- Around line 1170-1173: The `disableProgressPersistence` property in the
`StartPlaybackRequest` struct is declared as `var` while all other fields use
`let`, creating inconsistent mutability in what should be an immutable request
struct. Change the `var` declaration to `let` for the
`disableProgressPersistence` property to align with the immutability pattern
used throughout the rest of the `StartPlaybackRequest` struct.

In `@iosApp/iosApp/Pairing/Companion/TVPairingView.swift`:
- Around line 99-101: The close() function cancels the coordinator, but when the
user initiates the close action, the onDisappear handler also attempts to
cancel, resulting in a double-cancel on an already-closed session. Refactor the
close() function to signal that cancellation has been completed so that
onDisappear can skip the redundant cancel operation. This can be achieved by
introducing a state variable to track whether the coordinator has already been
cancelled, then check this state in both the close() function and the
onDisappear handler to ensure cancel() is only called once.

In `@iosApp/iosApp/Pairing/PairingDeviceAPI.swift`:
- Around line 44-49: The current implementation of the approve method relies on
an unsafe force cast in the generic post function (line 85), which is fragile
and could crash if the type constraint changes. Instead of using the
EmptyResponse struct with the generic post method, create a dedicated helper
method that specifically handles POST requests returning Void (similar to how
post is implemented but without needing to cast an empty response). Update the
approve method to use this new dedicated void-returning helper instead of
calling the generic post function with EmptyResponse, and remove the local
EmptyResponse struct definition since it will no longer be needed.

In `@iosApp/iosApp/Pairing/PairingProtocol.swift`:
- Around line 92-126: In the init(from decoder:) method, after creating the
keyed container, add version validation to check that the decoded `v` field
matches the expected PairingProtocol.version. Decode the version value from the
container using the appropriate CodingKey, compare it against
PairingProtocol.version, and throw a DecodingError if they do not match to
prevent silent compatibility failures when version mismatches occur between
encoder and decoder.

In `@iosApp/iosApp/Screens/Audio/AudioChaptersSheet.swift`:
- Around line 89-91: The chapterNumber function uses a fallback to chapter.index
when the chapter is not found in sortedChapters, which can display inconsistent
numbering if chapters arrive out of order. Either add warning-level logging when
the fallback is triggered to surface the unexpected state, or replace the
fallback entirely by returning a placeholder string like "–" instead of the
inconsistent index number. Choose the approach that best fits your
error-handling strategy for this scenario.

In `@iosApp/iosApp/Screens/Audio/AudioFullPlayerView.swift`:
- Around line 39-44: The stop() function can be invoked multiple times
concurrently, potentially causing duplicate player.close() calls which could
cause issues. Track the stop task similar to how other async operations are
managed in the AudioFullPlayerView to ensure that only one close operation
executes at a time. Store the task in a property, check if a stop task is
already in progress before creating a new one, and cancel any existing stop task
before creating a new one to prevent concurrent executions of player.close().

In `@iosApp/iosApp/Screens/Audio/AudioPlayerViewModel.swift`:
- Around line 149-181: The close() method uses try? to silence errors from the
ContinuumAPI.shared.syncProgress() and ContinuumAPI.shared.stopPlayback() calls,
preventing visibility into session-stop or sync failures. Instead of using try?,
wrap each API call in a do-catch block to log errors when they occur, while
still allowing close() to complete without blocking. This applies to both the
syncProgress call and the stopPlayback call so that potential server-side
session leaks or sync issues can be diagnosed through logged errors.

In `@iosApp/Tests/PairingFrameTests.swift`:
- Around line 1-11: The current standalone test harness using `@main` and
precondition is noted as valid for pure-logic unit tests, but the reviewer
suggests considering a migration to XCTestCase for better integration with
Xcode's test navigator and CI test reporting systems. To implement this, convert
the PairingFrameTests struct from a standalone `@main` entry point to an
XCTestCase subclass, move each test function (testSingleFrameRoundTrips,
testTwoFramesInOneChunks, testFrameSplitAcrossChunks, testOversizeLengthThrows)
into individual test methods prefixed with "test", replace precondition
assertions with XCTest assertion methods like XCTAssert and
XCTAssertThrowsError, and remove the main() function and print statement since
XCTest will handle test execution and reporting automatically. Update the import
statement to import XCTest instead of (or in addition to) Foundation.

In `@iosApp/Tests/PairingProtocolTests.swift`:
- Around line 3-10: The PairingProtocolTests currently uses a standalone
executable pattern with `@main` and a main() function, which bypasses Xcode's test
tooling. Refactor PairingProtocolTests from a struct with `@main` and main() to a
class inheriting from XCTestCase. Convert the existing test functions
(testRoundTripsEveryCase, testTypeDiscriminatorAndVersionArePresent,
testUnknownTypeFailsToDecode) into proper XCTest test methods by removing the
explicit function calls from main(), keeping the test logic intact, and removing
the `@main` attribute and main() function entirely to enable standard Xcode test
discovery and CI integration.

In `@iosApp/Vendor/ffmpeg-build/Package.swift`:
- Around line 3-12: The vendored ffmpeg-build dependency in Package.swift comes
from an archived upstream repository, creating ongoing maintenance risk when
checksums need updating (as demonstrated by the Libuavs3d issue). Expand the
existing comment block to document a process for monitoring mpvkit releases and
proactively checking for checksum updates, and also document the planned
migration path or trigger conditions for switching to an actively-maintained
FFmpeg package source. This will help future maintainers understand the
maintenance burden and when action is needed.
🪄 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: 4002a7ac-221e-4528-84e5-573f1770df8c

📥 Commits

Reviewing files that changed from the base of the PR and between 07d5b8d and f24a1439927825c638c3bdb854a314aea6db0a6d.

⛔ Files ignored due to path filters (17)
  • docs/mockups/media-integration/01-unified-home-feed-iphone.png is excluded by !**/*.png
  • docs/mockups/media-integration/02-library-first-switcher-iphone.png is excluded by !**/*.png
  • docs/mockups/media-integration/03-for-you-intent-hub-iphone.png is excluded by !**/*.png
  • docs/mockups/media-integration/04-ipad-sidebar-all-media.png is excluded by !**/*.png
  • docs/mockups/media-integration/05-tvos-unified-dashboard.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a1-skyline-home.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a2-skyline-movies.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a3-skyline-switcher.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a4-skyline-home-marquee.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a5-skyline-movies-marquee.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/a6-skyline-cascade.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/b1-rail-home.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/b2-rail-expanded.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/b3-rail-library.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/c1-stage-home.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/c2-stage-dock.png is excluded by !**/*.png
  • docs/tvos-redesign-mockups/shots/c3-stage-spaces.png is excluded by !**/*.png
📒 Files selected for processing (136)
  • .gitignore
  • docs/realtime-updates-spec.md
  • docs/skyline-design-guide.md
  • docs/skyline-implementation-prompt.md
  • docs/superpowers/plans/2026-06-14-companion-pairing.md
  • docs/superpowers/specs/2026-06-14-android-cross-platform-companion-pairing-design.md
  • docs/superpowers/specs/2026-06-14-apple-companion-pairing-implementation-summary.md
  • docs/superpowers/specs/2026-06-14-companion-pairing-design.md
  • docs/tvos-onboarding/base.css
  • docs/tvos-onboarding/base.js
  • docs/tvos-onboarding/index.html
  • docs/tvos-redesign-mockups/README.md
  • docs/tvos-redesign-mockups/b1-rail-home.html
  • docs/tvos-redesign-mockups/b2-rail-expanded.html
  • docs/tvos-redesign-mockups/b3-rail-library.html
  • docs/tvos-redesign-mockups/c1-stage-home.html
  • docs/tvos-redesign-mockups/c2-stage-dock.html
  • docs/tvos-redesign-mockups/c3-stage-spaces.html
  • docs/tvos-redesign-mockups/tv.css
  • iosApp/Tests/DetailVersionSelectionTests.swift
  • iosApp/Tests/PairingFrameTests.swift
  • iosApp/Tests/PairingProtocolTests.swift
  • iosApp/Vendor/ffmpeg-build/LICENSE
  • iosApp/Vendor/ffmpeg-build/Package.swift
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/dummy.c
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avcodec_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avdevice_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avfilter_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avformat_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/swresample_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/swscale_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/dummy.c
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avcodec_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avdevice_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avfilter_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avformat_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avutil_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/swresample_shim.h
  • iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/swscale_shim.h
  • iosApp/iosApp/Components/EpisodeThumbCard.swift
  • iosApp/iosApp/Components/MediaCard.swift
  • iosApp/iosApp/Components/MediaRow.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Info.plist
  • iosApp/iosApp/Navigation/TabRouter.swift
  • iosApp/iosApp/Networking/ContinuumAPI.swift
  • iosApp/iosApp/Networking/DeviceLoginModels.swift
  • iosApp/iosApp/Networking/Models.swift
  • iosApp/iosApp/Networking/ResponseCache.swift
  • iosApp/iosApp/Networking/TokenStore.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Companion/SetUpTVBanner.swift
  • iosApp/iosApp/Pairing/Companion/TVPairingBrowser.swift
  • iosApp/iosApp/Pairing/Companion/TVPairingView.swift
  • iosApp/iosApp/Pairing/PairingDeviceAPI.swift
  • iosApp/iosApp/Pairing/PairingFrame.swift
  • iosApp/iosApp/Pairing/PairingProtocol.swift
  • iosApp/iosApp/Pairing/PairingSession.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingAdvertiser.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swift
  • iosApp/iosApp/Screens/Audio/AudioChaptersSheet.swift
  • iosApp/iosApp/Screens/Audio/AudioCoverArtView.swift
  • iosApp/iosApp/Screens/Audio/AudioCoverPalette.swift
  • iosApp/iosApp/Screens/Audio/AudioFullPlayerView.swift
  • iosApp/iosApp/Screens/Audio/AudioMiniPlayerView.swift
  • iosApp/iosApp/Screens/Audio/AudioPlaybackStore.swift
  • iosApp/iosApp/Screens/Audio/AudioPlaybackTimeline.swift
  • iosApp/iosApp/Screens/Audio/AudioPlayerBackground.swift
  • iosApp/iosApp/Screens/Audio/AudioPlayerEngine.swift
  • iosApp/iosApp/Screens/Audio/AudioPlayerViewModel.swift
  • iosApp/iosApp/Screens/Audio/AudiobookPlaybackContext.swift
  • iosApp/iosApp/Screens/Auth/TVLoginView.swift
  • iosApp/iosApp/Screens/Auth/TVServerSetupView.swift
  • iosApp/iosApp/Screens/Browse/BrowseView.swift
  • iosApp/iosApp/Screens/Browse/LibrariesTabView.swift
  • iosApp/iosApp/Screens/Calendar/CalendarDayShelf.swift
  • iosApp/iosApp/Screens/Calendar/CalendarEventCard.swift
  • iosApp/iosApp/Screens/Calendar/CalendarFilterBar.swift
  • iosApp/iosApp/Screens/Calendar/CalendarModels.swift
  • iosApp/iosApp/Screens/Calendar/CalendarView.swift
  • iosApp/iosApp/Screens/Calendar/CalendarViewModel.swift
  • iosApp/iosApp/Screens/Calendar/CalendarWeek.swift
  • iosApp/iosApp/Screens/Calendar/CalendarWeekStrip.swift
  • iosApp/iosApp/Screens/Detail/AudiobookDetailContent.swift
  • iosApp/iosApp/Screens/Detail/ItemDetailView.swift
  • iosApp/iosApp/Screens/Detail/ItemDetailViewModel.swift
  • iosApp/iosApp/Screens/Home/FeaturedCarousel.swift
  • iosApp/iosApp/Screens/Home/HomeView.swift
  • iosApp/iosApp/Screens/Home/SectionRow.swift
  • iosApp/iosApp/Screens/Personal/FavoritesView.swift
  • iosApp/iosApp/Screens/Personal/HistoryView.swift
  • iosApp/iosApp/Screens/Personal/WatchlistView.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/DVSegmentWriter.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/AudioOutput.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/CompressedVideoPipeline.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swift
  • iosApp/iosApp/Screens/Player/CoreMedia/VideoFrameScheduler.swift
  • iosApp/iosApp/Screens/Player/NowPlayingController.swift
  • iosApp/iosApp/Screens/Profiles/ProfileSelectionView.swift
  • iosApp/iosApp/Screens/Search/SearchView.swift
  • iosApp/iosApp/Screens/Settings/PlaybackSettingsView.swift
  • iosApp/iosApp/Screens/Settings/SettingsView.swift
  • iosApp/iosApp/Screens/Settings/SubtitleSettingsView.swift
  • iosApp/iosApp/Shared/DateFormatters.swift
  • iosApp/iosApp/Startup/StartupContentPrefetcher.swift
  • iosApp/iosApp/Theme/Colors.swift
  • iosApp/iosApp/Theme/ContinuumTheme.swift
  • iosApp/iosApp/tvOS-Info.plist
  • iosApp/iosApp/tvOS/Aurora/AuroraBackdrop.swift
  • iosApp/iosApp/tvOS/Aurora/AuroraStyle.swift
  • iosApp/iosApp/tvOS/Components/TVFocusMarquee.swift
  • iosApp/iosApp/tvOS/Components/TVRootHeroBackdrop.swift
  • iosApp/iosApp/tvOS/Components/TVSkylineSectionFeed.swift
  • iosApp/iosApp/tvOS/Navigation/TVCascadeSelector.swift
  • iosApp/iosApp/tvOS/Navigation/TVLibraryScopeStore.swift
  • iosApp/iosApp/tvOS/Navigation/TVMainTabView.swift
  • iosApp/iosApp/tvOS/Navigation/TVTopMenuBar.swift
  • iosApp/iosApp/tvOS/Screens/Components/TVCollectionPosterCard.swift
  • iosApp/iosApp/tvOS/Screens/Detail/TVItemDetailView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVAlphabetRail.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibrariesTabView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryBrowseView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryCollectionsView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryGridView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryGridViewModel.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryLandingView.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryPillRow.swift
  • iosApp/iosApp/tvOS/Screens/Libraries/TVLibraryTypeTabView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVCardOverlaySettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVPlaybackSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift
  • iosApp/project.yml

Comment thread docs/skyline-design-guide.md Resolved
Comment on lines +69 to +73
### New client method
`ContinuumAPI.approveDevice(code:)` and `ContinuumAPI.lookupDevice(code:)` — the
endpoints exist but approval was previously web-only (`web/src/pages/ActivateDevice.tsx`),
so the iOS client needs these thin wrappers over `HTTPClient`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the explicit-server API boundary here.

ContinuumAPI is tied to the app's active server, but pairing needs to look up/approve against an arbitrary chosen server URL without switching app state. Please align this section with PairingDeviceAPI.

Suggested wording
- `ContinuumAPI.approveDevice(code:)` and `ContinuumAPI.lookupDevice(code:)`
+ `PairingDeviceAPI.lookup(serverURL:bearer:userCode:)` and `PairingDeviceAPI.approve(serverURL:bearer:userCode:)`
🤖 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 `@docs/superpowers/specs/2026-06-14-companion-pairing-design.md` around lines
69 - 73, The proposed ContinuumAPI.approveDevice(code:) and
ContinuumAPI.lookupDevice(code:) methods are problematic because ContinuumAPI is
tied to the app's active server, but the pairing flow needs to perform these
operations against an arbitrary chosen server URL without switching app state.
Instead of adding these methods to ContinuumAPI, create or use an
explicit-server API boundary pattern (similar to PairingDeviceAPI) that accepts
an explicit server URL parameter, allowing these operations to work against any
server without relying on or modifying the app's active server state.

Comment on lines +426 to +433
private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
if let fileName = part.fileName, !fileName.isEmpty {
return fileName
}
let rawIndex = part.presentationPartIndex ?? fallbackIndex
let displayIndex = rawIndex <= 0 ? rawIndex + 1 : rawIndex
return "Part \(displayIndex)"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix the part index adjustment to avoid duplicate "Part 1" labels.

The current logic creates a collision: when rawIndex is 0, it displays "Part 1", and when rawIndex is 1, it also displays "Part 1". The condition rawIndex <= 0 ? rawIndex + 1 : rawIndex causes this duplication.

🐛 Proposed fix

If the intent is to convert zero-based indices to one-based:

 private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
     if let fileName = part.fileName, !fileName.isEmpty {
         return fileName
     }
     let rawIndex = part.presentationPartIndex ?? fallbackIndex
-    let displayIndex = rawIndex <= 0 ? rawIndex + 1 : rawIndex
+    let displayIndex = rawIndex + 1
     return "Part \(displayIndex)"
 }

If the intent is to preserve positive indices and only offset non-positive ones:

 private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
     if let fileName = part.fileName, !fileName.isEmpty {
         return fileName
     }
     let rawIndex = part.presentationPartIndex ?? fallbackIndex
-    let displayIndex = rawIndex <= 0 ? rawIndex + 1 : rawIndex
+    let displayIndex = rawIndex < 1 ? rawIndex + 1 : rawIndex
     return "Part \(displayIndex)"
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
if let fileName = part.fileName, !fileName.isEmpty {
return fileName
}
let rawIndex = part.presentationPartIndex ?? fallbackIndex
let displayIndex = rawIndex <= 0 ? rawIndex + 1 : rawIndex
return "Part \(displayIndex)"
}
private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
if let fileName = part.fileName, !fileName.isEmpty {
return fileName
}
let rawIndex = part.presentationPartIndex ?? fallbackIndex
let displayIndex = rawIndex + 1
return "Part \(displayIndex)"
}
Suggested change
private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
if let fileName = part.fileName, !fileName.isEmpty {
return fileName
}
let rawIndex = part.presentationPartIndex ?? fallbackIndex
let displayIndex = rawIndex <= 0 ? rawIndex + 1 : rawIndex
return "Part \(displayIndex)"
}
private func partTitle(_ part: FileVersion, fallbackIndex: Int) -> String {
if let fileName = part.fileName, !fileName.isEmpty {
return fileName
}
let rawIndex = part.presentationPartIndex ?? fallbackIndex
let displayIndex = rawIndex < 1 ? rawIndex + 1 : rawIndex
return "Part \(displayIndex)"
}
🤖 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/Detail/AudiobookDetailContent.swift` around lines 426 -
433, The part index adjustment logic in the partTitle method contains a flaw in
the conditional expression for displayIndex that causes indices 0 and 1 to both
display as "Part 1". The condition rawIndex <= 0 ? rawIndex + 1 : rawIndex
treats rawIndex 0 as a special case (adding 1) but rawIndex 1 passes through
unchanged, creating a collision. Fix this by correcting the index transformation
logic: either use a simple rawIndex + 1 to convert zero-based indices to
one-based consistently, or adjust the condition from <= to < if the intent is to
handle only negative indices specially and offset all non-negative indices by
adding 1.

#ifndef AVDEVICE_SHIM_H
#define AVDEVICE_SHIM_H

#include <Libavdevice/avdevice.h>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify include-case consistency in FFmpeg shim headers.
rg -n 'Libavdevice/avdevice.h|libavdevice/avdevice.h' iosApp/Vendor/ffmpeg-build/Sources

Repository: Silo-Server/silo-apple

Length of output: 274


🏁 Script executed:

#!/bin/bash
# Find all FFmpeg shim headers and their include patterns
fd 'shim\.h$' iosApp/Vendor/ffmpeg-build/Sources --exec cat -n {} +

Repository: Silo-Server/silo-apple

Length of output: 18484


Fix mixed-case include path in avdevice_shim.h headers.

<Libavdevice/avdevice.h> is inconsistent with FFmpeg's standard lowercase convention used in all other shim headers (libavformat, libavutil, libavcodec, etc.). This breaks on case-sensitive filesystems.

Proposed fix
-#include <Libavdevice/avdevice.h>
+#include <libavdevice/avdevice.h>

Affects both iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/avdevice_shim.h and iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avdevice_shim.h.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#include <Libavdevice/avdevice.h>
`#include` <libavdevice/avdevice.h>
🤖 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/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avdevice_shim.h` at
line 4, The include directive in the avdevice_shim.h header file uses an
incorrect mixed-case path `<Libavdevice/avdevice.h>` with a capital L, which
breaks on case-sensitive filesystems and is inconsistent with the lowercase
convention used in other FFmpeg shim headers (libavformat, libavutil,
libavcodec, etc.). Change the include path to use all lowercase
`<libavdevice/avdevice.h>` to match the standard convention and ensure
compatibility across all filesystem types.

Comment on lines +95 to +97
static inline void swift_log(void *avcl, int level, const char *msg) {
av_log(avcl, level, msg);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect call sites to validate no one relies on printf-style formatting through swift_log.
rg -n 'swift_log\s*\(' iosApp

Repository: Silo-Server/silo-apple

Length of output: 346


🏁 Script executed:

# Check if there are any references to swift_log beyond the definitions
rg 'swift_log' iosApp --type h --type c --type m --type swift -B 2 -A 2

# Check if this header is included anywhere
rg 'avutil_shim\.h' iosApp

# Check the git history to understand the purpose of this file
git log --oneline -n 5 iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h 2>/dev/null || echo "No git history available"

# Check if there are comments explaining the purpose
head -20 iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h

Repository: Silo-Server/silo-apple

Length of output: 684


🏁 Script executed:

# Let's examine the full avutil_shim.h file to understand its purpose and scope
wc -l iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h

# Get the full content
cat -n iosApp/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h

# Check if swift_log is referenced in any .swift files
fd -e swift -x rg 'swift_log' {} + 2>/dev/null || echo "No swift_log in Swift files"

# Check Module.modulemap or other build configuration to understand what's exported
find iosApp/Vendor/ffmpeg-build -name "*.modulemap" -o -name "module.modulemap" | head -5 | xargs cat 2>/dev/null || echo "No modulemap found"

# Check if there's any bridging header or module definition
fd -e h -path "*/module*" iosApp/Vendor/ffmpeg-build

Repository: Silo-Server/silo-apple

Length of output: 8228


Fix format-string vulnerability in swift_log.

av_log expects a format string; passing msg directly exposes the function to format-string attacks if called with untrusted data.

Proposed fix
 static inline void swift_log(void *avcl, int level, const char *msg) {
-  av_log(avcl, level, msg);
+  av_log(avcl, level, "%s", msg ? msg : "");
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static inline void swift_log(void *avcl, int level, const char *msg) {
av_log(avcl, level, msg);
}
static inline void swift_log(void *avcl, int level, const char *msg) {
av_log(avcl, level, "%s", msg ? msg : "");
}
🤖 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/Vendor/ffmpeg-build/Sources/FFmpeg-GPL/include/avutil_shim.h` around
lines 95 - 97, The swift_log function has a format-string vulnerability because
it passes the msg parameter directly to av_log as if it were a format string,
which can be exploited if untrusted data is passed. Fix this by modifying the
av_log call in the swift_log function to use "%s" as the format string literal
and pass msg as an argument to that format string, ensuring msg is treated as
data rather than a format string.

#ifndef AVDEVICE_SHIM_H
#define AVDEVICE_SHIM_H

#include <Libavdevice/avdevice.h>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify FFmpeg header directory structure and casing

# Search for FFmpeg include directories in the vendor package
fd -t d -i 'avdevice' iosApp/Vendor/ffmpeg-build/

# Also check other shim headers for comparison
rg -n "include <[Ll]ib" iosApp/Vendor/ffmpeg-build/Sources/ --type-add 'header:*.h' --type header

Repository: Silo-Server/silo-apple

Length of output: 4542


🏁 Script executed:

# Check for the actual avdevice header directories
find iosApp/Vendor/ffmpeg-build -type d -name "*avdevice*" 2>/dev/null

# Check what's in the FFmpeg include directories
ls -la iosApp/Vendor/ffmpeg-build/Sources/FFmpeg/include/ 2>/dev/null | head -20

# Verify if there are actual framework or header directories with different casing
find iosApp/Vendor/ffmpeg-build -type d \( -name "lib*" -o -name "Lib*" \) 2>/dev/null | grep -i lib

Repository: Silo-Server/silo-apple

Length of output: 631


🏁 Script executed:

# Check if there are actual FFmpeg source headers with avdevice
find iosApp/Vendor/ffmpeg-build -name "avdevice.h" 2>/dev/null

# Look at the full directory structure of the vendor ffmpeg-build
find iosApp/Vendor/ffmpeg-build -maxdepth 3 -type d 2>/dev/null | head -30

# Check if this is a framework include or regular header path
grep -r "Libavdevice\|libavdevice" iosApp/Vendor/ffmpeg-build/ --include="*.h" --include="*.swift" 2>/dev/null | grep -v "avdevice_shim.h"

Repository: Silo-Server/silo-apple

Length of output: 1128


🏁 Script executed:

# Check the Package.swift to understand the framework setup
cat iosApp/Vendor/ffmpeg-build/Package.swift

Repository: Silo-Server/silo-apple

Length of output: 12636


🏁 Script executed:

# Check how the shim headers are actually imported/used in the codebase
rg -r "avdevice_shim|avcodec_shim|avfilter_shim" iosApp/ --type swift --type objc -A 2 -B 2

# Also check if there are any build configuration or header search paths
find iosApp -name "*.pbxproj" -o -name "*.xcconfig" | head -5

# Check how the FFmpeg target sources use these shim headers
find iosApp/Vendor/ffmpeg-build/Sources -name "*.swift" -o -name "*.h" | xargs grep -l "include" 2>/dev/null

Repository: Silo-Server/silo-apple

Length of output: 1145


Inconsistent include path casing in avdevice_shim.h.

The include path <Libavdevice/avdevice.h> uses a capital 'L', while all other shim headers in the same directory use lowercase: <libavcodec/avcodec.h>, <libavformat/avformat.h>, <libavfilter/avfilter.h>, <libavutil/avutil.h>, <libswresample/swresample.h>, and <libswscale/swscale.h>. This inconsistency affects both FFmpeg/include/avdevice_shim.h and FFmpeg-GPL/include/avdevice_shim.h. On case-sensitive filesystems, this could cause build failures if the actual header paths don't match. Standardize to lowercase for consistency with the other shim headers.

🤖 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/Vendor/ffmpeg-build/Sources/FFmpeg/include/avdevice_shim.h` at line 4,
The include directive in avdevice_shim.h uses a capital 'L' in 'Libavdevice',
which is inconsistent with all other shim headers in the same directory that use
lowercase 'lib' prefixes. Change the include path from
`<Libavdevice/avdevice.h>` to `<libavdevice/avdevice.h>` to match the casing
convention used in libavcodec, libavformat, libavfilter, libavutil,
libswresample, and libswscale headers. This fix must be applied to both the
FFmpeg/include/avdevice_shim.h and FFmpeg-GPL/include/avdevice_shim.h files to
ensure consistency and prevent build failures on case-sensitive filesystems.

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

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

guard let token = await TokenStore.shared.getAccessToken(for: server.id), !token.isEmpty else {
fail(server); await pushNext(); return
}
let lookup = try await api.lookup(serverURL: server.url, bearer: token, userCode: userCode)

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 Refresh tokens before pairing approval

Refresh tokens before using the stored bearer here. This path bypasses HTTPClient's 401 refresh and serversWithTokens() only verifies an access token exists, so a normal expired access token (especially for a non-active saved server) makes lookup/approve fail with 401 even though the refresh token is still valid; the selected server is then marked failed and companion setup cannot complete.

Useful? React with 👍 / 👎.

self.encoder = encoder
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601

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 Decode server fractional dates in pairing API

Use the same fractional-ISO8601 decoding as HTTPClient. The device/start response includes expiresAt, and the server's timestamps elsewhere include fractional seconds; with .iso8601, PairingDeviceAPI.start throws a decode error on values like ...42.211273Z, so the TV never reaches deviceStarted and pairing fails before the code appears.

Useful? React with 👍 / 👎.

@@ -93,6 +98,7 @@ struct ContentView: View {
handleDeepLink(url)
}
.onReceive(NotificationCenter.default.publisher(for: .continuumSessionExpired)) { _ in
Task { await audioStore.player.close() }

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 Dismiss audiobook cover on session expiry

Dismiss the audio full-screen cover when expiring the session. If the refresh failure arrives while AudioFullPlayerView is presented, player.close() clears the context but leaves isShowingFullPlayer == true, so the root swaps to login underneath an undismissed fullScreenCover that renders the no-audiobook empty state and provides no login path.

Useful? React with 👍 / 👎.

Comment on lines +439 to +443
.fullScreenCover(isPresented: Binding(
get: { audioStore.isShowingFullPlayer },
set: { if !$0 { audioStore.dismissFullPlayer() } }
)) {
AudioFullPlayerView()

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 Provide audiobook controls on macOS

Expose this presentation on macOS or don't start macOS playback. AudiobookDetailContent is compiled for macOS and its Play buttons call audioStore.play(...), but this cover/miniplayer is inside #if !os(macOS), so pressing Play on SiloMac starts the AVPlayer task with no visible controls to pause, stop, or minimize it.

Useful? React with 👍 / 👎.

Comment on lines +58 to +60
ErrorView(
state: error,
onRetry: { audioStore.retryLastRequest() }

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 Add a dismiss path for audio start failures

When an audiobook start fails before playback is established (for example the item-detail or playback-start request errors), this ErrorView is shown inside a non-dismissible fullScreenCover with only Retry and Sign Out actions. The user is trapped in the failed audio player instead of being able to close it and return to the app, so provide an onGoBack/close action that clears isShowingFullPlayer for this error state.

Useful? React with 👍 / 👎.

Comment on lines +546 to +548
if libraries.isEmpty,
let cached: LibrariesResponse = ResponseCache.shared.get(CacheKey.userLibraries) {
libraries = cached.libraries

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 Avoid reusing cached libraries after server switches

This cache entry is not scoped by server or profile, but switchToServer clears libraries and then calls loadLibraries() without clearing CacheKey.userLibraries. On a tvOS server switch, the old server's library tabs can be restored from this cache while the new /user/libraries request is slow or fails, leaving stale library IDs visible under the new server session.

Useful? React with 👍 / 👎.

if context != nil {
await close()
}
let detail = try await ContinuumAPI.shared.itemDetail(contentId: contentId)

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 audiobook start requests

Guard this initial item-detail load with a request token or cancel the previous start. If the user taps Play for one audiobook and then starts another before the first /catalog/items request returns, both start calls run concurrently while context is still nil; the slower, older response can overwrite the newer request's context/session and start the wrong book.

Useful? React with 👍 / 👎.

@@ -2,6 +2,7 @@ import SwiftUI

struct ContentView: View {
@State private var router = AppRouter()
@State private var audioStore = AudioPlaybackStore()

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 Stop audio when leaving the authenticated server

Because this root-scoped store survives auth-state changes, manual sign-out, profile switch, and server switch can leave an audiobook playing with the old stream/session after the UI has moved to another account or server. The sync loop then reports progress using the new active TokenStore state (or no tokens), so close the player on those auth/server boundaries, not only on session-expired notifications.

Useful? React with 👍 / 👎.

Comment on lines +89 to +90
if sections.indices.contains(pageIndex) {
let section = sections[pageIndex]

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 Clamp Skyline page after rows refresh

Clamp pageIndex when sections changes. Home refreshes its rows on return/player dismissal, and if the user was paged down to a row that disappears (for example Continue Watching shrinks or permissions/data change), this guard simply renders no band at all because the stale index is out of range, leaving the tvOS root page blank/stranded until another root is selected.

Useful? React with 👍 / 👎.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review

Found 1 issue:

  1. .done with zero sign-ins leaves the tvOS receiver stuck (bug due to ReceiverPairingCoordinator.run: when signedInCount == 0, the if signedInCount > 0 guard skips the terminal state and teardown(session:resetState: false) never resets state to .idle)

When the companion sends .done before any server is signed in (the user picks no servers, or every server fails/declines), state stays at .linked/.awaitingApproval, so TVServerSetupView keeps the pairing panel on screen with a spinner and no recovery path except the Cancel button. Every other exit (.cancel, stream end, stream error) passes resetState: true; this branch is the outlier and contradicts the class doc comment that "any drop, decline, timeout, or cancel returns to idle." Passing resetState: signedInCount == 0 resolves it.

https://github.com/Silo-Server/silo-apple/blob/3706383e63cb157f705b179d19afea02bdf0c845/iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift#L76-L81

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, 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

🤖 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/Pairing/Companion/CompanionPairingCard.swift`:
- Around line 43-44: The onDisappear handler at line 43 only cancels the
coordinator, but the startup task created at lines 256-262 (which waits on
session.open()) can continue running after the card is dismissed. You need to
store a reference to the task created in that startup logic and cancel it in the
onDisappear handler. Add a property to track the startup task instance, assign
it when the task is created at lines 256-262, and include cancellation of this
task in the onDisappear closure along with the existing coordinator cancellation
to prevent the pairing operation from continuing off-screen.
🪄 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: 2d925bf4-7ac5-43ea-b979-b4a613f23b7a

📥 Commits

Reviewing files that changed from the base of the PR and between 96635bda416e65c7aa7f23cf1e7fef3baa57a1b2 and a9fb6e6ba223c0e09f546b826bf3f62f9ceb6951.

📒 Files selected for processing (18)
  • .superpowers/brainstorm/90967-1781482515/content/flow-steps.html
  • .superpowers/brainstorm/90967-1781482515/content/intro-card.html
  • .superpowers/brainstorm/90967-1781482515/content/waiting.html
  • .superpowers/brainstorm/90967-1781482515/state/server-stopped
  • docs/superpowers/plans/2026-06-14-companion-pairing-card-ios.md
  • docs/superpowers/specs/2026-06-14-companion-pairing-card-ios-design.md
  • iosApp/Tests/CompanionDismissalKeyTests.swift
  • iosApp/iosApp/ContentView.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCard.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCardModifier.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingDismissal.swift
  • iosApp/iosApp/Pairing/Companion/TVPairingBrowser.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingAdvertiser.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swift
  • iosApp/iosApp/Screens/Auth/TVLoginView.swift
  • iosApp/iosApp/Screens/Auth/TVServerSetupView.swift
  • iosApp/iosApp/Screens/Profiles/ProfileSelectionView.swift
  • iosApp/iosApp/tvOS/Aurora/AuroraStyle.swift
✅ Files skipped from review due to trivial changes (3)
  • .superpowers/brainstorm/90967-1781482515/state/server-stopped
  • iosApp/iosApp/Pairing/Companion/CompanionPairingDismissal.swift
  • docs/superpowers/plans/2026-06-14-companion-pairing-card-ios.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • iosApp/iosApp/Pairing/Companion/TVPairingBrowser.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingAdvertiser.swift
  • iosApp/iosApp/Screens/Auth/TVLoginView.swift
  • iosApp/iosApp/Screens/Auth/TVServerSetupView.swift

Quick104 and others added 25 commits June 14, 2026 22:23
In the Skyline cascade selector, pressing d-pad Left out of the section
flyout landed on the geometrically nearest library row (e.g. "Movies –
Anime") instead of the library the flyout is scoped into ("Movies"),
since the flyout is top-aligned a row below its anchor.

Set the library column's user-initiated default focus to the anchored
row via defaultFocus(_:_:priority: .userInitiated) + focusSection — the
same idiom TVEpisodeRail uses for rail entry. prefersDefaultFocus and
onMoveCommand don't work here: the former only fires for automatic focus
evaluations (not d-pad moves), the latter is reactive and produces a
visible focus hop.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
HTML/CSS/JS prototypes for the Welcome → Server → Connecting → Sign-in →
Profile onboarding flow, in three directions: Monolith, Aurora, Tandem.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Phone-driven Apple TV setup: iOS discovers a waiting tvOS app over
Bonjour, pushes the server URL(s), and approves sign-in via the
server's existing device-auth endpoints. No URL/password typed on
the remote. v1 is Apple-client-only; protocol documented for Android.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Persist-on-success (Codex HIGH): TV treats a pushed server URL as a
  pending candidate, shows it, and commits to ServerRegistry/TokenStore
  only after sign-in; discards on cancel/fail/timeout/drop. §5, §6, §7, §9.
- Reframe self-signed TLS as opportunistic confidentiality only.
- Document confirm-once multi-server LAN-MITM as an explicitly accepted
  v1 risk with preconditions, rationale, mitigation, and tripwire (§6).
- Resolve the confirm-once open question (§12).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
14 TDD tasks: shared protocol/frame/session, isolated PairingDeviceAPI
(per-server device auth without disturbing the active server), tvOS
receiver (advertiser + persist-on-success coordinator + UI), iOS
companion (browser + confirm-once coordinator + banner + flow), and a
manual LAN end-to-end acceptance test. Pure-logic units unit-tested via
standalone swiftc programs; coordinators verified manually.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ation

- Remove the Face ID / biometric gate (spec §1/§5/§6). Authorization is the
  user's confirmation tap on a phone already signed in to the server — the
  signed-in phone is the authority. Resolves the spec/plan inconsistency
  (HIGH #1) by dropping the unimplemented gate rather than adding it.
- Make the Receiver poll loop cancellable (plan Task 8): the stream reader
  no longer blocks on polling; each server's start+poll is a separate
  cancellable Task, so a peer Cancel or dropped connection aborts the
  attempt immediately and frees the advertiser (HIGH #3).
- Confirm-once multi-server CRITICAL re-affirmed as the previously-accepted
  v1 risk (no change).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Apply the Aurora (cinematic) direction to the tvOS first-run flow: add
AuroraBackdrop + AuroraStyle, rework TVLoginView and TVServerSetupView
onto the Aurora styling, and adjust ProfileSelectionView to match.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…der guard, cancel state, token guards

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Quick104 and others added 21 commits June 14, 2026 22:23
The match-code tiles were a fixed 60pt wide each, so a long server
word-pair code (e.g. MEADOW-OCEAN) made the row the widest element in the
QR panel. That pushed the hero+panel split row past its maxWidth, which
overflowed and shoved the hero column off the left edge. Cap the row
width and scale the tiles down for longer codes so the panel stays
compact regardless of code length.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pin the eyebrow/title near the top and center the two cards in the
remaining space, instead of centering the whole title+cards block which
left the cards sitting low.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The tvOS first-run "Aurora" flow and the iOS companion pairing screens
used a system-serif display face plus ~40 ad-hoc point sizes that matched
nothing else in the app. Route their display/body/caption text through
the shared continuum* type tokens (system font, weight-driven, platform-
scaled) so the fonts line up with the rest of the app.

- Drop auroraSerif (New York serif) and remove the now-unused helper
- Map serif/ad-hoc headings to continuumHeroTitle/Title/Headline/
  Subheadline, body to continuumBody, status/metadata to continuumCaption,
  and match codes to continuumPIN
- iOS companion screens: swap stock .headline/.caption/.subheadline.bold()
  for their continuum equivalents
- Keep Aurora's layout, palette, glass, gold accents, and the bespoke
  SF Mono eyebrows/labels/step rows and SF Symbol icon sizes

SiloTV (tvOS) builds green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reconcile advertiser/dismissal comments and the design spec with the actual
tvOS advertiser lifecycle: sid rotates on each start() (setup-screen restart),
not per pairing attempt. Record optional per-attempt rotation as a deferred
follow-up. Surfaced by the final whole-implementation review.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Add setup card, server selection, and match-code concept screens
- Record brainstorm session stopped state
- Reserve the lower half of Skyline for the focused row and clipped next-row preview
- Align Home and library marquee insets for a consistent 50/50 split
- Add compact Skyline card padding and spacing constants
- Suppress top menu focus after content focus handoff
- Mark the pairing advertiser logger nonisolated
- Preserve the TV login headline while simplifying styled text composition
@Quick104
Quick104 force-pushed the feature/companion-pairing branch from f38c675 to be883c3 Compare June 15, 2026 02:25
@Quick104
Quick104 merged commit f91e54f into main Jun 15, 2026
1 check passed
@Quick104
Quick104 deleted the feature/companion-pairing branch June 15, 2026 02:26
Quick104 added a commit that referenced this pull request Jul 3, 2026
…UX hardening (#47)

* Companion pairing: consent gate, timeouts, unified LAN transport, UX hardening

Full-review hardening pass over the iPhone->Apple TV companion pairing
flow (originally PR #7).

Security:
- TV-side consent gate: the first pushed server now requires an explicit
  Allow on the TV before any device/start call is made on its behalf.
  The channel PSK is public, so previously any LAN device could sign a
  TV in setup mode into an arbitrary server unattended.
- Auto-approved servers 2..N bind the TV-displayed match code to the
  server's authoritative one, closing the channel-splice gap in the
  confirm-once design; a missing match code hard-fails.

Transport (shared with SiloControl):
- New generic FramedJSONSession actor under Networking/LAN backs both
  PairingSession and SiloControlSession as typealiases; pairing inherits
  the ordered outbound FIFO and watchdog-bounded closeGracefully, and
  the next transport fix lands once instead of maybe-twice. PairingFrame
  renamed SiloFrame and moved to the shared home; SiloLANTLS is the
  common PSK builder (wire PSKs unchanged for compatibility).

Reliability:
- Companion coordinator rewritten loop-driven (single stream reader):
  a TV-side cancel during the match-code pause is now heard immediately,
  and every peer wait has a watchdog (hello 15s, first response 90s to
  cover the consent prompt, others 30s) so a stale Bonjour endpoint is
  an explanatory error instead of a permanent spinner.
- Receiver keeps its failure screen instead of being clobbered back to
  idle by the phone's done/EOF; EOF after a success still lands on the
  summary; the post-persist result frame is best-effort so a lost packet
  can't repaint a real sign-in as a failure; a 180s idle watchdog stops
  a silent peer from holding setup mode hostage; a new pushServer
  supersedes an in-flight poll; TV-side cancels send a goodbye so the
  phone says "cancelled on the TV," not "connection lost."
- Advertiser and browser self-heal with the generation-guarded restart
  pattern from TVControlReceiver; the advertiser only accepts a new
  phone once the panel is back at idle, so a second phone can't clobber
  a summary mid-read.

UX / accessibility:
- Cancel on every non-terminal card step (the scrim stops dismissing
  once the flow starts, so a wedged TV used to trap the user); in-card
  Try Again on failures (the card could previously never re-appear for
  a TV that stayed advertising, making the TV's "try again from your
  iPhone" advice impossible); zero-success summaries no longer show a
  green checkmark; match codes are spelled out for VoiceOver on both
  platforms; copy is device-aware (iPad) and no longer asks the user to
  compare a code their phone never shows; the card is only offered when
  the phone has a signed-in server and browsing pauses in background.

Testing: coordinators now sit behind PairingChannel and
PairingDeviceAuthorizing seams; 11 new state-machine tests cover the
consent gate, the deaf-confirm regression, match-code binding, and the
end-of-stream summaries, plus expanded frame tests (zero-length, exact
max, byte-drip). ReceiverPairingCoordinator loses its tvOS-only guard so
the iOS test bundle can drive it. iOS, tvOS, and macOS build; full suite
passes.

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

* Address review: early drain start, watchdog ordering, committed-success automatic flag

- FramedJSONSession: start the outbound drain in open() instead of on
  .ready. A send() awaited before the connection came up (the receiver's
  hello) could hang forever if the peer failed TLS first: teardown
  finished the FIFO, but with no consumer the buffered continuation was
  never resumed, stranding the coordinator and leaving the advertiser
  busy. Writes queued pre-ready park in NWConnection until the transport
  comes up or is cancelled. (Codex P1 / CodeRabbit)

- CompanionPairingCoordinator: arm response watchdogs BEFORE the
  suspending send/approve calls. The stream reader keeps handling
  messages while those awaits are suspended, so a fast TV's reply could
  land first and the resumed task would then arm a stale watchdog that
  later killed a legitimate confirm screen. (Codex P2)

- ReceiverPairingCoordinator: derive the awaitingApproval "automatic"
  flag from a committed sign-in (!signedInNames.isEmpty) instead of
  attempt order — a pre-confirm failure on the first server must not
  make the TV claim the phone is auto-approving while the phone is
  still asking the user to compare codes. New regression test holds the
  second attempt at awaitingApproval and asserts manual copy.
  (CodeRabbit)

- Tests: guard-else branches now XCTFail instead of silently passing.
  (CodeRabbit nitpick)

All three platforms build; pairing/control/frame suites pass.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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