Skip to content

Companion pairing: TV consent gate, timeouts, unified LAN transport, UX hardening - #47

Merged
Quick104 merged 2 commits into
mainfrom
claude/mystifying-fermat-ba70a3
Jul 3, 2026
Merged

Quick104 merged 2 commits into
mainfrom
claude/mystifying-fermat-ba70a3

Conversation

@Quick104

@Quick104 Quick104 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Full-review hardening pass over the iPhone → Apple TV companion pairing flow (originally #7), addressing every finding from a three-angle review (correctness/security, architecture, UX). All three platforms build; full test suite passes with 19 new tests.

Security

  • TV-side consent gate — the channel PSK is public (by design; confidentiality only), so any LAN device could previously sign a TV in setup mode into an arbitrary server unattended. The first pushed server now shows "Allow this setup?" on the TV before any device/start call is made on its behalf. Consent is per-session; no protocol change, so shipped phones stay compatible.
  • Match-code binding for auto-approved servers — servers 2..N in a multi-server push (the confirm-once accepted risk) now require the TV-displayed code to equal the server's authoritative one, closing the channel-splice gap. A missing match code hard-fails instead of showing an empty prompt.

Transport — unified with SiloControl

  • New generic FramedJSONSession actor under Networking/LAN/ backs both PairingSession and SiloControlSession as typealiases. Pairing inherits SiloControl's hardening (ordered outbound FIFO, watchdog-bounded closeGracefully), and future transport fixes land once instead of maybe-twice. PairingFrame → SiloFrame in the shared home; SiloLANTLS is the common PSK builder (wire PSKs unchanged).

Reliability

  • Companion coordinator rewritten loop-driven (single stream reader, mirroring the receiver): a TV-side cancel during the match-code pause is heard immediately (previously the phone went deaf and would approve a dead session), and every peer wait has a watchdog (hello 15s / first response 90s to cover the consent prompt / others 30s) — a stale Bonjour endpoint becomes an explanatory error instead of a permanent spinner behind an undismissable scrim.
  • Receiver: failure screen no longer clobbered back to idle by the phone's done/EOF; EOF-after-success still lands on the summary; post-persist result frame is best-effort (a lost packet can't repaint a real sign-in as a failure); 180s idle watchdog against silent-peer DoS of setup mode; 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."
  • Self-heal: advertiser + browser adopt TVControlReceiver's generation-guarded restart, so the first-run screen can't silently stop advertising. The advertiser only accepts a new phone once the panel is back at idle (a second phone can't clobber a summary mid-read).

UX / accessibility

  • Cancel on every non-terminal card step; in-card Try Again on failures (the card previously could never re-appear for a TV that kept advertising, making the TV's "try again from your iPhone" advice impossible).
  • Zero-success summary loses its 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 for auto-approved servers; card only offered when the phone has a signed-in server; browsing pauses in background; card steps animate.

Testing

Coordinators now sit behind PairingChannel / PairingDeviceAuthorizing seams; 11 new state-machine tests cover the consent gate, the deaf-confirm regression, match-code binding, drop-mid-flow, and end-of-stream summaries, plus expanded frame tests (zero-length, exact-max boundary, byte-drip). ReceiverPairingCoordinator loses its tvOS-only guard so the iOS test bundle can drive it.

Reviewer notes

  • Behavior change: first pairing now needs one Allow click on the Siri remote — worth a TestFlight-notes mention.
  • Every card exit records a per-setup-session (sid) dismissal; retry lives inside the card, and the card re-offers when the TV starts a fresh setup session.
  • Wire format and PSKs are unchanged; old↔new app versions still pair (older phones simply see the consent wait as a slightly longer first step, inside the new 90s window).
  • Remaining validation: two-simulator end-to-end run, d-pad focus on the new consent screen, VoiceOver spot-check.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced TV and companion pairing UI with dedicated consent, consent denial, cancel/retry, and clearer completion outcomes (including “Try Again” vs “Done”).
    • Added more robust approval behavior, including automatic approval flow when applicable, plus improved accessibility for match codes.
    • Strengthened self-healing discovery/advertising so pairing better tolerates interruptions.
  • Bug Fixes

    • Fixed final-state handling for connection drops and failed approvals to avoid incorrect success/summary screens.
    • Ensured correct match-code verification and prevented mismatched auto-approval.
    • Improved edge cases like missing match codes and repeated attempts after early failures.

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

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c6e6b4fb-9fd2-4917-9e35-21d7a37afae2

📥 Commits

Reviewing files that changed from the base of the PR and between efdc800 and d548bd0.

📒 Files selected for processing (4)
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/iosApp/Networking/LAN/FramedJSONSession.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
🚧 Files skipped from review as they are similar to previous changes (4)
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/iosApp/Networking/LAN/FramedJSONSession.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift

📝 Walkthrough

Walkthrough

This PR replaces bespoke pairing session code with shared framed JSON transport, rewrites companion and receiver pairing coordinators around continuous stream handling, updates related UI and discovery/release flow, and adds coordinator coverage while removing older frame tests.

Changes

Pairing transport and coordinator rework

Layer / File(s) Summary
SiloFrame and framing tests
iosApp/iosApp/Networking/LAN/SiloFrame.swift, iosApp/Tests/SiloFrameTests.swift
PairingFrame/PairingFrameBuffer are renamed to SiloFrame/SiloFrameBuffer, frame-length checks use the new type, and the framing tests now cover the renamed implementation.
Generic framed JSON transport
iosApp/iosApp/Networking/LAN/FramedJSONSession.swift
Adds shared TLS setup, ordered outbound delivery, framed JSON receive handling, and graceful teardown over NWConnection.
Session aliases and protocol surfaces
iosApp/iosApp/Control/SiloControlSession.swift, iosApp/iosApp/Pairing/PairingSession.swift, iosApp/iosApp/Pairing/PairingDeviceAPI.swift, iosApp/iosApp/Pairing/PairingProtocol.swift
SiloControlSession and PairingSession become aliases of FramedJSONSession, and new PairingChannel and PairingDeviceAuthorizing protocols define the channel and device-authority interfaces.
Companion coordinator stream flow
iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
Moves the companion flow to a continuous stream consumer with watchdogs, device-start handling, match-code confirmation, and token-based gating helpers.
Companion pairing card and browser UI
iosApp/iosApp/Pairing/Companion/CompanionPairingCard.swift, iosApp/iosApp/Pairing/Companion/CompanionPairingCardModifier.swift, iosApp/iosApp/Pairing/Companion/TVPairingBrowser.swift
Updates dismissal, retry, accessibility, candidate latching, scene-phase handling, and browser restart behavior.
Receiver coordinator consent and lifecycle
iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
Adds consent gating, automatic approval state, superseding push handling, idle timeout handling, persistence injection, and updated completion classification.
Receiver advertiser and setup UI
iosApp/iosApp/Pairing/Receiver/TVPairingAdvertiser.swift, iosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swift, iosApp/iosApp/Screens/Auth/TVServerSetupView.swift
Adds generation-guarded listener restarts, consent and automatic-approval UI, and idle-based advertiser release.
Coordinator state-machine tests
iosApp/Tests/PairingCoordinatorTests.swift
Adds scripted fakes and coverage for companion and receiver coordinator flows, including consent, cancellation, approval, disconnect, and failure regressions.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Phone
  participant CompanionPairingCoordinator
  participant PairingChannel
  participant ReceiverPairingCoordinator
  Phone->>CompanionPairingCoordinator: connect(to: tv)
  CompanionPairingCoordinator->>PairingChannel: start run()
  PairingChannel-->>CompanionPairingCoordinator: .hello / .deviceStarted / .serverResult
  CompanionPairingCoordinator->>CompanionPairingCoordinator: validate, confirm, conclude
  PairingChannel-->>ReceiverPairingCoordinator: .pushServer
  ReceiverPairingCoordinator->>ReceiverPairingCoordinator: consentRequested / allowPendingServer
  ReceiverPairingCoordinator->>PairingChannel: .serverResult
  PairingChannel-->>CompanionPairingCoordinator: result / cancel
Loading

Possibly related PRs

  • Silo-Server/silo-apple#12: It also changes the shared LAN framing layer and is coupled to the same transport abstraction used by pairing sessions.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main changes: TV consent gating, timeout/reliability work, shared LAN transport, and pairing UX hardening.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/mystifying-fermat-ba70a3

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

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +117 to +120
private func beginLoops() {
receiveLoop()
drainTask = Task { [weak self] in await self?.startDrainLoop() }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Start the outbound drain before ready-state sends can hang

When a caller awaits send() before the NWConnection reaches .ready—for example the TV receiver sends its initial .hello immediately after open()—a peer that drops or fails TLS first takes the .failed/.cancelled teardown path without ever creating drainTask. teardown finishes the outbound stream, but with no consumer the queued send continuation is never resumed, so ReceiverPairingCoordinator.run can hang before arming its idle timer and the advertiser stays busy, rejecting future pairing attempts. Start the drain loop at open() time or otherwise fail buffered send continuations during teardown.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d548bd0 — the drain task now starts in open() (before connection.start), so a send awaited pre-.ready always has a consumer: on early .failed/.cancelled, teardown's connection.cancel() fails the in-flight write and the running drain fails the remaining buffered continuations with SessionError.closed. Writes queued before .ready park in NWConnection until the transport comes up.

Comment on lines +244 to +250
try await channel.send(.pushServer(serverURL: server.url, serverName: server.displayName))
armWatchdog(
isFirstPush ? Timeouts.firstDeviceStarted : Timeouts.deviceStarted,
isFirstPush
? "\(tvName) didn’t respond. Make sure you allowed the request on the TV, then try again."
: "\(tvName) stopped responding."
)

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 Arm peer watchdogs before awaiting operations

Because the stream reader can process inbound messages while this task is suspended in channel.send, a fast TV can send deviceStarted, have handleDeviceStarted disarm the current watchdog and show the match-code screen, and then this continuation resumes and arms a fresh first-response watchdog anyway. In that interleaving, the phone times out and cancels while the user is legitimately comparing the code. Arm the watchdog before the suspending send or verify the same server/state is still pending before arming it after the await.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d548bd0 — watchdogs are now armed before the suspending send in pushNext() and before the approve call in approveCurrent(), so a reply that lands while the task is suspended disarms the already-armed watchdog and the resume can no longer arm a stale one over the confirm screen.

@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

🧹 Nitpick comments (1)
iosApp/Tests/PairingCoordinatorTests.swift (1)

173-178: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Guard-else silently no-ops instead of failing.

In testCancelFromTVWhileConfirmingSurfacesError, testConnectionDropMidFlowShowsError, and testMissingMatchCodeFailsServer, the guard case let ... = coordinator.state else { return } blocks bail out with a bare return rather than XCTFail. If the pattern match ever fails here, the test exits silently and reports as passed, defeating the purpose of these regression tests. Contrast with lines 362-364 and 389-391 in the same file, which correctly call XCTFail in their else branches.

🧪 Proposed fix (apply to all three sites)
-        guard case let .pickServers(_, servers) = coordinator.state else { return }
+        guard case let .pickServers(_, servers) = coordinator.state else {
+            return XCTFail("expected pickServers state, got \(coordinator.state)")
+        }

Also applies to: 233-239, 254-260

🤖 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/PairingCoordinatorTests.swift` around lines 173 - 178, The guard
patterns in PairingCoordinatorTests are silently returning instead of failing,
so these regression tests can pass even when the expected state is wrong. Update
the `guard case let ... = coordinator.state` blocks in
`testCancelFromTVWhileConfirmingSurfacesError`,
`testConnectionDropMidFlowShowsError`, and `testMissingMatchCodeFailsServer` to
call `XCTFail` in the `else` branch, matching the existing pattern used
elsewhere in this file. Keep the flow anchored around `coordinator.state` and
`pushSelected(_:)` so any unexpected state transition is reported as a test
failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@iosApp/iosApp/Networking/LAN/FramedJSONSession.swift`:
- Around line 194-210: The drain loop in FramedJSONSession is started too late,
which can leave buffered send continuations hanging if teardown() happens before
connection state reaches .ready. Move the drain task startup into open() so
send() has a consumer immediately after the session opens, and keep teardown(_:)
focused on cancelling the connection and finishing the continuations without
depending on .ready. Use the existing symbols open(), teardown(_ error:), and
drainTask to wire this change.

In `@iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift`:
- Around line 223-231: The automatic-pairing decision in beginAttempt is
currently based on attemptCount, which can flip too early when pushNext()
advances before any server is actually signed in. Update the automatic flag
logic in ReceiverPairingCoordinator to derive from a committed success state
instead, such as checking signedInNames (for example, whether it is empty)
rather than attemptCount, so handlePushServer uses automatic only after a
sign-in has been committed.

---

Nitpick comments:
In `@iosApp/Tests/PairingCoordinatorTests.swift`:
- Around line 173-178: The guard patterns in PairingCoordinatorTests are
silently returning instead of failing, so these regression tests can pass even
when the expected state is wrong. Update the `guard case let ... =
coordinator.state` blocks in `testCancelFromTVWhileConfirmingSurfacesError`,
`testConnectionDropMidFlowShowsError`, and `testMissingMatchCodeFailsServer` to
call `XCTFail` in the `else` branch, matching the existing pattern used
elsewhere in this file. Keep the flow anchored around `coordinator.state` and
`pushSelected(_:)` so any unexpected state transition is reported as a test
failure.
🪄 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: d6ff4e09-5120-4902-9e98-4a79bde0a5a7

📥 Commits

Reviewing files that changed from the base of the PR and between b74da5a and efdc800.

📒 Files selected for processing (17)
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/Tests/PairingFrameTests.swift
  • iosApp/Tests/SiloFrameTests.swift
  • iosApp/iosApp/Control/SiloControlSession.swift
  • iosApp/iosApp/Networking/LAN/FramedJSONSession.swift
  • iosApp/iosApp/Networking/LAN/SiloFrame.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCard.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCardModifier.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Companion/TVPairingBrowser.swift
  • iosApp/iosApp/Pairing/PairingDeviceAPI.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/Auth/TVServerSetupView.swift
💤 Files with no reviewable changes (1)
  • iosApp/Tests/PairingFrameTests.swift

…ss 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]>
@Quick104
Quick104 merged commit 5e0b745 into main Jul 3, 2026
1 check was pending
@Quick104
Quick104 deleted the claude/mystifying-fermat-ba70a3 branch July 3, 2026 04:27
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