Skip to content

Let the Mac decide the iPhone's routes and send them over the connection - #372

Closed
oliverames wants to merge 34 commits into
mattt:mainfrom
oliverames:feat/ios-config-from-mac
Closed

oliverames wants to merge 34 commits into
mattt:mainfrom
oliverames:feat/ios-config-from-mac

Conversation

@oliverames

@oliverames oliverames commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Stack. Stacked on #370 (which sits on #369, #368, #366, #365 and #281). It does not depend on #367 or #371. Review only the two commits after #370. Merge order is in #364.

What it does and why

After #369 and #370 the phone decides how to reach the Mac: it keeps the endpoints from the pairing code and picks the order of routes itself. The Mac can't change anything for a paired phone without re-pairing, and a stale address stays on the phone. This makes the Mac the source of truth. Setup still starts locally with the pairing QR; after that the phone learns its configuration from the Mac.

What changed

  • MobileConfiguration is a versioned value the Mac builds from its real state: a revision that only goes up, the Mac's name and Bonjour service, the recommended mode, an ordered list of routes (local, Cloudflare, Tailscale VPN, Funnel, each with a label and a host and port or URL), and the features the phone needs (approvals and activity history). Decoding skips unknown route kinds and defaults missing fields, so a newer Mac still works with this phone.
  • The Mac sends it in the welcome on every authenticated connection, including pairing. The old tailnet, Funnel and Cloudflare fields are still sent and a phone that has a configuration ignores them, so older phones keep working.
  • While the phone is connected, the Mac calls a new config_apply tool whenever the route order, a route toggle, an endpoint or the activity-history setting changes. The phone replies with the revision it applied and the Mac shows it per paired device.
  • A revision that isn't newer is never applied. A newer one replaces the saved addresses and clears routes the Mac no longer offers. Automatic follows the Mac's recommended mode and then its order; a mode chosen on the phone uses that one route.
  • Mac: a "Routes Offered to Your Devices" section in the iPhone & iPad settings with drag to reorder, a toggle per route, the current revision and each device's applied revision.
  • iPhone: Connection Mode shows "Configured by (revision N)", the routes in order with their status, and a Refresh Configuration button. The manual address fields only appear until a configuration has been learned.

iPhone & iPad settings on the Mac: devices, routes, connection mode, approvals and activity

The Mac's iPhone & iPad settings as redesigned in my integration build, which is a separate upcoming PR. This PR does not include that redesign, and the sidebar in the screenshot still says "Developer & Advanced" (since renamed "Advanced").

Testing

  • imcp-serverTests, full suite: 289 tests, 1 skipped, 0 failures (24 new): the encode and decode round trip, an old welcome without a configuration, a newer Mac's unknown fields, the route order built from Mac state, never applying an older or equal revision, replace instead of merge, and the revision ledger. Delivery tests use a real TLS connection to a fake phone: the welcome on pairing and on every reconnect, config_apply and its acknowledgement, a settings change pushing a new revision to a connected phone, an old phone without the tool being left alone, and unpairing forgetting the acknowledgement.
  • macOS and iOS targets build. swift format lint --strict is clean on the changed files.
  • On a device, confirmed by me on my iPhone in my integration build, which has this protocol (TestFlight builds 30, 31 and 32 uploaded and VALID; build 32 carries the phone-learns-config-from-the-Mac protocol): the phone connected over the Cloudflare route, Connection Mode showed "Configured by " with a revision and the routes in the Mac's order, a live route-order change in the Mac's settings changed the revision on the phone, and the settings screens worked. The TestFlight builds come from my fork's integration branch, which carries the same code as this stack plus fork-only pieces. They are not builds of this exact branch.
  • CI: the macOS 26 (Xcode 26.0) and macOS 27 (Xcode 27.0) builds both pass on this branch. Earlier runs of some of these branches failed on a stale Clang module cache on the macOS 26 runner and passed when rerun; no code changed for that.

Not verified

  • This exact branch has not been on the device.
  • The phone's connection code, config_apply on the phone and both phone screens have no test target and are compile-checked only. Saving the learned configuration to the Keychain is untested.
  • The approvals flag is always false in this stack because Approve client connections from iMCP for iPhone and iPad #367 is not part of it.
  • The revision number lives in the Mac's UserDefaults. If those are reset, the numbers restart low and a paired phone ignores them until it re-pairs.

mattt and others added 30 commits November 6, 2026 10:20
Define the Health, Finance, and Alarms tools once in Shared/Companion,
store what the iPhone sends in an encrypted SQLite cache,
and answer read-only calls from that cache with synced_at and stale.
Generalize HomeInput into ToolInput so both services validate arguments.
The iPhone app dials the Mac over TLS with pre-shared keys,
pairs with a one-time code from a QR code in Settings > Companion,
and serves the companion tools as an MCP server on that connection.
The Mac calls tools live when the phone is connected,
retries a lost read or an alarm change that carries its ID,
and pulls queued changes from the phone's outbox into its cache.
Scripts/install-companion.sh builds and installs the app with your team.
Answer the Health tools live from HealthKit,
let the user allow each group of types from the app,
and queue anchored changes for the Mac: daily statistics for quantity types
and full records for sleep, workouts, and health records.
When HealthKit is locked, the Mac answers reads from its cache.
Create one-time, weekly, and countdown alarms with the ID the Mac sends,
so a retried call returns the existing alarm instead of a second one.
A widget extension shows a running timer as a Live Activity with a stop button,
the app lists the alarms that AI apps created and cancels them,
and the phone sends its alarm list to the Mac whenever AlarmKit reports a change.
Answer the Finance tools live and queue account, balance, and transaction
changes for the Mac with FinanceKit history tokens.
A background delivery extension queues changes while the app isn't running.
The code stays inactive until a build carries the FinanceKit entitlement,
which Scripts/install-companion.sh --finance requests;
without it, the Finance tools say why they're unavailable.
Add Alarms, Finance, and Health to the README and its hero image,
describe how to install, pair, and use the companion,
add Scripts/check-companion.py for read-only checks through imcp-server,
and build the companion unsigned in CI.
When the iPhone drops a connection, disconnect the Mac's MCP client,
so pending calls fail over to the cache and syncing resumes on the next connection.
Keep lines that arrive before MCP reads them, end a closed channel's stream
with an error, and enforce read and open time limits.
Reject outbox writes from a sync that a cache reset overtook, run each
service's sync one at a time, and give the FinanceKit reason in cached answers.
The Mac used to send the device key inside the pairing session,
so anyone with the QR secret who recorded that session could recover it.
Now each side sends a one-time X25519 public key, both derive the device key
from the shared secret salted with the pairing key, and each side's proof
covers the public keys so neither can be swapped.
The iOS app is now iMCP on the device and builds for iPhone and iPad.
Targets, folders, and shared code use iOS and Mobile names,
the Mac's Settings pane is iPhone & iPad,
and the Bonjour type, pairing link, and status tool drop the companion name.
The name no longer collides with the separate Companion debugging app
that the README describes.
The macOS 26 runner's Xcode 26.0 has no iOS platform,
so the iOS app's build couldn't find a destination.
Download the platform when it's missing and allow time for the download.
AlarmKit shows its own stop control on the alarm alert,
so the app doesn't need an App Intent for it.
The timer Live Activity now shows the countdown without a stop button.
The phone can dial the Mac from two places at once (the foreground loop and a
background flush). Replacing the live link cancelled the sync in progress and
started the same race again. attach() now keeps the current link for the same
device while it answers a status call within a short time, and replaces it
when it doesn't. A cancelled sync is logged at debug instead of as an error.
The foreground loop, a background flush, and pull to refresh each dialed the
Mac on their own, and the Mac treats two connections from one device as a
conflict. They now join a single dial, and the channel is served by one task
that the loop waits on. Pull to refresh reuses the open connection, retries the
dial now instead of waiting out the backoff, and returns within eight seconds
whatever the Mac or HealthKit is doing. The retry delay tops out at ten seconds,
and the status shows when the phone last connected.
…e phone

Every tool call a client makes (succeeded, failed, or denied) is recorded with
the client, service, tool, whether it writes, and how long it took. The Mac
keeps the last 500 in Application Support, tracks what each paired device has
acknowledged, and pushes the rest over the existing link with a new
activity_sync call. The store opens from disk, so events recorded before a
relaunch reach the phone, and activity syncs before the pull so a short
connection still delivers it.
The phone accepts activity_sync, keeps the events in its own Application Support
folder, and lists them under Activity with a filter for reads, writes, and
denied or failed calls, search by client, service, or tool, and Clear. Unpairing
removes the history, because the next Mac numbers its events again.
iOS kills an app with 0xdead10cc when it is suspended while holding a
SQLite lock on a file in a shared container, and background syncs can be
suspended mid-write. Only the app reads the outbox (the widget extension
reads nothing from the group), so the database now lives in the app's own
Application Support directory. An outbox left in the group container by an
earlier build is checkpointed and moved with its queued batches and
HealthKit anchors. Preferences stay in the group's UserDefaults.
HealthKit wakes and alarm updates synced without an assertion, so iOS
could suspend the app while a sync held the outbox. Every sync, pull, and
acknowledgement now runs inside BackgroundWork, which begins a UIKit
background task and cancels the work if iOS expires it. The outbox
checks for cancellation at the start of its write transaction and rolls
back, so no transaction is open across a suspension.
The pairing code and the Mac's welcome now carry optional Tailscale,
Funnel, and Cloudflare Tunnel endpoints, and MobileTransportMode names
the routes a phone may use. Over a WebSocket, the phone and the Mac agree
a key with X25519, derive directional keys with HKDF<SHA256>, and frame
every message with ChaChaPoly under strictly increasing counters, so a
tunnel only ever sees ciphertext. The Mac advertises its own Tailscale
address and the port its TLS listener last used, takes a typed host
override, and can run a loopback WebSocket listener for a tunnel to
forward to. The advertising hooks for Funnel and for a host that remote
access knows are in place but nothing calls them yet.
The phone saves the routes from the pairing code and the Mac's welcome,
tries them in order, and gives every route but the last a six second
budget so a dead route can't use up the time the next one needs. A mode
that the Mac offered no route for fails with a message that says so
instead of a vague timeout.
The status screen shows which route carries the connection, and a new
Connection Mode screen lists every route. A route that the Mac hasn't
offered an address for is marked unavailable, with the reason, instead
of being left to time out. The addresses the Mac gave the phone can be
edited there.
Oliver Ames added 3 commits November 18, 2026 09:12
Settings shows which route a connected device uses, lets the person limit
the Mac to the local network, turn off Tailscale VPN, type a Tailscale
host, and set up a Cloudflare Tunnel address and the local port the Mac
listens on for it.
The Mac builds a versioned configuration (revision, ordered routes, the mode
it recommends, feature flags) from its settings and live addresses. It sends
the configuration in every welcome, keeps the individual endpoint fields for
older phones, and pushes it with config_apply when its settings change. The
phone's answer records which revision each device applied. The iPhone and iPad
settings pane lists the routes in order, with drag to reorder and a toggle for
each, and shows the revision each phone applied.
The phone keeps the newest configuration the Mac sent, dials its routes in
the Mac's order, and replaces its saved addresses instead of merging, so a
route the Mac stops offering is cleared. config_apply applies a pushed
configuration and answers with the revision held. The Connection Mode screen
shows who configured the phone, the routes in order, and a Refresh
Configuration action.
@oliverames
oliverames marked this pull request as ready for review November 18, 2026 15:09
@oliverames

Copy link
Copy Markdown
Contributor Author

Replaced by #381, the same change cut as one PR so it can merge on its own.

@oliverames oliverames closed this Nov 18, 2026
@oliverames
oliverames deleted the feat/ios-config-from-mac branch November 18, 2026 21:44
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.

2 participants