Skip to content

feat(pairing): pair devices through v2 - #361

Merged
Quick104 merged 2 commits into
mainfrom
apiv2-stack/13-pair-devices-through-v2
Sep 23, 2026
Merged

Quick104 merged 2 commits into
mainfrom
apiv2-stack/13-pair-devices-through-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Phone-to-TV pairing and the tvOS SiloRemote handoff now start, poll, check capability, look up and approve through /api/v2/auth/device/*. A v1-only server reads as "needs an update" on both screens, and the TV binds the paired session to the verified account id.

Problem

Pairing and the handoff still used /api/v1/auth/device/* for start, poll, capability, lookup and approve (inventory rows 13-18). A 1.0 server answers every one of those with 410.

These calls target an explicit server URL (the pushed or chosen server), not the active one. They go through PairingDeviceAPI's own URLSession and skip APIv2Client.gate() and its recorded probe verdict. After a plain path switch, a v1-only server's 404 page not found would read as "request expired" on the TV and as "Couldn't reach … to approve" on the phone, not as "server needs an update". The TV also installed the paired session with no verified account id.

Solution

  • PairingDeviceAPI calls POST /api/v2/auth/device/start (expects 201), POST /api/v2/auth/device/poll, GET /api/v2/auth/device/capability, GET /api/v2/auth/device?code= and POST /api/v2/auth/device/approve (all expect 200). It decodes the existing APIv2DeviceStart, APIv2DevicePoll (with validated()), APIv2DeviceLookup, APIv2DeviceCapability and APIv2DeviceDecision models with HTTPClient.makeJSONDecoder().
  • The client classifies failures like APIv2Client.mapErrors: a problem document becomes APIv2Error.problem, Go's plain 404 (APIv2Probe.isLegacyNotFound) becomes APIv2Error.serverUpdateRequired, any other status becomes APIv2Error.httpStatus, and transport failures stay URLError. A 2xx other than the expected status becomes incompleteAuthResponse. UpdateRequirement(error) therefore recognizes both the legacy 404 and a 410 client_upgrade_required.
  • Each request is sent once. Start and poll are non_retryable. Approve is domain_identity, but it is also never re-sent: this path has no refresh, and a lost answer is reported rather than approved again. This is the single-dispatch exemption the plan asks for. The request never enters HTTPClient, so shouldAttemptRefresh needs no change.
  • TV receiver (ReceiverPairingCoordinator): reads the nested TokenPair, binds TokenPair.user.id through installAccountSession(accountID:clearProfile: false) (previously saveTokens with no account), and follows poll_after. An update requirement on start or poll ends the attempt with the existing update copy (UpdateRequirement.message) and sends a new update_required failure code to the phone. Under the existing PairingFailureCode(wire:) rule, older phones read that code as auth_failed. A 404 problem still means "expired". An incomplete approval ends the attempt, because the tokens are issued once. Other errors keep polling, as before.
  • Session-install breadcrumb: TokenStore.installAccountSession now writes the essential "session credential event" breadcrumb (phase: sessionInstall, outcome: failed, fixed reason) when it cannot install the session. saveTokens used to write it. Pairing no longer calls saveTokens, so without this move a hosted diagnostics report for a pairing that failed at the Keychain write would have no line explaining it. saveTokens drops its own copy so the line is not written twice. Login also calls installAccountSession, so a failed login install now records the same breadcrumb.
  • Phone companion (CompanionPairingCoordinator): a lookup that fails with an update requirement is summarised as update_required. A failed approval now names the cause: the update message, "already approved or declined" (409), "code expired" (410 or 404 problem), the old connection message for a transport failure, or "couldn't approve the sign-in" for anything else.
  • SiloRemote handoff (RemotePlaybackIdentityManager): the capability check now requires state == "available", allowed != false, remote_playback_handoff and the protocol version. The session expiry comes from the validated poll; the 24-hour fallback is gone. A 404 problem on poll maps to expired, and an incomplete approval maps to invalidResponse. An update requirement surfaces through the error's localizedDescription.
  • Deleted: DeviceLoginPollRequest, DeviceLoginPollResponse, DeviceLoginCapabilityResponse, APIv2DeviceCapability.presentation, PairingDeviceAPI.APIError.http/decode and the custom date formatters. DeviceLoginStartRequest/DeviceLoginStartResponse stay as the v2 request body and the start presentation shared with QR sign-in. DeviceLookupResponse and DeviceApproveRequest stay because SiloControlClient (W5-D) still uses them.

Failure outcomes

Operation Definite success Definite failure Uncertain (sent, no answer)
start (non_retryable) TV shows the match code Attempt fails: update copy for update-required, "unreachable" for a transport failure before the send, auth_failed otherwise Surfaces as URLError, so the attempt shows "unreachable". Not re-sent
poll (non_retryable) Approved: tokens installed with the verified account A 404 problem ends the attempt as expired; update-required ends it with update copy; an incomplete approval ends it Keeps polling the same device code until it expires, as before. A consumed code then reads as expired
approve (domain_identity, sent once) The TV's poll collects the tokens Session ends with a cause-specific message and cancel(approve_failed) Session ends with the connection message. Never re-sent

Validation

  • iOS, tvOS and macOS builds passed.
  • iOS tests for PairingDeviceAPITests (new), CompanionPairingCoordinatorTests, ReceiverPairingCoordinatorTests, ServerSessionPersistenceTests, PairingProtocolTests, RemotePlaybackRoutingTests and AuthDeviceV2Tests passed: 70 tests, 0 failures. tvOS tests for the same classes (the companion class is iOS-only) passed: 30 tests, 0 failures.
  • After the breadcrumb fix, iOS tests for AccountSessionPersistenceTests, PairingCoordinatorTests and PairingDeviceAPITests passed (40 tests, 0 failures), and tvOS tests for AccountSessionPersistenceTests and PairingDeviceAPITests passed (40 tests, 0 failures).
  • scripts/ci/check-no-api-v1.sh passed. PairingDeviceAPI.swift and DeviceLoginModels.swift no longer contain /api/v1.
  • New PairingDeviceAPITests use StubURLProtocol to check:
    • the v2 paths, no bearer on start and poll, and the chosen server's bearer on lookup and approve
    • snake_case bodies with unset members omitted, and the 201 requirement on start
    • the three 404 cases: legacy text becomes update-required, a problem 404 stays a problem, and a proxy HTML 404 becomes httpStatus
    • 410 client_upgrade_required as an app update
    • a single dispatch for approve on 409, 410 and a dropped connection
    • capability gating on state
  • New AccountSessionPersistenceTests.testFailedVerifiedInstallRecordsSessionInstallBreadcrumb fails the session write through the injected persistence and reads the sessionInstall/failed/persistenceUnavailable breadcrumb back from the early-boot buffer. It fails without the TokenStore change.
  • New coordinator tests cover update-required on start and on poll (typed code and copy, no further polling), the verified account id passed to persist, the phone summary for an update-required lookup, and the 409 approval message.
  • The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, built for macOS and passed the v1 path guard. Every branch in the stack builds on its own.
  • Not run: a manual pairing on devices against a bridge server and a v1-only server. persistServer's switch from saveTokens to installAccountSession has no direct test, because it runs against the shared TokenStore, HTTPClient and ServerRegistry singletons.

Risks and follow-ups

  • persistServer now fails, and rolls back, if a SiloRemote temporary scope is active during setup pairing. installAccountSession refuses that case, whereas saveTokens silently wrote the tokens into the temporary scope. Pairing runs from the TV setup screen, so this should not happen in practice.
  • The pairing protocol gains the update_required failure code. A phone from before this change shows it as the generic "couldn't finish signing in".
  • The handoff poll still ends on the first transport error, as before. Only the error mapping changed.
  • W5-D (rows 19-21) still uses DeviceLookupResponse and DeviceApproveRequest from SiloControlClient and should delete them once it moves to v2.
  • No open-PR conflict is expected. Issues TV client sign-in & onboarding — iOS #326 and TV client sign-in & onboarding — tvOS #327 (TV sign-in validation) cover this flow, so their validation pass should include pairing.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 13 of 50 in the Apple API v2 stack. Base: apiv2-stack/12-tvos-qr-sign-in-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 8 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: bd96972c-317e-451f-9af4-b292213e0b83

📥 Commits

Reviewing files that changed from the base of the PR and between f69e854 and a45cbbe.

📒 Files selected for processing (12)
  • iosApp/Tests/AccountSessionPersistenceTests.swift
  • iosApp/Tests/PairingCoordinatorTests.swift
  • iosApp/Tests/PairingDeviceAPITests.swift
  • iosApp/iosApp/Control/tvOS/RemotePlaybackIdentityManager.swift
  • iosApp/iosApp/Networking/APIv2/APIv2AuthModels.swift
  • iosApp/iosApp/Networking/DeviceLoginModels.swift
  • iosApp/iosApp/Networking/TokenStore.swift
  • iosApp/iosApp/Pairing/Companion/CompanionPairingCoordinator.swift
  • iosApp/iosApp/Pairing/PairingDeviceAPI.swift
  • iosApp/iosApp/Pairing/PairingProtocol.swift
  • iosApp/iosApp/Pairing/Receiver/ReceiverPairingCoordinator.swift
  • iosApp/iosApp/Pairing/Receiver/TVPairingReceiverView.swift

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:37:54.190330Z a45cbbe New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 05bbc975 (apiv2-stack/13-pair-devices-through-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • minor: A failed pairing session install no longer leaves a diagnostics breadcrumb

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@Quick104
Quick104 force-pushed the apiv2-stack/12-tvos-qr-sign-in-v2 branch from 17e6bdf to c1182a6 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/13-pair-devices-through-v2 branch from 05bbc97 to 8fda12a Compare September 23, 2026 13:19

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

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

let value: APIv2DeviceStart = try await post(
serverURL,
"/api/v1/auth/device/start",
"/api/v2/auth/device/start",

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 Migrate the handoff controller before switching the receiver

When a handoff is not reused, this now creates and polls a v2 request, but SiloControlClient.sendHandoff still looks up, approves, and denies that challenge through the v1 routes at SiloControlClient.swift:351-374. On servers that retire v1 with HTTP 410—the target of this migration—the phone therefore cannot approve the v2 challenge, so every fresh SiloRemote handoff fails after displaying its challenge. Move the controller lookup/approve/deny calls to v2 in the same rollout, or defer this receiver switch.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/12-tvos-qr-sign-in-v2 branch from c1182a6 to 4e75806 Compare September 23, 2026 13:32
Phone-to-TV pairing and the SiloRemote handoff still opened, polled,
looked up and approved device logins through /api/v1/auth/device/*. A
1.0 server answers those with 410. These calls target an explicit
server URL rather than the active server, so they bypass APIv2Client
and its recorded probe verdict. A v1-only server's plain 404 therefore
ended as a generic "Something went wrong signing in". The paired
session was also installed with no verified account id.

PairingDeviceAPI now calls /api/v2/auth/device/start (expects 201),
/poll, /capability, GET /api/v2/auth/device and /approve. It classifies
failures the way APIv2Client.mapErrors does: a problem document becomes
APIv2Error.problem, Go's plain 404 becomes serverUpdateRequired, any
other status becomes httpStatus, and transport failures stay URLError.
Each request is dispatched once; approve is never re-sent, even after a
lost answer.

The TV receiver reads the nested TokenPair, binds TokenPair.user.id as
the verified account at install, and follows poll_after. An update
requirement ends the attempt with the existing update copy and a new
update_required failure code, which older phones read as auth_failed.
The phone summarises that code, and an approval that fails with 409 or
410 says the request was already decided or expired instead of blaming
the connection. The SiloRemote handoff gates on an available capability
document and takes the session expiry from the validated poll.

The v1 poll request and response and the capability presentation model
are deleted.

Stack-PR: W5-C
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Base automatically changed from apiv2-stack/12-tvos-qr-sign-in-v2 to main September 23, 2026 13:33
Pairing now installs the paired session through installAccountSession
instead of saveTokens. Only saveTokens recorded the essential "session
credential event" breadcrumb when the session could not be written, so
a diagnostics report for a pairing that failed at the Keychain write
had nothing explaining the failure.

installAccountSession now records the sessionInstall/failed breadcrumb
with the fixed persistence-failure reason for every installer (pairing,
login and saveTokens), and saveTokens drops its duplicate. A test fails
the session write through the injected persistence and reads the
breadcrumb back.

Stack-PR: W5-C
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/13-pair-devices-through-v2 branch from 8fda12a to a45cbbe Compare September 23, 2026 13:33
@Quick104
Quick104 merged commit 311dca6 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/13-pair-devices-through-v2 branch September 23, 2026 13:33

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

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

private static func isMissingRequest(_ error: Error) -> Bool {
switch error {
case APIv2Error.problem(let problem): return problem.status == 404
case APIv2Error.httpStatus(404): return true

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 Retry non-problem 404 poll responses

When a reverse proxy returns its own HTML 404 while the device request is still live, PairingDeviceAPI deliberately classifies it as APIv2Error.httpStatus(404) (as covered by PairingDeviceAPITests.swift:91-95), but this branch treats it as definitive expiry. That bypasses the transient proxy-error retry immediately below, ends pairing, and incorrectly tells the user the code expired. Only a typed v2 problem 404 proves the request is missing; a bare 404 should remain retryable.

Useful? React with 👍 / 👎.

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