Repository navigation
Companion pairing: TV consent gate, timeouts, unified LAN transport, UX hardening - #47
Conversation
…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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThis 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. ChangesPairing transport and coordinator rework
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 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".
| private func beginLoops() { | ||
| receiveLoop() | ||
| drainTask = Task { [weak self] in await self?.startDrainLoop() } | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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." | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
iosApp/Tests/PairingCoordinatorTests.swift (1)
173-178: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winGuard-else silently no-ops instead of failing.
In
testCancelFromTVWhileConfirmingSurfacesError,testConnectionDropMidFlowShowsError, andtestMissingMatchCodeFailsServer, theguard case let ... = coordinator.state else { return }blocks bail out with a barereturnrather thanXCTFail. 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 callXCTFailin theirelsebranches.🧪 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
📒 Files selected for processing (17)
iosApp/Tests/PairingCoordinatorTests.swiftiosApp/Tests/PairingFrameTests.swiftiosApp/Tests/SiloFrameTests.swiftiosApp/iosApp/Control/SiloControlSession.swiftiosApp/iosApp/Networking/LAN/FramedJSONSession.swiftiosApp/iosApp/Networking/LAN/SiloFrame.swiftiosApp/iosApp/Pairing/Companion/CompanionPairingCard.swiftiosApp/iosApp/Pairing/Companion/CompanionPairingCardModifier.swiftiosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swiftiosApp/iosApp/Pairing/Companion/TVPairingBrowser.swiftiosApp/iosApp/Pairing/PairingDeviceAPI.swiftiosApp/iosApp/Pairing/PairingProtocol.swiftiosApp/iosApp/Pairing/PairingSession.swiftiosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swiftiosApp/iosApp/Pairing/Receiver/TVPairingAdvertiser.swiftiosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swiftiosApp/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]>
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
device/startcall is made on its behalf. Consent is per-session; no protocol change, so shipped phones stay compatible.Transport — unified with SiloControl
FramedJSONSessionactor underNetworking/LAN/backs bothPairingSessionandSiloControlSessionas typealiases. Pairing inherits SiloControl's hardening (ordered outbound FIFO, watchdog-boundedcloseGracefully), and future transport fixes land once instead of maybe-twice.PairingFrame→SiloFramein the shared home;SiloLANTLSis the common PSK builder (wire PSKs unchanged).Reliability
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 newpushServersupersedes an in-flight poll; TV-side cancels send a goodbye so the phone says "cancelled on the TV," not "connection lost."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
Testing
Coordinators now sit behind
PairingChannel/PairingDeviceAuthorizingseams; 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).ReceiverPairingCoordinatorloses its tvOS-only guard so the iOS test bundle can drive it.Reviewer notes
sid) dismissal; retry lives inside the card, and the card re-offers when the TV starts a fresh setup session.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes