Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Phone link: an opt-in, local-network server so the Android app can show sessions and answer approvals

Rhytam Biswas0d0a543fade2
diff --git a/docs/ANDROID_LINK.md b/docs/ANDROID_LINK.md
new file mode 100644
index 00000000..4799a447
--- /dev/null
+++ b/docs/ANDROID_LINK.md
@@ -0,0 +1,388 @@
+# Android link (protocol v1)
+
+How *Coucou for Android* talks to a desktop Coucou. The iPhone uses iCloud (CloudKit) and Apple
+push, neither of which exists on Android, so the Android app connects to the desktop directly over
+the local network.
+
+Status: the Android client, `android/tools/dev-desktop.mjs` (a stand-in desktop for testing) and the
+real desktop server of the Windows/Linux app (`windows/src-tauri/src/phone_link/`) implement this.
+The Mac app is left to its author.
+
+## Transport
+
+- TCP, then TLS 1.2 or 1.3. The desktop uses a self-signed certificate it generates once.
+- Newline-delimited JSON (one object per line, UTF-8). A line over 64 KiB is a protocol error.
+- No hostname check and no certificate authority: the phone accepts exactly one certificate, the
+ one whose SHA-256 it got when pairing (certificate pinning).
+- Default port 47821 (any port works; it is in the pairing link).
+
+## Pairing
+
+The desktop shows a QR code (and a copyable link) containing:
+
+```
+coucou://pair?v=1&host=192.168.1.20&port=47821&fp=<sha256 hex of the TLS certificate>&token=<secret>&name=<desktop name>
+```
+
+- `token` is 16 to 128 characters of `[A-Za-z0-9_-]`, random, created per pairing. It is the shared
+ secret; it travels only inside the pinned TLS connection and is stored on the phone encrypted
+ with a key from the Android Keystore.
+- The app can read the QR code itself ("Scan QR code" on the pairing card; CameraX for the preview, zxing-core to
+ decode, no Play services). Scanning the QR with the phone's own camera app also opens the link in the app (the
+ app registers the `coucou://pair` scheme). Either way the app names the computer and asks the user to confirm
+ before it pairs; the link can also be pasted. The camera is used only on the scan screen and nothing is stored or sent.
+- Unpairing on either side deletes the token. The desktop should accept one token per phone and let
+ the user revoke it.
+
+## Messages
+
+Phone to desktop:
+
+| `type` | fields | meaning |
+|---|---|---|
+| `hello` | `v`, `token`, `device` | first message; must match the pairing |
+| `decision` | `fingerprint`, `decision` (`allow` or `deny`) | answer to an approval. No "always" from the phone |
+| `ping` | | keep-alive, every 20 s |
+| `bye` | | courtesy before closing; may be lost |
+
+Desktop to phone:
+
+| `type` | fields | meaning |
+|---|---|---|
+| `welcome` | `v`, `desktop`, `os` | reply to a valid `hello`. The phone refuses a different `v` |
+| `error` | `code`, `message` | `auth` closes the link and the phone stops retrying quickly |
+| `sessions` | `sessions[]` | the full list, replacing the previous one |
+| `approval` | `pillId`, `fingerprint`, `tool`, `command`, `createdAt` (ms), `truncated` (bool, optional) | an agent waits for permission |
+| `approvalResolved` | `fingerprint` | answered elsewhere or timed out; remove it |
+| `pong` | | reply to `ping` |
+
+A session is `{pillId, agent, state, statusText, stepIndex, stepCount, updatedAt}`. `state` is one of
+`idle working thinking searching approval question error finished ratelimit sleeping dizzy`; an
+unknown value is shown as `idle`. `pillId` values come from the pill catalog
+(`windows/src/core/pills.ts`) and are never renamed. Unknown message types are ignored.
+
+## Approvals
+
+- `fingerprint` is the Mac's derivation (`ApprovalRelay.fingerprint`): lowercase hex SHA-256 of
+ `pillId`, `sessionId`, `tool`, `command`, `inputKey` joined by U+001F.
+- On the Windows/Linux desktop `inputKey` is the island's request id, so asking for the same command
+ twice gives two different fingerprints.
+- The desktop applies a `decision` only if its fingerprint matches the approval **still pending**
+ (same session, tool, command and input). A late decision, or one for another command, is ignored.
+- The phone offers an approval for at most 120 s (the desktop dismisses it at 115 s), and sends one
+ decision per request.
+- **Allow requires the user's biometric or screen lock on the phone.** Deny does not. With no
+ screen lock set up, Allow is refused.
+- The command text is hidden on the lock screen.
+- **A command is sent in full up to 500 characters.** A longer one is cut to its first 500 and the approval carries
+ `"truncated": true` (additive: absent means false, and a phone that does not know the field ignores it). The fingerprint
+ is computed over the text as sent. For a truncated approval the phone says "Command is longer than shown", offers
+ **Deny only** (sheet, notification and island), and the request is answered on the computer. The computer enforces it too:
+ an `allow` for a truncated approval is ignored and the request stays pending (a `deny` works as usual).
+
+## Capabilities and chat (optional, still protocol v1)
+
+`hello` may carry `caps`, a list of optional features the phone understands; `welcome` carries `caps` with the
+ones this computer offers **to this phone right now**. A side that sends no `caps` gets none of them, so older
+phones and older computers keep working unchanged (an unknown field is ignored, an unknown message type is ignored).
+The only capability defined so far is `chat`: the phone talks to the AI providers the computer is set up for.
+**The computer's API key never leaves the computer**; the phone sends text and receives text.
+
+The computer offers `chat` only if the user turned "Let the phone chat with my AI providers" on (off by default),
+and re-reads that switch for every message. The user also chooses which provider/model pairs the phone may use.
+
+| Direction | `type` | fields |
+|---|---|---|
+| phone to computer | `chatModels` | none: ask for the allowed list |
+| computer to phone | `chatModels` | `models[]`: `{id: "provider/model", provider, label}`, only what the user allowed |
+| phone to computer | `chatSend` | `id` (1 to 64 chars of `[A-Za-z0-9_-]`, made by the phone), `model` (an `id` from the list), `text` (at most 4000 characters) |
+| computer to phone | `chatDelta` | `id`, `text` appended to the answer (pieces of at most 8 KiB) |
+| computer to phone | `chatDone` | `id`; `text` only if the streamed text must be replaced by this full answer |
+| computer to phone | `chatError` | `id`, `reason`, `message` |
+| phone to computer | `chatCancel` | `id`: stop waiting for this answer |
+| phone to computer | `chatReset` | none: new chat; the computer forgets the conversation and stops a running answer |
+
+- `reason` is one of `off not_allowed busy rate too_long empty no_key unreachable auth provider canceled internal`.
+ `message` is a fixed English sentence written by the computer; a provider's own error text is never sent
+ (some providers echo part of a key in an error).
+- One answer runs at a time (`busy`), at most 12 sends per 10 minutes (`rate`). An answer stops when its phone leaves,
+ when the user turns the switch or the link off, or on `chatCancel`. Stopping cannot undo what a provider already started.
+- A `chatSend` whose id is not valid is ignored (there is nothing to answer to). A phone that did not negotiate `chat` is
+ never sent, and never answered about, any `chat*` message.
+- The computer keeps the conversation in memory only while the switch is on; nothing new is written to disk. The phone
+ sends no files, window context, keys or addresses, and the computer would not accept them.
+- Cloud providers answer all at once (as on the computer's own chat), local models stream.
+
+## Session details (optional capability `details`)
+
+A phone that sends `caps: ["details"]` in its `hello`, while the user has turned on "Show session details on the phone" on the
+computer (off by default; re-read for every connection), is offered `details` in `welcome.caps`. Its `sessions` lines then
+carry these optional fields on each session; any other phone gets the exact v1 fields and nothing else:
+
+| field | meaning |
+|---|---|
+| `steps` | the last steps of the session, oldest first: at most 20, each at most 200 characters, as the island shows them (a file change is its file name). Can include commands. |
+| `finalLine` | the agent's final line after it stopped, at most 200 characters |
+| `project` | the **folder name** the session runs in, at most 64 characters. Never a path (only the last segment survives, on both the island and the link) |
+| `color` | the pill's colour as `#RRGGBB`; anything else is dropped |
+
+The whole `sessions` line stays under 56 KiB: when many sessions carry many steps, the oldest steps are dropped until it fits.
+A field with nothing to say is left out. Turning the switch on or off disconnects the phones once so they reconnect and are told.
+Not sent, ever: the prompt, command output, Claude's full answer, file contents, full paths.
+
+## Answering Claude Code's questions (optional capability `answers`)
+
+A phone that sends `caps: ["answers"]` in its `hello`, while the user has turned on "Let the phone answer Claude Code's
+questions" on the computer (off by default; re-read for every connection), is offered `answers` in `welcome.caps`. Any other
+phone never hears of a question and cannot answer one (its `answer` messages are ignored).
+
+| Direction | `type` | fields |
+|---|---|---|
+| computer to phone | `question` | `pillId`, `fingerprint`, `createdAt` (ms), `questions[]`: `{question, multiSelect, options[]: {label, description}}` |
+| phone to computer | `answer` | `fingerprint`, `picks`: one list of labels per question, in order |
+| computer to phone | `approvalResolved` | `fingerprint`: the question was answered (here or on the computer) or timed out; remove it |
+
+- At most 4 questions of at most 8 options. A question with a longer text (500 characters), a longer label (120) or description
+ (300), no option, or two options with the same label is **not offered** (it stays on the computer): the answer must carry the
+ exact text and labels back to the agent, so nothing is ever cut.
+- `fingerprint` identifies the pending question like an approval's does (derived from the session, the question texts and the
+ island's request id); the request id itself never leaves the computer.
+- The computer applies an `answer` only if its fingerprint is the question **still pending**, it is not older than 115 s, and
+ `picks` matches exactly: one list per question; each label equal to one of that question's labels (exact, case-sensitive);
+ one label for a single choice; one or more distinct labels for a multiple choice. Anything else changes nothing and the
+ question stays open. Applied once, then the island's card closes as if answered there. The agent receives
+ `{question text: label}` (a list of labels for a multiple choice), the same shape the island produces.
+- **The phone asks for its screen lock (fingerprint, pattern, PIN) before it sends an answer**, like Allow. Nothing is
+ logged about what was picked, on either side.
+- A permission request is still sent to every phone as an `approval`, unchanged.
+
+## File changes (optional capability `diffs`)
+
+A phone that sends `caps: ["diffs"]` in its `hello`, while the user has turned on "Show the files an agent changed on the
+phone" on the computer (off by default, a switch of its own; re-read for every connection), is offered `diffs` in `welcome.caps`.
+Any other phone gets the v1 `sessions` line and cannot ask for a diff (its `getDiff` messages are ignored).
+
+**The list.** With `diffs`, a session may carry `files`, at most 20 (the newest), each `{id, name, added, removed}` plus
+`tooLarge: true` (the change is too large to show line by line: counts only) and `isNew: true` (a file that was written whole).
+`name` is the **file name only**: the computer keeps the last segment of the path, cut at 80 characters, and the phone does the
+same again if it is sent more. The line counts toward the 56 KiB budget of a `sessions` line like the details do.
+
+**The lines, on request only.**
+
+| Direction | `type` | fields |
+|---|---|---|
+| phone to computer | `getDiff` | `pillId`, `fileId` (an `id` from the list) |
+| computer to phone | `diff` | `pillId`, `fileId`, `name`, `added`, `removed`, `tooLarge`, `gone`, `truncated`, `part`, `parts`, `lines` |
+
+- `lines` are `[kind, text]`: kind `+` (added), `-` (removed), ` ` (context) or `@` (a hunk starts; the text is `@@ <line>`).
+ An unknown kind is read as context.
+- At most **200 lines** per file, each cut at **400 characters**, sent in **parts of 100 lines** (`part` from 0 to `parts - 1`, at
+ most 2 parts), so no line of the link nears 64 KiB. `truncated: true` says there were more than 200. A diff the island no
+ longer has is answered with `gone: true` and no lines (one part); a change that was `tooLarge` has no lines either.
+- The answer goes to the phone that asked, and only if it still has `diffs`. A phone may ask for at most 20 diffs in 10 seconds.
+- The phone holds the lines in memory while its sheet is open and forgets them when it closes; nothing is stored or logged.
+- Deviation from the plan: the plan said "600 lines in total"; the computer keeps 200 lines per file and the 20-in-10-seconds rate
+ instead, which bounds the same thing (at most 4 000 lines in 10 s) without per-connection bookkeeping.
+
+## Service cards (optional capability `services`)
+
+Read-only cards of the island's service pills (Stripe, GitHub, Vercel, n8n, Resend, Notion, Cal.com). **One tick per service**
+in Settings > Android phone on the computer, none ticked by default; a phone that sends `caps: ["services"]` is offered
+`services` in `welcome.caps` only if at least one service is ticked (re-read for every connection; a change reconnects the phones).
+Each phone is sent only the services ticked, and nothing is sent for the others, not even their names.
+
+```json
+{"type":"services","services":[{"id":"integration_stripe","title":"Stripe","headline":"12.50 EUR","reason":"Payments",
+ "items":[{"label":"Payment","detail":"+9.00 · 2m"}]}]}
+```
+
+Sent after the first `sessions` when there is something to show, and again when the cards of **that phone's** services change.
+An empty `services` list takes the cards away. Limits, kept by the computer and checked again by the phone: only the seven ids above
+(once each), `title`/`headline`/`reason`/`label`/`detail` one line of at most 24/40/80/60/60 characters (80 on the phone), at most
+three `items`. What each card says (and what it never says):
+
+| Service | Headline | Lines | Never sent |
+|---|---|---|---|
+| Stripe | the balance | the last three payments: paid or failed, the amount, how long ago | descriptions, customers |
+| GitHub | total stars | the number of repositories | repository names, links |
+| Vercel | latest deployment ready or failed | project name, ready or failed, how long ago | links, branches |
+| Resend | total emails | delivered or not, how long ago | addresses, subjects |
+| Notion | number of recent pages | the page titles and how long ago | links, content |
+| Cal.com | the next call's date and time | titles and times | attendees, links |
+| n8n | the last workflow's result | its name | the error text |
+
+Nothing in a card can be acted on, and nothing goes back: there are no actions on any service from the phone.
+
+## Plan usage (optional capability `usage`)
+
+A phone that sends `caps: ["usage"]` in its `hello`, while the user has turned on "Show my plan usage on the phone" on the
+computer (off by default, a switch of its own; re-read for every connection), is offered `usage` in `welcome.caps`. It is then
+sent, right after the first `sessions` and again whenever a number changes, what the island's Claude and Codex pills show:
+
+```json
+{"type":"usage",
+ "claude":{"fiveHour":{"pct":42,"resetsAt":1900000000000},"sevenDay":{"pct":7,"resetsAt":1900500000000},"plan":"max","updatedAt":1899999990000},
+ "codex":{"sevenDay":{"pct":100,"resetsAt":1900500000000},"resetCredits":2,"plan":"plus"}}
+```
+
+`pct` is a whole percent 0..100 (rounded and clamped by the computer), `resetsAt` epoch milliseconds, `plan` a short name (letters,
+digits, spaces and dashes, 20 characters at most), `resetCredits` Codex's free resets (0..99). A plan with no usable window is left
+out. A bare `{"type":"usage"}` means the computer has nothing to say any more: the phone removes the panel. A window whose
+`resetsAt` has passed counts as 0 on the phone, as on the PC. Nothing else about the plans (no account, no token, no cost) is
+ever sent, and nothing goes back.
+
+## Admission (what a flood cannot do)
+
+The server answers the local network before it knows who is calling, so it bounds what a caller who has not yet sent
+a valid `hello` can hold (`phone_link/admission.rs`, pure bookkeeping with unit tests):
+
+- one source address may hold at most **2** connections that have not said a valid hello;
+- addresses that never authenticated (strangers) share **4** such connections between them, so at least half of the 8
+ slots stay free for a phone the computer already knows;
+- an address that sent a valid hello is remembered, in memory only (8 addresses, never written to disk), and is not
+ held to the stranger pool: the paired phone can always reconnect, even during a flood from other addresses;
+- when the pool is getting full, the TLS handshake and the hello get 3 s instead of 10 s, so silent connections free
+ their slots quickly;
+- a slot is given back whenever the connection ends, however it ends.
+
+What it does not do: a device that floods from many addresses at once can still keep a *new, never-paired* phone out
+for a few seconds at a time; it cannot keep out the phone that is already paired. A wrong token still costs the caller
+a pause and is never admitted.
+
+## Mochi's outfit (optional capability `prefs`)
+
+A phone that sends `caps: ["prefs"]` in its `hello` is offered `prefs` in `welcome.caps` (no switch on the computer: what
+Mochi wears is no secret and says nothing about the user's work). It is then sent what the island's wardrobe says, right
+after the first `sessions` and again whenever it changes:
+
+```json
+{"type":"prefs","outfit":"beanie"}
+```
+
+`outfit` is one of `auto`, `none`, `partyHat`, `beanie`, `crown`, `sunglasses`, `roundGlasses`, `bow`, `scarf`, `witchHat`,
+`pumpkin`, `santaHat`, `bunnyEars`: the PC's and the Mac's stored values, nothing else is ever sent (the computer checks the
+list; a test compares it with `windows/src/mochi/wardrobe.ts`). `auto` means "dress for the season": **the phone applies the
+seasons to its own calendar**, the computer sends no date. A phone ignores a value it does not know and keeps what it wore.
+The phone has its own choice too (Settings > Mochi's wardrobe): "Same as my computer" (default) or one outfit, which then wins.
+Nothing goes back to the computer.
+
+## Finding the computer again (optional, still protocol v1)
+
+The pairing link holds the computer's address, and an address changes with every network (a home Wi-Fi, a hotspot, a
+new router). So the computer can also announce itself on the local network, and the phone can find it there. This is
+an addition: **v=1 is unchanged, the saved address stays the first thing tried, and an old phone or an old computer
+simply keeps using the saved address.**
+
+- **Announcement** (computer): while the phone link is on, DNS-SD over multicast DNS, service type `_coucou._tcp`,
+ instance name = the computer's name, the real port, IPv4 address. Off means silent: when the switch is turned off, the
+ link stops or the app quits, the announcement is withdrawn and nothing runs.
+- **TXT record**: `v=1` and `fp=<first 16 lowercase hex characters of the certificate's SHA-256>`. Nothing else. Never the
+ token, never the pairing link, never a user name or a path. The certificate is public by nature (every peer that connects
+ receives it), so its short id is not a secret, and it is **a hint, not a credential**.
+- **Phone**: the framework's `NsdManager` (no library). It searches only when it has a paired computer, a Wi-Fi or cable is
+ up and the link is not connected; it holds a multicast lock only while searching.
+ 1. The saved address is tried first and gets 2 s to accept the TCP connection.
+ 2. After that failure the network is searched for up to 15 s. Between searches it waits 20 s, 60 s, 3 min, then 5 min;
+ a network change (`ConnectivityManager` callback) starts a search at once and resets the waiting. No Wi-Fi: no search.
+ 3. A service is a candidate only if its `fp` equals the first 16 characters of the **paired** certificate fingerprint and its
+ `v` is `1` (or absent), and its address is on the local network. The name and the address never count.
+ 4. A candidate is then checked with a bare TLS handshake against the **full** pinned fingerprint. The probe takes no
+ token: nothing secret can be sent to it. Only a certificate that matches is accepted; one that does not (a lookalike
+ that copied the short id) is dropped and never saved. When the paired fingerprint is announced twice, the first that
+ passes wins.
+ 5. The stored host and port are replaced; the token and the pinned fingerprint are untouched. The link reconnects.
+- If nothing is found, the phone says so calmly (same Wi-Fi? computer awake and Coucou running? firewall? hotspots and guest
+ networks can block devices from finding each other, "client isolation") and offers to pair again or to type the address.
+- Limits, honestly: multicast does not cross routers or VPNs; some access points block it between clients; a firewall that
+ blocks UDP 5353 on the private profile hides the computer (the Windows prompt "allow Coucou on private networks" covers
+ it); two computers with the same certificate do not exist (each has its own).
+
+## Behaviour rules (same as the other ports)
+
+- Never block the agent: if the phone does not answer, the desktop's own approval stays usable.
+- No telemetry. The only network traffic is between the phone and its paired desktop.
+- The desktop link is **off by default** and opt-in in settings. It should listen only while it is
+ on, and only to the local network.
+
+## Windows/Linux implementation notes
+
+- Settings → Android phone: off by default (`phoneLink` in settings.json, owned by Rust: the webview
+ cannot switch it on). While off, nothing listens, nothing is published and no timer runs.
+- It listens on `0.0.0.0` (port 47821, else any free port) but drops every peer that is not on the
+ local network (private, loopback, link-local). At most 8 connections; 10 s to say hello (3 s when the pool is
+ filling up); 20 min idle (a sleeping phone cannot ping every 20 s, see "Keeping the link alive"). Unauthenticated connections are limited, see "Admission" below.
+- The certificate (ECDSA P-256, self-signed) is generated once; its key and the pairing token live in
+ the OS keystore (Credential Manager / Secret Service) and nowhere else. Without a keystore the link
+ does not start.
+- One token at a time: "Pair again" replaces it and disconnects the phone that had the old one. The
+ pairing code is shown only after a click, and only to the settings window.
+- Chat (Settings → Android phone → "Let the phone chat with my AI providers"): off by default, owned by Rust like
+ `phoneLink` (`phoneChat`, `phoneChatModels` in settings.json; the webview cannot change them). The user ticks the
+ provider/model pairs the phone may use (a provider's model list is asked for only when its "Choose models" button is
+ pressed). Turning the switch on or off disconnects the phones once so they reconnect and learn about the capability;
+ turning it off also stops a running answer and forgets the phone's conversation. The phone's conversation is a
+ separate in-memory `Chat`, not the island's. The provider code is the island's (`chat::send_for_phone`); a provider's
+ error text is never forwarded or logged, only a kind (no key, unreachable, auth, provider).
+- Permission requests (Allow/Deny) go to every phone. A question from Claude Code goes only to a phone with the `answers`
+ capability (Settings → Android phone → "Let the phone answer Claude Code's questions", off by default); otherwise its
+ options are picked on the island.
+- New crates: `mdns-sd` (+ `flume`, `if-addrs`, `socket-pktinfo`, `spin`; default features off, so no async runtime or logger) announces the computer on the local network while the link is on (`phone_link/discovery.rs`); `rcgen` (+ `yasna`) makes the certificate once, `qrcode` draws the pairing QR; `rustls`,
+ `tokio-rustls` and `ring` were already in the dependency tree (through `reqwest`) and are now named
+ directly. Hashing, randomness and the constant-time comparison use `ring`; no other crate.
+
+## Android notes
+
+- Android 16 asks for local network access the first time the app connects.
+- A foreground service keeps the link alive in the background so approvals arrive as notifications.
+- The app needs Android 11 or later (API 30) for the combined biometric / screen-lock prompt.
+
+## Testing
+
+- `android/tools/dev-desktop.mjs` pretends to be a desktop (needs `node` and `openssl`). With `--fake-chat` it offers
+ `chat` with a fake provider (no key, no cost): `/error`, `/auth`, `/slow`, `/long` and `/rewrite` trigger the odd cases.
+- `DevDesktopInteropTest` runs the Android client against it.
+- `cargo test -p coucou phone_link` also tests the announcement (what is published and when, that no secret can be in it); the real multicast needs a real network and is not in the tests.
+- `cargo test -p coucou phone_link` tests the real server (wrong token, fingerprint mismatch, oversize
+ line, late decision, answered-at-the-desk, pairing again, local-network filter...).
+- `RustDesktopInteropTest` runs the Android client against the real Rust server
+ (`COUCOU_RUST_INTEROP=1`, needs cargo; the `Phone link` workflow does it).
+
+## Through a relay (optional capability `relay`)
+
+When the user turns on "Away from home Wi-Fi" in Settings > Android phone, the pairing link carries four more fields
+(`relay`, `room`, `key`, `access`) and a phone that sends `caps: ["relay"]` is offered `relay` in `welcome.caps` (re-read for
+every connection). The conversation itself is unchanged and runs inside an end-to-end encrypted channel through the user's own
+relay; the wire is in `docs/RELAY_LINK.md`. When the user replaces the relay's access key, each phone that negotiated `relay`
+is sent `{"type":"relayAccess","access":"<43 base64url characters>"}` and follows the new key. A phone that did not negotiate
+`relay` is never sent it.
+
+## Keeping the link alive while the phone sleeps
+
+What actually happens when the screen is off, as found and fixed (Galaxy A12s, Android 13):
+
+- **A foreground service keeps the process alive, not the connection.** `LinkService` is what stops Android from killing the app, but
+ the app's own timers (the 20-second ping, every timeout) are stopped with the CPU in Doze, and the network of an app that is not
+ exempt from battery optimisation is restricted while the phone is idle. So the phone could not ping, the computer (which allowed only 90 s of
+ silence) closed the connection, and the phone found out only when it woke up and sent something: a new connection from the phone's
+ address at wake time.
+- **The computer is more patient**: an authenticated phone may be silent for 20 minutes (`IDLE_TIMEOUT` in `server.rs`). A conversation
+ whose phone disappeared without saying goodbye (its address changed) holds one of the 8 places until then.
+- **The phone has a heartbeat that works in Doze**: an alarm every 4 minutes (`AlarmManager.setAndAllowWhileIdle`, no exact-alarm
+ permission). Android may run it later (about every 9 minutes in Doze, or in a maintenance window), never more often. Each time, the
+ app asks the computer for a pong and drops the connection (so it reconnects) if nothing comes within 8 s, or reconnects at once if the
+ link was down. The check holds a wake lock for at most 15 seconds, only so the question and its answer can cross; nothing is held between checks.
+- **Other triggers**, all through one rule table (`ReconnectPolicy`): the screen turning on or the phone being unlocked, a new
+ default network (Wi-Fi joined, Wi-Fi to mobile data), and the connection dying (the usual reconnect with backoff). Connected: ask for a
+ pong. Not connected: reconnect now, if there is a network to use.
+- **What is not possible**: while Doze restricts the network of an app that is *not* exempt, nothing can reach or leave the app until the
+ next maintenance window, whatever the app does. The only reliable fix is the user's: set the app's battery usage to **Unrestricted** (on
+ Samsung also: not in Sleeping apps or Deep sleeping apps). The app suggests it, calmly, only after a connection that ended on its own after
+ the screen had been off, and only opens Android's screen: it cannot change the setting itself and does not ask for the permission that
+ would allow a one-tap request (Google restricts it on its store). Push notifications (FCM) would work without this setting, but need Google's
+ servers and a Google account of the app; they are not used (decision D6 of the relay plan).
+- Home says what happened ("Connection lost 2 min ago, reconnecting", and why: the computer stopped answering / closed the connection /
+ the network dropped). **Settings > Computer > "Can't connect?"** checks, in order, the phone's network, the saved address, whether the
+ computer announces itself, the pinned certificate, the pairing code and version, and the relay if the pairing has one. Its copyable
+ report names the checks and what they found, and never contains the pairing code, the certificate fingerprint, the computer's name or
+ the full address.
+
diff --git a/docs/RELAY_DEPLOY.md b/docs/RELAY_DEPLOY.md
new file mode 100644
index 00000000..d7a286eb
--- /dev/null
+++ b/docs/RELAY_DEPLOY.md
@@ -0,0 +1,122 @@
+# Deploying the relay, and trying it with the phone on mobile data
+
+This is the guide for **you** (the person who runs the computer and the phone). It takes about 15 minutes. Nothing here is
+published anywhere: the relay is a small program you put on your own Cloudflare account, and only you hold its key.
+
+Why a relay at all: on your home Wi-Fi the phone talks to the computer directly. Away from home it cannot, so both sides
+connect *out* to a relay on the internet that passes encrypted messages between them. The relay cannot read them
+(wire details: `docs/RELAY_LINK.md`, reasoning and threats: `android/RELAY_PLAN.md`, `android/RELAY_THREAT_CHECK.md`).
+
+You need: a free Cloudflare account, Node 22 or newer on the computer, this repository, and a phone with a debug build of
+Coucou for Android (`cd android && ./gradlew assembleDebug`, then `adb install -r app/build/outputs/apk/debug/app-debug.apk`).
+
+## 1. Deploy the relay
+
+```
+cd android/relay
+npm install
+export WRANGLER_SEND_METRICS=false # optional: Wrangler is Cloudflare's tool and may send anonymous usage statistics
+npx wrangler login # opens a browser; sign in to your Cloudflare account
+```
+
+Make the **access key**, a random 43-character secret that lets a request create or join rooms on *your* relay. Write it down
+somewhere safe; you will paste it into the computer's settings:
+
+```
+openssl rand -base64 32 | tr '+/' '-_' | tr -d '='
+```
+
+Store it on the relay as a secret (this prompts for the value; it is never written to a file or to git), then deploy:
+
+```
+npx wrangler secret put ACCESS_KEY # paste the key when asked
+npx wrangler deploy # prints https://coucou-link.<your-name>.workers.dev
+curl https://coucou-link.<your-name>.workers.dev/ # must print: Coucou link relay
+```
+
+Notes:
+
+- If `deploy` complains about the `[[ratelimits]]` block, delete that block from `android/relay/wrangler.toml` and deploy again:
+ the relay works without it (it only limits new connections per address).
+- In the Cloudflare dashboard, open the Worker `coucou-link` and check that **Observability / Logs are off**. The relay logs
+ nothing and has nothing worth logging, but this is the one place a setting could differ from the file.
+- `wrangler.toml` contains no secret. Never add the access key to it, to `.dev.vars`, or to any file you commit.
+
+## 2. Set up the computer (Windows or Linux)
+
+1. Settings > **Android phone**. Turn **Phone link** on.
+2. In the block **Away from home Wi-Fi**:
+ - **Relay address**: `wss://coucou-link.<your-name>.workers.dev` (it must start with `wss://`), press **Save address**.
+ - **Relay access key**: paste the key from step 1, press **Save key**. The field empties; the key is kept in the system keystore
+ and is never shown again.
+ - Turn **Away from home Wi-Fi** on.
+3. The status under it should read **Connected to the relay, waiting for the phone.** Other messages and what they mean are in
+ section 6.
+4. Press **Show pairing code**. The code now also carries the relay's host (a line says so) and an end-to-end key made for this
+ pairing.
+
+If you change the address or the key later, press **Show pairing code** again and scan the new code with the phone.
+
+## 3. Pair the phone (the real test: mobile data, not Wi-Fi)
+
+1. On the phone, **turn Wi-Fi off** (mobile data only) and make sure the data connection works.
+2. Open Coucou for Android, scan the code on the computer's screen (the camera does not need a network). The confirmation names
+ the computer **and the relay's host**: check that it is yours, then pair.
+3. Within a few seconds Home should show the computer as connected, and Settings > **Away from home Wi-Fi** should say
+ **Connected through your relay (coucou-link...)**. The computer's block says **The phone is connected through the relay.**
+
+If it does not connect, go to section 6 before anything else.
+
+## 4. The checklist (PC on home Wi-Fi, phone on mobile data)
+
+Tick each line and note anything odd. "Expect" is what should happen.
+
+| # | Do | Expect |
+|---|---|---|
+| 1 | `curl` the relay address | `Coucou link relay` |
+| 2 | Computer: relay on | `Connected to the relay, waiting for the phone.` |
+| 3 | Phone on mobile data: scan, pair | Connected, card says **through your relay** |
+| 4 | Start an agent on the computer | Its session appears on the phone |
+| 5 | Trigger a permission request | The sheet appears. **Deny** works at once. **Allow** asks for the fingerprint or screen lock, then the agent goes on |
+| 6 | Tap the same decision twice, quickly | The second one is ignored |
+| 7 | Leave a request unanswered for 2 minutes | It expires on both sides; a late tap is refused |
+| 8 | Phone back on the home Wi-Fi | Within about a minute the card says **Connected directly**; leave again and it goes back to the relay |
+| 9 | Put the computer to sleep for a minute, wake it | Phone shows the computer offline, then recovers by itself |
+| 10 | Computer: change the relay address to something wrong | Status says the relay cannot be reached; **the agents are never delayed**; at home the direct link still works |
+| 11 | Computer: **Pair again** | The phone is cut off at once and must scan the new code; the old pairing cannot reconnect |
+| 12 | Make a new access key, `npx wrangler secret put ACCESS_KEY`, paste it in the computer's **Relay access key**, Save | New connections with the old key are refused. A phone that is connected **follows the new key by itself** (it is sent inside the encrypted channel); a phone that was offline needs a new scan |
+| 13 | `npx wrangler tail` while an agent works | Connections only, **no readable content** (there is none to show) |
+| 14 | Phone on mobile data, screen off, not moving, **30 minutes** | Does an approval still arrive? (Doze and the carrier decide; this is the one result I cannot predict) |
+| 15 | Overnight battery: before, `adb shell dumpsys batterystats --reset`; after, `adb shell dumpsys batterystats --charged com.coucou.android` | Note the percentage used and tell me |
+
+## 5. Rotating, losing a phone, switching off
+
+- **A phone is lost or stolen:** on the computer press **Pair again** (a new key and a new room; the old phone can no longer read
+ or send anything). That phone also still holds the relay's access key, which only lets someone use your free quota, not read
+ anything. If you want to cut that too, rotate the access key (row 12 above).
+- **The access key leaked:** rotate it (row 12). It protects your quota, not your data.
+- **Stop using the relay:** turn **Away from home Wi-Fi** off on the computer. Nothing connects out any more. To remove the relay
+ entirely: `cd android/relay && npx wrangler delete`.
+- **Free tier:** Cloudflare's current limits are on their pages (I wrote them down from memory, check). If the daily quota runs out,
+ the phone keeps working on the home network and the card says the relay is unreachable; nothing is lost because nothing is
+ stored. A paid Workers plan removes the cap.
+
+## 6. When the status line is not green
+
+| Computer says | Phone card says | What to check |
+|---|---|---|
+| **The relay refused the access key** | Check it in Settings on your computer | The key pasted on the computer is not the one stored with `wrangler secret put`. Paste again; Save key |
+| **The relay cannot be reached. Trying again.** | Cannot reach the relay | Wrong address, no internet, or Cloudflare unreachable. The address must be `wss://` and nothing else |
+| **This pairing is in use somewhere else. Press Pair again.** | This pairing is in use somewhere else | A second copy of the computer app with the same pairing, or someone holds the room. Press **Pair again** |
+| **The relay is limiting connections from here** | The relay is limiting connections for now | Too many connection attempts from this address in a minute; it retries by itself |
+| Connected, waiting for the phone | Your computer is not answering through the relay | The computer is asleep, the app is closed, or its relay switch is off |
+
+The phone's card says **This pairing has no relay** when the code was made before the relay was switched on: switch it on, show
+the code again, and scan it.
+
+## 7. What I could not test for you
+
+Doze and carrier behaviour on a real phone, real battery cost, the real Cloudflare free-tier limits and the hibernation timing
+in production (the tests run the real Worker code locally under `wrangler dev`, end to end with the Rust computer and the Kotlin
+phone, but not on Cloudflare's network), and the Android screens' appearance (Compose and lint run in CI only). Rows 14 and 15
+above, and a first look at the Settings card, are what is missing.
diff --git a/docs/RELAY_LINK.md b/docs/RELAY_LINK.md
new file mode 100644
index 00000000..15008161
--- /dev/null
+++ b/docs/RELAY_LINK.md
@@ -0,0 +1,183 @@
+# Relay link (protocol v1 over the internet)
+
+How *Coucou for Android* and a desktop Coucou talk **through a relay** when they are not on the same network. This is
+the wire specification; the reasoning, threats and stages are in `android/RELAY_PLAN.md`. The direct LAN link
+(`docs/ANDROID_LINK.md`) is unchanged and stays the fast path. **Status: the computer side is built (stage R3, `windows/src-tauri/src/phone_link/relay_client.rs`); the phone side is built too (stage R4, `android/app/.../link/WebSocket.kt`, `RelayLink.kt`, `Transport.kt`).** Fixed test vectors for everything below are in `android/relay/test-vectors.json`
+(generated by `android/relay/tools/gen-vectors.mjs`).
+
+The relay is a small stateless forwarder that the user deploys on their own Cloudflare account. It forwards opaque frames
+between exactly two peers, a computer (role `pc`) and a phone (role `phone`), and never sees a content key. Every
+protocol v1 message (`hello`, `welcome`, `sessions`, `approval`, `decision`, `chat*`, …) travels **inside** an
+end-to-end encrypted channel exactly as it travels over TLS on the LAN.
+
+## 1. Secrets, and who holds what
+
+| secret | size | made by | held by | relay sees it? |
+|---|---|---|---|---|
+| **K**, the pairing key | 256 bits | the computer, at pairing | computer (OS keystore), phone (Keystore-encrypted) | **never** |
+| **access key** | 256 bits | the user, once, at deploy time | the relay (a Worker secret), the computer (OS keystore), the phone (Keystore-encrypted) | yes: it only lets a request create or join rooms |
+| room id | 128 bits | the computer, at pairing | all three | yes (it is the address) |
+| `K_join` (derived from K) | 256 bits | both sides | both sides; the relay sees only that value in the join header | yes, but it is a one-way derivation and cannot decrypt anything |
+
+The access key gates **use of the relay** (and of the user's free quota). It protects no content. K protects content.
+
+## 2. Pairing link
+
+The existing link gains optional fields (an older phone ignores unknown keys and pairs over the LAN only):
+
+```
+coucou://pair?v=1&host=…&port=…&fp=…&token=…&name=…&relay=<wss URL, percent-encoded>&room=<22 chars>&key=<43 chars>&access=<43 chars>
+```
+
+- `relay`: `wss://` URL of the relay, no path, no query, no credentials. The phone shows its host in the confirmation.
+- `room`: 16 random bytes, base64url without padding (22 characters).
+- `key`: K, 32 random bytes, base64url without padding (43 characters).
+- `access`: the access key, 32 bytes, base64url without padding (43 characters).
+- All of `relay`, `room`, `key`, `access` are present together or not at all.
+
+## 3. Connecting to the relay
+
+```
+GET wss://<relay>/v1/room/<room>?role=pc|phone
+Authorization: Bearer <access key, base64url>
+Sec-WebSocket-Protocol: coucou.v1, coucou.join.<K_join, base64url>
+```
+
+- The relay refuses, **before it creates or contacts any room**, a request whose path is not `/v1/room/` plus exactly 22
+ base64url characters, whose `role` is not `pc` or `phone`, or whose `Authorization` does not carry the access key.
+ The check is a constant-time comparison of SHA-256 digests. **If the relay has no access key configured it refuses every
+ room request (fail closed).** Refusals are `404` (bad path), `401` (access key) or `429` (rate limit); the body is empty.
+- `GET /` answers `200` with the text `Coucou link relay` and needs no key.
+- The client offers both sub-protocols (a strict client requires the server to choose one it offered); the relay accepts the
+ upgrade and answers with `Sec-WebSocket-Protocol: coucou.v1`. A request whose `coucou.join.` value is missing or is not 43
+ base64url characters is refused with `400` before any room is touched.
+- **Join proof, in memory only.** The first live socket of a room records `SHA-256(K_join)` in its WebSocket attachment
+ (hibernation state, not storage). Later sockets of that room must present a `K_join` that hashes to the same value or are
+ closed with `1008 join proof`. When the room is empty the record is gone.
+- **Slots.** One live socket per role. A new socket for a role that already has one (with a valid join proof) replaces the
+ old one, which is closed with `1000 replaced`. One phone per room.
+- **Limits.** A frame is at most 66,000 bytes (larger: close `1009`). Per room, a token bucket of 30 messages/s sustained,
+ burst 60 (over: close `1008 rate`). Per source address, a limit on new connections at the Worker (`429`).
+- **No buffering.** A frame for an absent peer is dropped and the sender receives the text message `{"peer":"offline"}`.
+- **Hints.** When the other role joins or leaves, the relay sends the remaining socket a text message
+ `{"peer":"online"}` or `{"peer":"offline"}`. Hints are for the status line and the phone's retry; **they are never
+ trusted for anything else** (they are not authenticated).
+- **Keep-alive.** A client may send the **text** message `ping`; the platform answers `pong` itself
+ (`setWebSocketAutoResponse`), without waking the room, so heartbeats cost almost nothing. These are the only text messages a
+ client may send; any other text message closes the socket with `1003`. The relay has **no idle timer** (a timer would wake the
+ room): liveness is judged by the clients, from the encrypted v1 `ping/pong` and from these `pong`s.
+- **Access key rotation takes effect on live rooms.** Each socket's attachment keeps the first 8 bytes of
+ `SHA-256(access key)` it was admitted with; when the next frame arrives and the current key's digest differs, the relay
+ closes the socket with `1008 access key changed`.
+- The relay logs nothing (observability off), stores nothing (no storage API is used) and holds no key for any content.
+
+## 4. Derived values
+
+HKDF-SHA-256 (RFC 5869), empty salt unless stated, `L` = output length. `LABEL = "coucou-relay/v1"`.
+
+```
+K_auth = HKDF(ikm=K, salt="", info=LABEL + " auth", L=32)
+K_join = HKDF(ikm=K, salt="", info=LABEL + " join", L=32)
+session = HKDF(ikm=K, salt=N_phone ‖ N_pc, info=LABEL + " session", L=64)
+k_p2h = session[0..32] key for frames phone → computer
+k_h2p = session[32..64] key for frames computer → phone
+```
+
+`N_phone` and `N_pc` are 16 random bytes each, fresh for every connection. `‖` is concatenation. Strings are UTF-8, the
+room is the 22 ASCII characters of the URL.
+
+## 5. Frames
+
+Every WebSocket **binary** message is one frame:
+
+```
+ver (1 byte = 1) ‖ type (1 byte) ‖ counter (8 bytes, big endian) ‖ body
+```
+
+| type | name | sent by | body | counter |
+|---|---|---|---|---|
+| 1 | `init` | phone | `N_phone` (16) ‖ `HMAC-SHA256(K_auth, "init" ‖ room ‖ N_phone)` (32) | 0 |
+| 2 | `accept` | computer | `N_pc` (16) ‖ `HMAC-SHA256(K_auth, "accept" ‖ room ‖ N_phone ‖ N_pc)` (32) | 0 |
+| 3 | `data` | either | `AES-256-GCM(key, nonce, aad, padded line)` = ciphertext ‖ 16-byte tag | 0, 1, 2, … per direction |
+
+### Handshake
+
+1. The phone connects and, on every (re)connection and whenever it hears `{"peer":"online"}` without an open session, sends `init`.
+2. The computer checks the MAC with `K_auth`, creates a fresh `N_pc`, derives the session keys and answers `accept`.
+ Only the newest `init` is answered; a computer that gets a new `init` drops its previous session.
+3. The phone checks that the `accept` MAC covers **its current** `N_phone` (so a recorded `accept` is useless), derives the same
+ keys and may send `data` frames. The first valid `data` frame from the phone proves to the computer that the phone holds K.
+4. Inside the channel the ordinary v1 `hello`/`welcome` follow (token, protocol version, `caps`).
+5. A wrong MAC, a malformed frame or an unexpected type before the handshake ends is ignored; after 3 bad handshake frames the
+ computer stops answering `init` for 10 s.
+
+### Data frames
+
+- **Plaintext** = `u32 big-endian length` ‖ the v1 line (UTF-8 JSON, **without** the newline, at most 65,536 bytes) ‖ zero bytes,
+ so that the plaintext length is a multiple of 128 and at least 128. The receiver reads the length, takes that many bytes,
+ and requires the rest to be zeros. (The padding hides whether a frame is a ping or an approval.)
+- **Nonce** (12 bytes) = `direction (1 byte) ‖ 0x00 0x00 0x00 ‖ counter (8 bytes, big endian)`, with direction `1` for
+ phone → computer and `2` for computer → phone.
+- **AAD** = `LABEL ‖ room ‖ direction (1 byte) ‖ ver ‖ type ‖ counter (8 bytes)`.
+- **Counters** start at 0 in each direction of each session. The receiver accepts a data frame **only if its counter is exactly
+ the previous accepted counter plus 1** (0 for the first). A repeat, a gap, a jump back or a jump forward is a fault.
+- **Faults** (bad tag, bad header, wrong counter, bad padding, oversize): the receiver closes the session, discards the keys,
+ and the phone starts again from step 1. No error text is sent to the peer.
+- A session ends at counter 2^32 − 1 (the frame with that counter is the last one); the sender re-handshakes before sending more.
+
+### Why a (key, nonce) pair never repeats
+
+1. The two directions use **different keys** (`k_p2h`, `k_h2p`) **and** different direction bytes in the nonce, so even a bug that
+ made them share a key could not make a nonce collide across directions.
+2. Within a direction the counter strictly increases by 1, and the sender refuses to wrap (the session ends first).
+3. Every connection derives new keys from fresh random nonces, so a restart or reconnect (counter back to 0) is a new key.
+ Random 128-bit nonces are used for this; a collision would need ~2^64 sessions.
+
+Required tests (R2, both Rust and Kotlin; done in `phone_link/relay_crypto.rs` and `link/RelayCryptoTest.kt`): `mustRefuse`, `mustRefuseInOrder` and `data` vectors of `test-vectors.json`;
+a property test that enumerates (key, nonce) over thousands of frames in both directions and two sessions and finds no
+duplicate; a test that a sender at counter 2^32 − 1 refuses to send; a test that two sessions with different nonces have
+different keys.
+
+## 6. Where protocol v1 plugs in
+
+The computer feeds decrypted lines (adding `\n`) to the same server code that handles a LAN connection, and sends the lines
+it produces back through `data` frames. The phone's `LinkClient` reads and writes the same lines. Nothing in v1 changes:
+fingerprints, 120 s offers, decide-once, per-feature switches and the biometric gate behave as on the LAN.
+
+One additive v1 message is defined for rotation (section 7), offered as the capability `relay`:
+
+| direction | `type` | fields | meaning |
+|---|---|---|---|
+| computer → phone | `relayAccess` | `access` (43 base64url characters) | the new access key, sent inside the authenticated channel (over the LAN or the relay) |
+
+The phone replaces its stored access key (Keystore-encrypted) and reconnects. A phone that did not negotiate `relay`
+is never sent it.
+
+## 7. Rotation and revocation
+
+| what | how | effect |
+|---|---|---|
+| **Access key** | `openssl rand -base64 32 \| tr '+/' '-_' \| tr -d '='` → `npx wrangler secret put ACCESS_KEY`, then paste the same value into the computer's setting | New connections with the old key are refused (`401`); live sockets are closed at their next frame (section 3). The computer sends `relayAccess` to paired phones so they follow without scanning again; a phone that was offline at that time re-scans or is sent it when it next connects over the LAN. |
+| **K and the room** (“Pair again”) | the computer makes a new K and room id | The old room stays empty forever; the old phone cannot read or write anything new. A stolen or lost phone is cut off this way. |
+| **A phone leaving** (“Disconnect this computer”) | the phone deletes K, access key and token | The pairing is gone on the phone; the computer can “Pair again”. |
+
+The access key can be rotated as often as the user likes: it protects the quota, not the content.
+
+## 8. What each party can learn
+
+| party | can see | cannot see |
+|---|---|---|
+| relay (user's account) and Cloudflare | IP addresses, that a pairing exists (stable room id), when each side is online, frame sizes (padded to 128) and timing | any content, K, tokens, sessions, commands, paths, approvals, chat |
+| someone with the access key only | nothing about any room; can use the user's quota | any content |
+| someone with the room id only | nothing | any content; cannot join a live room without `K_join` |
+| someone with K and the room id | everything of that pairing, until “Pair again” | other pairings |
+
+## 9. Known limits
+
+- No forward secrecy: session keys come from K and the nonces only (decision D3 of the plan). A later leak of K would let
+ someone decrypt traffic they had recorded.
+- The relay can delay, drop or cut frames. It can never forge one. Dropping a decision leaves the approval to expire on the
+ computer, which is not an allow.
+- An attacker who knows both the access key and a room id could occupy an empty room before its owner connects (the join
+ proof is not stored); the owner sees “room is taken” and does “Pair again”.
+- Free-tier quota can be exhausted by anyone who holds the access key.
diff --git a/windows/Cargo.lock b/windows/Cargo.lock
index 24ec8234..362f3b56 100644
--- a/windows/Cargo.lock
+++ b/windows/Cargo.lock
@@ -613,10 +613,16 @@ name = "coucou"
version = "0.3.0"
dependencies = [
"dbus",
+ "futures-util",
"gtk",
"keyring",
"libc",
+ "mdns-sd",
+ "qrcode",
+ "rcgen",
"reqwest 0.12.28",
+ "ring",
+ "rustls",
"serde",
"serde_json",
"tauri",
@@ -625,6 +631,9 @@ dependencies = [
"tauri-plugin-global-shortcut",
"tauri-plugin-single-instance",
"tokio",
+ "tokio-rustls",
+ "tokio-tungstenite",
+ "webpki-roots",
"webview2-com",
"windows 0.61.3",
"windows-core 0.62.2",
@@ -755,6 +764,12 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "data-encoding"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+
[[package]]
name = "dbus"
version = "0.9.12"
@@ -1130,6 +1145,15 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "flume"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
+dependencies = [
+ "spin",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1893,6 +1917,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -2238,6 +2272,20 @@ dependencies = [
"web_atoms",
]
+[[package]]
+name = "mdns-sd"
+version = "0.21.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "127d3355da0615643c88c885e29a1ccb29ca4b1ca1f2e44b3caed2e728a796aa"
+dependencies = [
+ "fastrand",
+ "flume",
+ "if-addrs",
+ "mio",
+ "socket-pktinfo",
+ "socket2",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -2286,6 +2334,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
+ "log",
"wasi",
"windows-sys 0.61.2",
]
@@ -2974,6 +3023,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
[[package]]
name = "quick-xml"
version = "0.42.0"
@@ -3067,10 +3122,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
- "rand_chacha",
+ "rand_chacha 0.3.1",
"rand_core 0.6.4",
]
+[[package]]
+name = "rand"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
+dependencies = [
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.5",
+]
+
[[package]]
name = "rand"
version = "0.10.3"
@@ -3092,6 +3157,16 @@ dependencies = [
"rand_core 0.6.4",
]
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
[[package]]
name = "rand_core"
version = "0.6.4"
@@ -3101,6 +3176,15 @@ dependencies = [
"getrandom 0.2.17",
]
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
[[package]]
name = "rand_core"
version = "0.10.1"
@@ -3122,6 +3206,18 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "rcgen"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "yasna",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -3710,6 +3806,17 @@ version = "1.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+[[package]]
+name = "socket-pktinfo"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
+dependencies = [
+ "libc",
+ "socket2",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "socket2"
version = "0.6.5"
@@ -3768,6 +3875,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "spin"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+dependencies = [
+ "lock_api",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -4342,9 +4458,21 @@ dependencies = [
"mio",
"pin-project-lite",
"socket2",
+ "tokio-macros",
"windows-sys 0.61.2",
]
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "tokio-rustls"
version = "0.26.6"
@@ -4355,6 +4483,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.26.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
+dependencies = [
+ "futures-util",
+ "log",
+ "tokio",
+ "tungstenite",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -4568,6 +4708,23 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "tungstenite"
+version = "0.26.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
+dependencies = [
+ "bytes",
+ "data-encoding",
+ "http",
+ "httparse",
+ "log",
+ "rand 0.9.5",
+ "sha1",
+ "thiserror 2.0.21",
+ "utf-8",
+]
+
[[package]]
name = "typeid"
version = "1.0.3"
@@ -4634,6 +4791,12 @@ dependencies = [
"url",
]
+[[package]]
+name = "utf-8"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
+
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -5539,6 +5702,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+[[package]]
+name = "yasna"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
+dependencies = [
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.toml
index 54b1bd18..766b00c7 100644
--- a/windows/src-tauri/Cargo.toml
+++ b/windows/src-tauri/Cargo.toml
@@ -20,8 +20,28 @@ tauri-plugin-autostart = "2"
tauri-plugin-global-shortcut = "2"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
-tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt"] }
+tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt", "macros"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
+# Phone link (phone_link/): a TLS server for the Android app, off unless the user
+# turns it on. Every crate here is justified in docs/ANDROID_LINK.md.
+rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
+tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
+ring = "0.17"
+rcgen = { version = "0.13", default-features = false, features = ["ring"] }
+qrcode = { version = "0.14", default-features = false, features = ["svg"] }
+# The phone finds this computer by itself when its address changes: it is announced on the local network
+# (mDNS / DNS-SD, `_coucou._tcp`) only while the phone link is on (phone_link/discovery.rs). Pure Rust,
+# Apache-2.0 OR MIT, no async runtime or logger (default features off); it adds five small crates
+# (mdns-sd, flume, if-addrs, socket-pktinfo, spin). See docs/ANDROID_LINK.md.
+mdns-sd = { version = "0.21", default-features = false }
+# Phone link through a relay (phone_link/relay_client.rs; docs/RELAY_LINK.md): the computer opens an outbound
+# WebSocket to the user's own relay, only while "Away from home Wi-Fi" is on. tokio-tungstenite is the WebSocket
+# framing only (no TLS feature: the TLS is the tokio-rustls/ring already here, with the web roots reqwest already
+# pulls in), so no second crypto provider is added. MIT.
+tokio-tungstenite = { version = "0.26", default-features = false, features = ["handshake"] }
+webpki-roots = "1"
+# Stream/Sink traits for the WebSocket (already in the tree through tokio-tungstenite and tauri).
+futures-util = { version = "0.3", default-features = false, features = ["sink"] }
[target.'cfg(windows)'.dependencies]
keyring = { version = "3", features = ["windows-native"] }
diff --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rs
index 834e2ef8..81d74955 100644
--- a/windows/src-tauri/src/chat.rs
+++ b/windows/src-tauri/src/chat.rs
@@ -219,6 +219,29 @@ pub async fn send(
Err(format!("Unknown chat provider: {provider}"))
}
+/// One turn of the phone's conversation (phone_link/chat_backend.rs): the same providers as
+/// [`send`], with no file or window context and no `AppHandle`. `on_delta` gets the streamed
+/// text so far, which only the model servers produce; the cloud providers answer all at once.
+pub async fn send_for_phone(
+ settings: &Settings,
+ chat: &Chat,
+ provider: &str,
+ model: &str,
+ query: String,
+ on_delta: impl FnMut(String),
+) -> Result<ChatReply, String> {
+ if provider == ANTHROPIC {
+ return claude::send(chat, model, query, None).await;
+ }
+ if let Some(p) = openai_compat::provider(provider) {
+ return openai_compat::send(chat, p, model, query, None).await;
+ }
+ if let Some(server) = local_chat::server(settings, provider) {
+ return local_chat::send_with(chat, &server, model, query, None, on_delta).await;
+ }
+ Err(format!("Unknown chat provider: {provider}"))
+}
+
/// The models `provider` offers. Asked only when the user opens the picker on
/// that provider, and only once it has a key (or, for a local server, an
/// address): nothing is sent anywhere before that.
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index 870af4b6..e35793fa 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -18,6 +18,7 @@ mod local_chat;
mod log;
mod net;
mod openai_compat;
+mod phone_link;
mod pipe;
mod platform;
#[cfg(target_os = "linux")]
@@ -92,6 +93,17 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {
// Where Mochi sits on the desktop is desktop.rs's to say, not a webview's.
let mut settings = settings.clone();
settings.desktop_mochi = current.desktop_mochi.clone();
+ // Same for the phone link: only its own commands turn it on or off.
+ settings.phone_link = current.phone_link;
+ settings.phone_chat = current.phone_chat;
+ settings.phone_details = current.phone_details;
+ settings.phone_answers = current.phone_answers;
+ settings.phone_diffs = current.phone_diffs;
+ settings.phone_usage = current.phone_usage;
+ settings.phone_services = current.phone_services.clone();
+ settings.phone_relay = current.phone_relay;
+ settings.phone_relay_url = current.phone_relay_url.clone();
+ settings.phone_chat_models = current.phone_chat_models.clone();
*current = settings;
(screen_changed, autostart_changed, shortcuts_changed)
};
@@ -713,6 +725,32 @@ pub fn run() {
set_paused,
shortcuts_status,
shortcuts_suspend,
+ phone_link::phone_link_status,
+ phone_link::phone_link_set_enabled,
+ phone_link::phone_link_pairing,
+ phone_link::phone_link_new_pairing,
+ phone_link::phone_link_publish,
+ phone_link::phone_link_publish_question,
+ phone_link::phone_link_publish_prefs,
+ phone_link::phone_answers_status,
+ phone_link::phone_answers_set_enabled,
+ phone_link::phone_diffs_status,
+ phone_link::phone_diffs_set_enabled,
+ phone_link::phone_link_send_diff,
+ phone_link::phone_usage_status,
+ phone_link::phone_usage_set_enabled,
+ phone_link::phone_relay_status,
+ phone_link::phone_relay_set,
+ phone_link::phone_relay_set_access,
+ phone_link::phone_link_publish_usage,
+ phone_link::phone_services_status,
+ phone_link::phone_services_set,
+ phone_link::phone_link_publish_services,
+ phone_link::phone_details_status,
+ phone_link::phone_details_set_enabled,
+ phone_link::phone_chat_status,
+ phone_link::phone_chat_set_enabled,
+ phone_link::phone_chat_set_models,
recap::recap_history,
recap::recap_prefs,
recap::recap_set_enabled,
@@ -742,6 +780,7 @@ pub fn run() {
])
.setup(move |app| {
let handle = app.handle().clone();
+ app.manage(phone_link::PhoneLink::new(handle.clone()));
tray::build(&handle)?;
// Before the island: see create_settings_window.
create_settings_window(&handle);
@@ -774,13 +813,20 @@ pub fn run() {
log::line(format!("--- Coucou {} started ---", env!("CARGO_PKG_VERSION")));
hooks::ensure_hook_exe(&handle);
pipe::start(handle.clone());
+ phone_link::start_if_enabled(&handle);
integrations::start(handle.clone());
spotify::sync(&handle, &loaded.active_integrations);
shortcuts::apply(&handle, &loaded.shortcuts);
Ok(())
})
- .run(tauri::generate_context!())
- .expect("error while running Coucou");
+ .build(tauri::generate_context!())
+ .expect("error while building Coucou")
+ .run(|app, event| {
+ // Withdraw the phone link's announcement on the local network before the process ends.
+ if let tauri::RunEvent::Exit = event {
+ phone_link::stop_on_exit(app);
+ }
+ });
}
#[cfg(test)]
diff --git a/windows/src-tauri/src/local_chat.rs b/windows/src-tauri/src/local_chat.rs
index 95d624c7..26dfa979 100644
--- a/windows/src-tauri/src/local_chat.rs
+++ b/windows/src-tauri/src/local_chat.rs
@@ -253,7 +253,7 @@ fn request_body(model: &str, system: &str, history: &[Value], user: &Value) -> V
json!({ "model": model, "messages": messages, "stream": true, "max_tokens": MAX_TOKENS })
}
-/// One chat turn with a model server.
+/// One chat turn with a model server; the island gets the streamed text as `chat-delta` events.
pub async fn send(
app: &AppHandle,
chat: &Chat,
@@ -261,6 +261,21 @@ pub async fn send(
model: &str,
query: String,
context: Option<ChatContext>,
+) -> Result<ChatReply, String> {
+ send_with(chat, server, model, query, context, |visible| {
+ let _ = app.emit_to(WINDOW_LABEL, "chat-delta", visible);
+ })
+ .await
+}
+
+/// The same turn, with the streamed text handed to `on_delta` instead (the phone link uses this).
+pub async fn send_with(
+ chat: &Chat,
+ server: &Server,
+ model: &str,
+ query: String,
+ context: Option<ChatContext>,
+ on_delta: impl FnMut(String),
) -> Result<ChatReply, String> {
let base = base_url(server)?;
if model.is_empty() {
@@ -270,10 +285,7 @@ pub async fn send(
let user = json!({ "role": "user", "content": user_text(turn.first, context.as_ref(), &query) });
let body = request_body(model, &chat::system_prompt(false), &turn.history, &user);
- let answer = stream(&base, server.key.as_deref(), model, &body, |visible| {
- let _ = app.emit_to(WINDOW_LABEL, "chat-delta", visible);
- })
- .await?;
+ let answer = stream(&base, server.key.as_deref(), model, &body, on_delta).await?;
if answer.is_empty() {
return Err(t("No response text."));
}
diff --git a/windows/src-tauri/src/phone_link/admission.rs b/windows/src-tauri/src/phone_link/admission.rs
new file mode 100644
index 00000000..dda9b3d1
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/admission.rs
@@ -0,0 +1,290 @@
+// Who may open a connection, and for how long it may stay unauthenticated (docs/ANDROID_LINK.md, "Admission").
+//
+// The server accepts connections from the local network before it knows who is calling. Left alone, one noisy or
+// hostile device could fill every slot with silent connections and keep the paired phone out. So:
+// * one source address may hold at most 2 connections that have not yet said a valid hello;
+// * strangers (addresses that never authenticated) share a pool of 4 such connections, so at least half of the
+// 8 slots are always left for a phone the computer already knows;
+// * an address that authenticated before is remembered (in memory only, 8 addresses) and is not held to the
+// stranger pool;
+// * when the pool is getting full the TLS handshake and the hello get 3 s instead of 10 s, so a flood of silent
+// connections frees its slots fast.
+// Pure bookkeeping: no sockets, no clock, so every rule is a unit test.
+
+use std::collections::{HashMap, VecDeque};
+use std::net::IpAddr;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+pub const MAX_CONNECTIONS: usize = 8;
+/// Connections from one address that have not yet sent a valid hello.
+pub const MAX_UNAUTH_PER_ADDRESS: usize = 2;
+/// Unauthenticated connections from addresses that never authenticated, all together.
+pub const MAX_UNAUTH_STRANGERS: usize = 4;
+/// Addresses remembered as "authenticated before".
+pub const KNOWN_ADDRESSES: usize = 8;
+pub const PATIENT: Duration = Duration::from_secs(10);
+pub const HURRIED: Duration = Duration::from_secs(3);
+
+#[derive(Default)]
+struct State {
+ total: usize,
+ strangers_unauth: usize,
+ unauth: HashMap<IpAddr, usize>,
+ known: VecDeque<IpAddr>,
+}
+
+#[derive(Default)]
+pub struct Admission {
+ state: Mutex<State>,
+}
+
+fn canonical(ip: IpAddr) -> IpAddr {
+ ip.to_canonical()
+}
+
+impl Admission {
+ pub fn new() -> Arc<Admission> {
+ Arc::new(Admission::default())
+ }
+
+ /// A slot for this caller, or None (the connection is closed unserved). The slot is given back when the ticket drops.
+ pub fn admit(self: &Arc<Self>, ip: IpAddr) -> Option<Ticket> {
+ let ip = canonical(ip);
+ let mut s = self.state.lock().unwrap();
+ if s.total >= MAX_CONNECTIONS {
+ return None;
+ }
+ if s.unauth.get(&ip).copied().unwrap_or(0) >= MAX_UNAUTH_PER_ADDRESS {
+ return None;
+ }
+ let stranger = !s.known.contains(&ip);
+ if stranger && s.strangers_unauth >= MAX_UNAUTH_STRANGERS {
+ return None;
+ }
+ // Looked at before this caller is counted: "is the pool getting full already?"
+ let hurried = s.total + 2 >= MAX_CONNECTIONS || s.strangers_unauth * 2 >= MAX_UNAUTH_STRANGERS;
+ s.total += 1;
+ *s.unauth.entry(ip).or_insert(0) += 1;
+ if stranger {
+ s.strangers_unauth += 1;
+ }
+ Some(Ticket {
+ admission: self.clone(),
+ ip,
+ stranger,
+ unauthenticated: Mutex::new(true),
+ wait: if hurried { HURRIED } else { PATIENT },
+ })
+ }
+
+ #[cfg(test)]
+ pub fn counts(&self) -> (usize, usize) {
+ let s = self.state.lock().unwrap();
+ (s.total, s.strangers_unauth)
+ }
+
+ #[cfg(test)]
+ pub fn knows(&self, ip: IpAddr) -> bool {
+ self.state.lock().unwrap().known.contains(&canonical(ip))
+ }
+}
+
+/// One accepted connection's slot.
+pub struct Ticket {
+ admission: Arc<Admission>,
+ ip: IpAddr,
+ stranger: bool,
+ unauthenticated: Mutex<bool>,
+ wait: Duration,
+}
+
+impl Ticket {
+ /// How long the TLS handshake and then the hello may take (shorter when the pool is nearly full).
+ pub fn wait(&self) -> Duration {
+ self.wait
+ }
+
+ /// The caller said a valid hello: it no longer counts against the unauthenticated limits and its address is
+ /// remembered, so a flood from elsewhere cannot keep it out.
+ pub fn authenticated(&self) {
+ let mut flag = self.unauthenticated.lock().unwrap();
+ if !*flag {
+ return;
+ }
+ *flag = false;
+ let mut s = self.admission.state.lock().unwrap();
+ release_unauth(&mut s, self.ip, self.stranger);
+ s.known.retain(|k| *k != self.ip);
+ s.known.push_front(self.ip);
+ s.known.truncate(KNOWN_ADDRESSES);
+ }
+}
+
+fn release_unauth(s: &mut State, ip: IpAddr, stranger: bool) {
+ if let Some(n) = s.unauth.get_mut(&ip) {
+ *n -= 1;
+ if *n == 0 {
+ s.unauth.remove(&ip);
+ }
+ }
+ if stranger {
+ s.strangers_unauth -= 1;
+ }
+}
+
+impl Drop for Ticket {
+ fn drop(&mut self) {
+ let mut s = self.admission.state.lock().unwrap();
+ s.total -= 1;
+ if *self.unauthenticated.lock().unwrap() {
+ release_unauth(&mut s, self.ip, self.stranger);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+ }
+
+ #[test]
+ fn one_address_holds_at_most_two_unauthenticated_connections() {
+ let a = Admission::new();
+ let t1 = a.admit(ip("192.168.1.50")).unwrap();
+ let _t2 = a.admit(ip("192.168.1.50")).unwrap();
+ assert!(a.admit(ip("192.168.1.50")).is_none(), "the third from one address");
+ assert!(a.admit(ip("192.168.1.51")).is_some(), "another address is not affected");
+ drop(t1);
+ assert!(a.admit(ip("192.168.1.50")).is_some(), "a closed connection frees its place");
+ }
+
+ #[test]
+ fn the_same_address_written_two_ways_is_one_address() {
+ let a = Admission::new();
+ let _t1 = a.admit(ip("192.168.1.50")).unwrap();
+ let _t2 = a.admit(ip("::ffff:192.168.1.50")).unwrap();
+ assert!(a.admit(ip("192.168.1.50")).is_none());
+ }
+
+ #[test]
+ fn strangers_share_a_pool_smaller_than_the_whole() {
+ let a = Admission::new();
+ let mut held = Vec::new();
+ for n in 0..MAX_UNAUTH_STRANGERS / MAX_UNAUTH_PER_ADDRESS {
+ for _ in 0..MAX_UNAUTH_PER_ADDRESS {
+ held.push(a.admit(ip(&format!("10.0.0.{}", n + 1))).unwrap());
+ }
+ }
+ assert_eq!(held.len(), MAX_UNAUTH_STRANGERS);
+ assert!(a.admit(ip("10.0.0.99")).is_none(), "the stranger pool is full");
+ assert!(held.len() < MAX_CONNECTIONS, "the pool leaves slots for known phones");
+ }
+
+ #[test]
+ fn a_flood_from_many_addresses_cannot_lock_out_the_paired_phone() {
+ let a = Admission::new();
+ // The phone connected once before: its address is known.
+ a.admit(ip("192.168.1.20")).unwrap().authenticated();
+ assert!(a.knows(ip("192.168.1.20")));
+ // A flood fills everything strangers may take.
+ let mut flood = Vec::new();
+ for n in 0..50 {
+ if let Some(t) = a.admit(ip(&format!("192.168.1.{}", 100 + n))) {
+ flood.push(t);
+ }
+ }
+ assert_eq!(flood.len(), MAX_UNAUTH_STRANGERS, "the flood is capped");
+ // The paired phone still gets in, and keeps getting in after it reconnects.
+ let phone = a.admit(ip("192.168.1.20")).expect("the paired phone is not locked out");
+ phone.authenticated();
+ let again = a.admit(ip("192.168.1.20")).expect("and can reconnect while the flood goes on");
+ again.authenticated();
+ let (total, strangers) = a.counts();
+ assert_eq!(strangers, MAX_UNAUTH_STRANGERS);
+ assert!(total <= MAX_CONNECTIONS);
+ }
+
+ #[test]
+ fn a_flood_from_one_address_leaves_every_other_address_alone() {
+ let a = Admission::new();
+ let _flood: Vec<_> = (0..20).filter_map(|_| a.admit(ip("192.168.1.66"))).collect();
+ let newcomer = a.admit(ip("192.168.1.20"));
+ assert!(newcomer.is_some(), "a new phone, never seen before, still connects");
+ assert_eq!(a.counts().1, MAX_UNAUTH_PER_ADDRESS + 1);
+ }
+
+ #[test]
+ fn authenticating_frees_the_unauthenticated_places_and_is_counted_once() {
+ let a = Admission::new();
+ let t = a.admit(ip("192.168.1.20")).unwrap();
+ t.authenticated();
+ t.authenticated();
+ assert_eq!(a.counts(), (1, 0));
+ // An authenticated connection no longer counts against the two-per-address limit.
+ let _u1 = a.admit(ip("192.168.1.20")).unwrap();
+ let _u2 = a.admit(ip("192.168.1.20")).unwrap();
+ drop(t);
+ assert_eq!(a.counts().0, 2);
+ }
+
+ #[test]
+ fn the_places_come_back_when_tickets_drop_whatever_their_state() {
+ let a = Admission::new();
+ {
+ let t1 = a.admit(ip("192.168.1.20")).unwrap();
+ let _t2 = a.admit(ip("192.168.1.21")).unwrap();
+ t1.authenticated();
+ }
+ assert_eq!(a.counts(), (0, 0));
+ assert!(a.admit(ip("192.168.1.21")).is_some());
+ }
+
+ #[test]
+ fn the_total_never_goes_over_eight_even_for_known_phones() {
+ let a = Admission::new();
+ let mut held = Vec::new();
+ for n in 0..MAX_CONNECTIONS {
+ let t = a.admit(ip(&format!("192.168.1.{}", 10 + n))).unwrap();
+ t.authenticated();
+ held.push(t);
+ }
+ assert!(a.admit(ip("192.168.1.10")).is_none());
+ assert_eq!(a.counts().0, MAX_CONNECTIONS);
+ }
+
+ #[test]
+ fn the_wait_is_shorter_when_the_pool_is_filling_up() {
+ let a = Admission::new();
+ assert_eq!(a.admit(ip("192.168.1.1")).unwrap().wait(), PATIENT, "an empty server is patient");
+ let mut held = Vec::new();
+ for n in 0..2 {
+ held.push(a.admit(ip(&format!("192.168.2.{n}"))).unwrap());
+ }
+ // Two strangers waiting is half of their pool: new callers are hurried.
+ let t = a.admit(ip("192.168.3.1")).unwrap();
+ assert_eq!(t.wait(), HURRIED);
+ // And when the whole pool is nearly full, even a known phone gets the short wait.
+ let b = Admission::new();
+ let mut known = Vec::new();
+ for n in 0..6 {
+ let t = b.admit(ip(&format!("192.168.4.{n}"))).unwrap();
+ t.authenticated();
+ known.push(t);
+ }
+ assert_eq!(b.admit(ip("192.168.4.0")).unwrap().wait(), HURRIED);
+ }
+
+ #[test]
+ fn at_most_eight_addresses_are_remembered() {
+ let a = Admission::new();
+ for n in 0..(KNOWN_ADDRESSES + 3) {
+ a.admit(ip(&format!("192.168.5.{n}"))).unwrap().authenticated();
+ }
+ assert!(!a.knows(ip("192.168.5.0")), "the oldest is forgotten");
+ assert!(a.knows(ip(&format!("192.168.5.{}", KNOWN_ADDRESSES + 2))));
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/chat.rs b/windows/src-tauri/src/phone_link/chat.rs
new file mode 100644
index 00000000..36c976a8
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/chat.rs
@@ -0,0 +1,419 @@
+// Chat from the phone (docs/ANDROID_LINK.md, "Chat").
+//
+// The phone sends text, this computer asks the provider with ITS key, and the answer
+// comes back as small `chatDelta` lines. Nothing here knows a key, a provider address
+// or a provider's error text: the backend (a trait, so tests use a fake) answers with a
+// string or one of a handful of failure kinds, and each kind has a fixed message written
+// here. A provider's own message may echo part of a key, so it never reaches the phone.
+//
+// What it enforces, whatever the phone sends:
+// * the connection must have asked for the "chat" capability and been offered it;
+// * the switch on the computer is read again for every message (turning it off cancels
+// the running answer and forgets the conversation);
+// * the model must be one the user allowed; the text is at most MAX_TEXT_CHARS;
+// * one running answer at a time, at most MAX_SENDS sends per RATE_WINDOW_MS;
+// * an answer is cancelled when its phone leaves, so nothing keeps running unseen.
+
+use std::collections::VecDeque;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+
+use serde_json::{json, Value};
+use tokio::sync::mpsc;
+use tokio::task::AbortHandle;
+
+use super::hub::Out;
+use super::server::MAX_LINE;
+
+pub const MAX_TEXT_CHARS: usize = 4000;
+pub const MAX_SENDS: usize = 12;
+pub const RATE_WINDOW_MS: u64 = 10 * 60 * 1000;
+/// Text per `chatDelta` line. Even when every character needs escaping a line stays far under 64 KiB.
+pub const DELTA_PIECE: usize = 8 * 1024;
+/// The full answer a `chatDone` may carry when the streamed text had to be corrected.
+pub const DONE_TEXT_MAX: usize = 30_000;
+const MAX_ID: usize = 64;
+
+pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
+
+/// A model the user allowed for the phone. `id` is "provider/model".
+#[derive(Debug, Clone, PartialEq)]
+pub struct ModelOption {
+ pub id: String,
+ pub provider: String,
+ pub label: String,
+}
+
+/// What the user chose on the computer, read again for every message.
+#[derive(Debug, Clone, Default)]
+pub struct ChatConfig {
+ pub enabled: bool,
+ pub allowed: Vec<ModelOption>,
+}
+
+/// Why a turn failed, as far as the phone may know.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ChatFail {
+ NoKey,
+ Unreachable,
+ Auth,
+ Provider,
+ Internal,
+}
+
+/// The computer's chat. The real one calls the same provider code as the island's chat.
+pub trait ChatBackend: Send + Sync {
+ fn config(&self) -> ChatConfig;
+ /// One turn of the phone's conversation. `deltas` receives the answer **so far**
+ /// (the whole visible text each time), whenever the provider streams it. Returns the full answer.
+ fn send(&self, model_id: &str, text: String, deltas: mpsc::UnboundedSender<String>) -> BoxFuture<Result<String, ChatFail>>;
+ /// Forget the phone's conversation.
+ fn reset(&self);
+}
+
+/// The fixed code and message for a failure; never anything a provider wrote.
+pub fn reason(code: &str) -> &'static str {
+ match code {
+ "off" => "Chat from the phone is turned off on the computer.",
+ "not_allowed" => "That model is not allowed for the phone.",
+ "busy" => "Another answer is still being written.",
+ "rate" => "Too many messages. Try again in a few minutes.",
+ "too_long" => "The message is too long.",
+ "empty" => "Nothing to send.",
+ "no_key" => "The computer has no key for that provider.",
+ "unreachable" => "The computer could not reach the provider.",
+ "auth" => "The provider refused the computer's key.",
+ "provider" => "The provider returned an error.",
+ "canceled" => "Canceled.",
+ _ => "Something went wrong on the computer.",
+ }
+}
+
+fn fail_code(f: ChatFail) -> &'static str {
+ match f {
+ ChatFail::NoKey => "no_key",
+ ChatFail::Unreachable => "unreachable",
+ ChatFail::Auth => "auth",
+ ChatFail::Provider => "provider",
+ ChatFail::Internal => "internal",
+ }
+}
+
+fn error_line(id: &str, code: &str) -> Out {
+ Out::Line(json!({ "type": "chatError", "id": id, "reason": code, "message": reason(code) }).to_string().into())
+}
+
+// ── Streaming a growing text as appended pieces ───────────────────────────────
+
+/// Turns "the answer so far" into appended pieces. A text that stops being an extension of what
+/// was already sent (a model's hidden reasoning being filtered, say) is held back, and the final
+/// answer corrects it in `chatDone`.
+#[derive(Default)]
+pub struct DeltaSplitter {
+ sent: String,
+}
+
+impl DeltaSplitter {
+ pub fn feed(&mut self, so_far: &str) -> Vec<String> {
+ match so_far.strip_prefix(self.sent.as_str()) {
+ Some(rest) if !rest.is_empty() => {
+ let pieces = split_chars(rest, DELTA_PIECE);
+ self.sent.push_str(rest);
+ pieces
+ }
+ _ => Vec::new(),
+ }
+ }
+
+ /// The last pieces, and the full answer when what was sent is not a prefix of it.
+ pub fn finish(&mut self, answer: &str) -> (Vec<String>, Option<String>) {
+ if answer.starts_with(self.sent.as_str()) {
+ (self.feed(answer), None)
+ } else {
+ (Vec::new(), Some(cut(answer, DONE_TEXT_MAX).to_string()))
+ }
+ }
+}
+
+/// At most `max` bytes per piece, never inside a character.
+fn split_chars(text: &str, max: usize) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut rest = text;
+ while !rest.is_empty() {
+ let piece = cut(rest, max);
+ out.push(piece.to_string());
+ rest = &rest[piece.len()..];
+ }
+ out
+}
+
+fn cut(text: &str, max: usize) -> &str {
+ if text.len() <= max {
+ return text;
+ }
+ let mut end = max;
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ &text[..end]
+}
+
+/// A line that fits the phone's 64 KiB limit, shortening `text` if it would not.
+fn fit(mut v: Value, field: &str) -> Out {
+ loop {
+ let line = v.to_string();
+ if line.len() < MAX_LINE - 1024 {
+ return Out::Line(line.into());
+ }
+ let shorter = cut(v[field].as_str().unwrap_or(""), v[field].as_str().map_or(0, str::len) / 2).to_string();
+ v[field] = Value::String(shorter);
+ }
+}
+
+// ── The link's chat ───────────────────────────────────────────────────────────
+
+struct Run {
+ token: u64,
+ id: String,
+ conn: u64,
+ abort: AbortHandle,
+}
+
+#[derive(Default)]
+struct Gate {
+ running: Option<Run>,
+ sends: VecDeque<u64>,
+ next_token: u64,
+}
+
+pub struct ChatLink {
+ backend: Arc<dyn ChatBackend>,
+ gate: Mutex<Gate>,
+}
+
+/// Frees the "one at a time" slot when the answer ends, however it ends (finished, failed, aborted).
+struct Slot {
+ link: Arc<ChatLink>,
+ token: u64,
+}
+
+impl Drop for Slot {
+ fn drop(&mut self) {
+ let mut g = self.link.gate.lock().unwrap();
+ if g.running.as_ref().is_some_and(|r| r.token == self.token) {
+ g.running = None;
+ }
+ }
+}
+
+impl ChatLink {
+ pub fn new(backend: Arc<dyn ChatBackend>) -> Arc<ChatLink> {
+ Arc::new(ChatLink { backend, gate: Mutex::new(Gate::default()) })
+ }
+
+ /// Offered to a phone only while the user's switch is on.
+ pub fn enabled(&self) -> bool {
+ self.backend.config().enabled
+ }
+
+ /// The switch went off (or the link stopped): nothing keeps running and the conversation is forgotten.
+ pub fn shutdown(&self) {
+ self.cancel_where(|_| true);
+ self.backend.reset();
+ }
+
+ /// A phone left: its answer, if any, stops.
+ pub fn cancel_conn(&self, conn: u64) {
+ self.cancel_where(|r| r.conn == conn);
+ }
+
+ fn cancel_where(&self, which: impl Fn(&Run) -> bool) -> Option<Run> {
+ let mut g = self.gate.lock().unwrap();
+ if g.running.as_ref().is_some_and(which) {
+ let run = g.running.take()?;
+ run.abort.abort();
+ return Some(run);
+ }
+ None
+ }
+
+ fn models_line(&self) -> Out {
+ let cfg = self.backend.config();
+ let models: Vec<Value> = if cfg.enabled {
+ cfg.allowed.iter().map(|m| json!({ "id": m.id, "provider": m.provider, "label": m.label })).collect()
+ } else {
+ Vec::new()
+ };
+ Out::Line(json!({ "type": "chatModels", "models": models }).to_string().into())
+ }
+
+ /// One chat message from a phone that negotiated the capability. Never blocks; answers are written
+ /// by a task that stops when the connection's channel closes.
+ pub fn handle(self: &Arc<Self>, conn: u64, tx: &mpsc::Sender<Out>, msg: &Value, now: u64) {
+ let say = |o: Out| {
+ let _ = tx.try_send(o);
+ };
+ match msg["type"].as_str() {
+ Some("chatModels") => say(self.models_line()),
+ Some("chatReset") => {
+ if let Some(r) = self.cancel_where(|r| r.conn == conn) {
+ say(error_line(&r.id, "canceled"));
+ }
+ self.backend.reset();
+ }
+ Some("chatCancel") => {
+ let id = msg["id"].as_str().unwrap_or("");
+ if let Some(r) = self.cancel_where(|r| r.conn == conn && r.id == id) {
+ say(error_line(&r.id, "canceled"));
+ }
+ }
+ Some("chatSend") => self.send(conn, tx, msg, now),
+ _ => {}
+ }
+ }
+
+ fn send(self: &Arc<Self>, conn: u64, tx: &mpsc::Sender<Out>, msg: &Value, now: u64) {
+ // Without a usable id there is nothing to answer to.
+ let Some(id) = msg["id"].as_str().filter(|i| !i.is_empty() && i.len() <= MAX_ID && i.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) else {
+ return;
+ };
+ let refuse = |code: &str| {
+ let _ = tx.try_send(error_line(id, code));
+ };
+ let cfg = self.backend.config();
+ if !cfg.enabled {
+ return refuse("off");
+ }
+ let text = msg["text"].as_str().unwrap_or("");
+ if text.trim().is_empty() {
+ return refuse("empty");
+ }
+ if text.chars().count() > MAX_TEXT_CHARS {
+ return refuse("too_long");
+ }
+ let model = msg["model"].as_str().unwrap_or("");
+ if !cfg.allowed.iter().any(|m| m.id == model) {
+ return refuse("not_allowed");
+ }
+
+ let mut g = self.gate.lock().unwrap();
+ if g.running.is_some() {
+ drop(g);
+ return refuse("busy");
+ }
+ while g.sends.front().is_some_and(|&t| now.saturating_sub(t) >= RATE_WINDOW_MS) {
+ g.sends.pop_front();
+ }
+ if g.sends.len() >= MAX_SENDS {
+ drop(g);
+ return refuse("rate");
+ }
+ g.sends.push_back(now);
+ g.next_token += 1;
+ let token = g.next_token;
+
+ let (link, tx, id_owned, model, text) = (self.clone(), tx.clone(), id.to_string(), model.to_string(), text.to_string());
+ let task_id = id_owned.clone();
+ let join = tokio::spawn(async move {
+ let _slot = Slot { link: link.clone(), token };
+ answer(&link, &tx, &task_id, &model, text).await;
+ });
+ g.running = Some(Run { token, id: id_owned, conn, abort: join.abort_handle() });
+ }
+}
+
+/// Runs one turn and writes its lines. Ends quietly if the phone's channel is gone.
+async fn answer(link: &ChatLink, tx: &mpsc::Sender<Out>, id: &str, model: &str, text: String) {
+ let (dtx, mut drx) = mpsc::unbounded_channel::<String>();
+ let forward = {
+ let (tx, id) = (tx.clone(), id.to_string());
+ tokio::spawn(async move {
+ let mut splitter = DeltaSplitter::default();
+ while let Some(so_far) = drx.recv().await {
+ for piece in splitter.feed(&so_far) {
+ let line = json!({ "type": "chatDelta", "id": id, "text": piece }).to_string();
+ if tx.send(Out::Line(line.into())).await.is_err() {
+ return splitter;
+ }
+ }
+ }
+ splitter
+ })
+ };
+ let result = link.backend.send(model, text, dtx).await;
+ // The sender went with the future: the forwarder drains what is queued and ends.
+ let Ok(mut splitter) = forward.await else { return };
+ match result {
+ Ok(full) => {
+ let (pieces, correction) = splitter.finish(&full);
+ for piece in pieces {
+ let line = json!({ "type": "chatDelta", "id": id, "text": piece }).to_string();
+ if tx.send(Out::Line(line.into())).await.is_err() {
+ return;
+ }
+ }
+ let mut done = json!({ "type": "chatDone", "id": id });
+ if let Some(full) = correction {
+ done["text"] = Value::String(full);
+ }
+ let _ = tx.send(fit(done, "text")).await;
+ }
+ Err(f) => {
+ let _ = tx.send(error_line(id, fail_code(f))).await;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_growing_text_is_sent_as_appended_pieces() {
+ let mut s = DeltaSplitter::default();
+ assert_eq!(s.feed("Hel"), vec!["Hel"]);
+ assert_eq!(s.feed("Hello"), vec!["lo"]);
+ assert!(s.feed("Hello").is_empty());
+ assert_eq!(s.finish("Hello world"), (vec![" world".to_string()], None));
+ }
+
+ #[test]
+ fn a_text_that_is_rewritten_is_corrected_by_the_final_answer() {
+ let mut s = DeltaSplitter::default();
+ assert_eq!(s.feed("<think>hmm"), vec!["<think>hmm"]);
+ assert!(s.feed("Answer").is_empty(), "not an extension: held back");
+ let (pieces, correction) = s.finish("Answer");
+ assert!(pieces.is_empty());
+ assert_eq!(correction.as_deref(), Some("Answer"));
+ }
+
+ #[test]
+ fn pieces_never_split_a_character_and_stay_small() {
+ let text = "é".repeat(DELTA_PIECE); // 2 bytes each
+ let mut s = DeltaSplitter::default();
+ let pieces = s.feed(&text);
+ assert!(pieces.len() >= 2);
+ assert!(pieces.iter().all(|p| p.len() <= DELTA_PIECE));
+ assert_eq!(pieces.concat(), text);
+ }
+
+ #[test]
+ fn a_huge_correction_is_cut_and_every_line_fits_the_limit() {
+ let mut s = DeltaSplitter::default();
+ s.feed("x");
+ let (_, c) = s.finish(&"é".repeat(100_000));
+ assert!(c.unwrap().len() <= DONE_TEXT_MAX);
+ // control characters double or sextuple in JSON: the line is shortened until it fits
+ let Out::Line(l) = fit(json!({ "type": "chatDone", "id": "a", "text": "\u{1}".repeat(30_000) }), "text") else { panic!() };
+ assert!(l.len() < MAX_LINE);
+ }
+
+ #[test]
+ fn every_reason_has_a_fixed_message_and_none_looks_like_a_key() {
+ for code in ["off", "not_allowed", "busy", "rate", "too_long", "empty", "no_key", "unreachable", "auth", "provider", "canceled", "internal", "whatever"] {
+ let m = reason(code);
+ assert!(!m.is_empty() && !m.contains("sk-") && m.len() < 80, "{code}");
+ }
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/chat_backend.rs b/windows/src-tauri/src/phone_link/chat_backend.rs
new file mode 100644
index 00000000..ccca521b
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/chat_backend.rs
@@ -0,0 +1,207 @@
+// The real chat behind the phone link (chat.rs holds the rules): the same provider code as the
+// island's chat, with the phone's own conversation. The key is read inside `claude`, `openai_compat`
+// or `local_chat` from the credential store; nothing in this file ever holds one.
+//
+// Failures are sorted into a few kinds here and only the kind goes on: a provider's message may
+// contain part of a key, so it is neither forwarded nor logged.
+
+use std::sync::Arc;
+
+use tauri::{AppHandle, Manager};
+use tokio::sync::mpsc::UnboundedSender;
+
+use super::chat::{BoxFuture, ChatBackend, ChatConfig, ChatFail, ModelOption};
+use crate::chat::Chat;
+use crate::settings::Settings;
+use crate::{chat, claude, log, openai_compat, secrets, Shared};
+
+/// Most models the user can allow, and the longest model name taken.
+pub const MAX_ALLOWED: usize = 50;
+const MAX_MODEL_CHARS: usize = 200;
+
+const PROVIDERS: [&str; 7] = ["anthropic", "google", "openai", "openrouter", "ollama", "lmstudio", "custom"];
+
+pub struct AppChat {
+ app: AppHandle,
+ chat: Arc<Chat>,
+}
+
+impl AppChat {
+ pub fn new(app: AppHandle) -> Self {
+ Self { app, chat: Arc::new(Chat::default()) }
+ }
+
+ fn settings(&self) -> Settings {
+ self.app.state::<Shared>().settings.lock().unwrap().clone()
+ }
+}
+
+impl ChatBackend for AppChat {
+ fn config(&self) -> ChatConfig {
+ let s = self.settings();
+ ChatConfig { enabled: s.phone_chat, allowed: options(&s.phone_chat_models) }
+ }
+
+ fn send(&self, model_id: &str, text: String, deltas: UnboundedSender<String>) -> BoxFuture<Result<String, ChatFail>> {
+ let settings = self.settings();
+ let chat = self.chat.clone();
+ let id = model_id.to_string();
+ Box::pin(async move {
+ let Some((provider, model)) = parse_model_id(&id) else { return Err(ChatFail::Internal) };
+ if let Some(key) = key_name(provider) {
+ if secrets::get(key).is_none() {
+ return Err(ChatFail::NoKey);
+ }
+ }
+ let result = chat::send_for_phone(&settings, &chat, provider, model, text, |so_far| {
+ let _ = deltas.send(so_far);
+ })
+ .await;
+ match result {
+ Ok(reply) => Ok(reply.text),
+ Err(err) => {
+ let kind = classify(is_local(provider), &err);
+ // The kind only: the text may echo a key.
+ log::line(format!("phone link: chat via {provider} failed ({kind:?})"));
+ Err(kind)
+ }
+ }
+ })
+ }
+
+ fn reset(&self) {
+ self.chat.reset();
+ }
+}
+
+// ── Pure helpers (tested below) ───────────────────────────────────────────────
+
+fn is_local(provider: &str) -> bool {
+ matches!(provider, "ollama" | "lmstudio" | "custom")
+}
+
+/// The credential store entry a provider's key lives in; None for the model servers.
+fn key_name(provider: &str) -> Option<&'static str> {
+ if provider == chat::ANTHROPIC {
+ return Some(claude::KEY);
+ }
+ openai_compat::provider(provider).map(|p| p.key)
+}
+
+pub fn provider_name(provider: &str) -> String {
+ match provider {
+ "anthropic" => "Anthropic".into(),
+ "google" => "Google".into(),
+ "openai" => "OpenAI".into(),
+ "openrouter" => "OpenRouter".into(),
+ "ollama" => "Ollama".into(),
+ "lmstudio" => "LM Studio".into(),
+ _ => "Custom server".into(),
+ }
+}
+
+/// "provider/model" with a provider this build knows and a plain model name; the model may contain
+/// slashes ("openrouter/auto" is the model of the "openrouter" provider written "openrouter/openrouter/auto").
+pub fn parse_model_id(id: &str) -> Option<(&str, &str)> {
+ let (provider, model) = id.split_once('/')?;
+ let model = model.trim();
+ if !PROVIDERS.contains(&provider) || model.is_empty() || model.chars().count() > MAX_MODEL_CHARS || model.chars().any(char::is_control) {
+ return None;
+ }
+ Some((provider, model))
+}
+
+/// The user's list, made safe: valid ids only, no duplicates, at most MAX_ALLOWED.
+pub fn clean_models(ids: &[String]) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for id in ids {
+ if parse_model_id(id).is_some() && !out.contains(id) && out.len() < MAX_ALLOWED {
+ out.push(id.clone());
+ }
+ }
+ out
+}
+
+pub fn options(ids: &[String]) -> Vec<ModelOption> {
+ clean_models(ids)
+ .into_iter()
+ .filter_map(|id| {
+ let (provider, model) = parse_model_id(&id)?;
+ let label = format!("{} · {}", provider_name(provider), model);
+ Some(ModelOption { provider: provider.to_string(), label, id })
+ })
+ .collect()
+}
+
+/// Which kind of failure an error message from `chat::send_for_phone` stands for. The messages are
+/// written for people (and translated), so this looks only at what does not change with the language:
+/// an HTTP status in the text. A model server that answers with no status at all is one that did not answer.
+pub fn classify(local: bool, err: &str) -> ChatFail {
+ let has = |code: &str| err.split(|c: char| !c.is_ascii_digit()).any(|w| w == code);
+ if has("401") || has("403") {
+ return ChatFail::Auth;
+ }
+ let has_status = err.split(|c: char| !c.is_ascii_digit()).any(|w| w.len() == 3 && w.starts_with(['4', '5']));
+ if local && !has_status {
+ return ChatFail::Unreachable;
+ }
+ if err.starts_with("Network error") {
+ return ChatFail::Unreachable;
+ }
+ ChatFail::Provider
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ids(v: &[&str]) -> Vec<String> {
+ v.iter().map(|s| s.to_string()).collect()
+ }
+
+ #[test]
+ fn model_ids_need_a_known_provider_and_a_plain_model() {
+ assert_eq!(parse_model_id("openai/gpt-4o"), Some(("openai", "gpt-4o")));
+ assert_eq!(parse_model_id("openrouter/openrouter/auto"), Some(("openrouter", "openrouter/auto")));
+ assert_eq!(parse_model_id("ollama/llama3.2:latest"), Some(("ollama", "llama3.2:latest")));
+ for bad in ["", "openai", "openai/", "openai/ ", "nope/gpt", "OpenAI/gpt", "openai/a\nb", &format!("openai/{}", "x".repeat(201))] {
+ assert_eq!(parse_model_id(bad), None, "{bad:?}");
+ }
+ }
+
+ #[test]
+ fn the_allowed_list_is_cleaned_and_capped() {
+ assert_eq!(clean_models(&ids(&["openai/gpt-4o", "bad", "openai/gpt-4o", "google/gemini"])), ids(&["openai/gpt-4o", "google/gemini"]));
+ let many: Vec<String> = (0..80).map(|i| format!("openai/m{i}")).collect();
+ assert_eq!(clean_models(&many).len(), MAX_ALLOWED);
+ assert!(clean_models(&[]).is_empty());
+ }
+
+ #[test]
+ fn what_the_phone_is_told_about_a_model_is_its_id_provider_and_label_only() {
+ let o = options(&ids(&["anthropic/claude-x", "lmstudio/qwen"]));
+ assert_eq!(o[0], ModelOption { id: "anthropic/claude-x".into(), provider: "anthropic".into(), label: "Anthropic · claude-x".into() });
+ assert_eq!(o[1].label, "LM Studio · qwen");
+ }
+
+ #[test]
+ fn failures_are_sorted_by_status_and_never_by_wording() {
+ assert_eq!(classify(false, "Claude API 401 Unauthorized: invalid x-api-key"), ChatFail::Auth);
+ assert_eq!(classify(false, "OpenAI rejected the API key (403). Check it in Settings."), ChatFail::Auth);
+ assert_eq!(classify(false, "OpenAI rate limit reached (429): slow down"), ChatFail::Provider);
+ assert_eq!(classify(false, "Claude API 500 Internal Server Error: boom"), ChatFail::Provider);
+ assert_eq!(classify(false, "Network error: connection refused"), ChatFail::Unreachable);
+ assert_eq!(classify(true, "Cannot reach http://127.0.0.1:11434. Is the server running?"), ChatFail::Unreachable);
+ assert_eq!(classify(true, "Ollama 500: model crashed"), ChatFail::Provider);
+ // 4010 or 14012 are not 401
+ assert_eq!(classify(false, "something 14012 happened"), ChatFail::Provider);
+ }
+
+ #[test]
+ fn keys_are_found_by_provider() {
+ assert_eq!(key_name("anthropic"), Some("anthropic-api-key"));
+ assert_eq!(key_name("openai"), Some("openai-api-key"));
+ assert_eq!(key_name("ollama"), None);
+ assert!(is_local("custom") && !is_local("openai"));
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/discovery.rs b/windows/src-tauri/src/phone_link/discovery.rs
new file mode 100644
index 00000000..fe10afa7
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/discovery.rs
@@ -0,0 +1,272 @@
+// Announces this computer on the local network while the phone link is on, so the phone finds it by itself when
+// its address changes (another Wi-Fi, a hotspot). mDNS / DNS-SD, service type `_coucou._tcp`, protocol: docs/ANDROID_LINK.md.
+//
+// What is announced: the computer's name (the instance name), the port, and a TXT record with the protocol version and a
+// short fingerprint id (the first 16 hex characters of the certificate's SHA-256, which is public by nature: anyone who
+// connects gets the certificate). NEVER the token, the pairing link, a user name or a path. The phone matches the
+// service to its paired computer only by that id and still pins the full certificate, so this is a hint, not a credential.
+//
+// Off means silent: nothing is announced and no thread runs. The daemon is created when the announcement starts and
+// shut down (after a goodbye) when it stops, so there is nothing to idle.
+
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+/// The DNS-SD service type. The phone browses for `_coucou._tcp`.
+pub const SERVICE_TYPE: &str = "_coucou._tcp.local.";
+/// How many hex characters of the certificate fingerprint go into the TXT record.
+pub const FP_ID_LEN: usize = 16;
+/// The protocol version in the TXT record (docs/ANDROID_LINK.md stays at v=1).
+pub const TXT_VERSION: &str = "1";
+
+/// The short, non-secret id of a certificate fingerprint: its first 16 lowercase hex characters. None if the input is not hex.
+pub fn fingerprint_id(fingerprint: &str) -> Option<String> {
+ let f = fingerprint.trim().to_ascii_lowercase();
+ if f.len() < FP_ID_LEN || !f.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return None;
+ }
+ Some(f[..FP_ID_LEN].to_string())
+}
+
+/// The TXT record: `v` and `fp`, nothing else.
+pub fn txt(fingerprint: &str) -> Option<Vec<(String, String)>> {
+ let id = fingerprint_id(fingerprint)?;
+ Some(vec![("v".to_string(), TXT_VERSION.to_string()), ("fp".to_string(), id)])
+}
+
+/// A DNS host label from the computer's name: ASCII letters, digits and hyphens, at most 63, "coucou" if nothing is left.
+pub fn host_label(name: &str) -> String {
+ let mut label: String = name
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
+ .collect::<String>()
+ .trim_matches('-')
+ .chars()
+ .take(63)
+ .collect();
+ if label.is_empty() {
+ label = "coucou".to_string();
+ }
+ label
+}
+
+/// What is announced for one computer.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Advert {
+ pub instance: String,
+ pub host: String,
+ pub port: u16,
+ pub txt: Vec<(String, String)>,
+}
+
+pub fn advert(name: &str, port: u16, fingerprint: &str) -> Option<Advert> {
+ let instance: String = name.trim().chars().take(48).collect();
+ let instance = instance.trim().to_string();
+ Some(Advert {
+ instance: if instance.is_empty() { "Coucou".to_string() } else { instance },
+ host: format!("{}.local.", host_label(name)),
+ port,
+ txt: txt(fingerprint)?,
+ })
+}
+
+/// Where announcements go: the network in the app, a recorder in tests.
+pub trait Publisher: Send + Sync {
+ fn publish(&self, advert: &Advert) -> Result<(), String>;
+ fn withdraw(&self, advert: &Advert);
+}
+
+/// Starts and stops the announcement with the phone link.
+pub struct Advertiser {
+ publisher: Arc<dyn Publisher>,
+ current: Mutex<Option<Advert>>,
+}
+
+impl Advertiser {
+ pub fn new(publisher: Arc<dyn Publisher>) -> Self {
+ Self { publisher, current: Mutex::new(None) }
+ }
+
+ /// Announces the computer. A failure is returned for the log and changes nothing else: the link works without it
+ /// (the phone still has the saved address).
+ pub fn start(&self, name: &str, port: u16, fingerprint: &str) -> Result<(), String> {
+ let ad = advert(name, port, fingerprint).ok_or("the certificate fingerprint is not valid")?;
+ let mut cur = self.current.lock().unwrap();
+ if let Some(old) = cur.take() {
+ self.publisher.withdraw(&old);
+ }
+ self.publisher.publish(&ad)?;
+ *cur = Some(ad);
+ Ok(())
+ }
+
+ /// Withdraws the announcement (switch off, link stopped, app quitting). Safe to call when nothing is announced.
+ pub fn stop(&self) {
+ if let Some(ad) = self.current.lock().unwrap().take() {
+ self.publisher.withdraw(&ad);
+ }
+ }
+
+ #[cfg(test)]
+ pub fn is_advertising(&self) -> bool {
+ self.current.lock().unwrap().is_some()
+ }
+}
+
+/// The real thing: mdns-sd. A daemon exists only between `publish` and `withdraw`.
+pub struct MdnsPublisher {
+ daemon: Mutex<Option<mdns_sd::ServiceDaemon>>,
+}
+
+impl MdnsPublisher {
+ pub fn new() -> Self {
+ Self { daemon: Mutex::new(None) }
+ }
+}
+
+impl Publisher for MdnsPublisher {
+ fn publish(&self, ad: &Advert) -> Result<(), String> {
+ use mdns_sd::{IfKind, ServiceDaemon, ServiceInfo};
+ let daemon = ServiceDaemon::new().map_err(|e| e.to_string())?;
+ // The server listens on IPv4 only; announcing an IPv6 address would send the phone to a dead end.
+ let _ = daemon.disable_interface(IfKind::IPv6);
+ let info = ServiceInfo::new(SERVICE_TYPE, &ad.instance, &ad.host, "", ad.port, ad.txt.as_slice())
+ .map_err(|e| e.to_string())?
+ .enable_addr_auto();
+ if let Err(e) = daemon.register(info) {
+ let _ = daemon.shutdown();
+ return Err(e.to_string());
+ }
+ *self.daemon.lock().unwrap() = Some(daemon);
+ Ok(())
+ }
+
+ fn withdraw(&self, ad: &Advert) {
+ let Some(daemon) = self.daemon.lock().unwrap().take() else { return };
+ let fullname = format!("{}.{}", ad.instance, SERVICE_TYPE);
+ // A goodbye packet lets phones forget the service at once; then the daemon thread ends.
+ if let Ok(done) = daemon.unregister(&fullname) {
+ let _ = done.recv_timeout(Duration::from_millis(500));
+ }
+ if let Ok(done) = daemon.shutdown() {
+ let _ = done.recv_timeout(Duration::from_millis(500));
+ }
+ }
+}
+
+#[cfg(test)]
+pub mod tests {
+ use super::*;
+
+ const FP: &str = "AB12CD34EF56AB78901234567890abcdef1234567890abcdef1234567890abcd";
+ const TOKEN: &str = "tok_ABCDEFGHIJKLMNOP1234";
+
+ #[derive(Default)]
+ pub struct Recorder {
+ pub log: Mutex<Vec<String>>,
+ pub fail: Mutex<bool>,
+ }
+
+ impl Publisher for Recorder {
+ fn publish(&self, ad: &Advert) -> Result<(), String> {
+ if *self.fail.lock().unwrap() {
+ return Err("no network".into());
+ }
+ self.log.lock().unwrap().push(format!("publish {} {} {:?}", ad.instance, ad.port, ad.txt));
+ Ok(())
+ }
+ fn withdraw(&self, ad: &Advert) {
+ self.log.lock().unwrap().push(format!("withdraw {}", ad.instance));
+ }
+ }
+
+ #[test]
+ fn the_id_is_the_first_sixteen_hex_characters_in_lowercase() {
+ assert_eq!(fingerprint_id(FP).as_deref(), Some("ab12cd34ef56ab78"));
+ assert_eq!(fingerprint_id(&FP.to_lowercase()).as_deref(), Some("ab12cd34ef56ab78"));
+ assert_eq!(FP_ID_LEN, 16);
+ }
+
+ #[test]
+ fn a_fingerprint_that_is_not_hex_or_too_short_gives_no_id() {
+ assert_eq!(fingerprint_id("zz12cd34ef56ab78901234"), None);
+ assert_eq!(fingerprint_id("abcd"), None);
+ assert_eq!(fingerprint_id(""), None);
+ }
+
+ #[test]
+ fn the_txt_record_is_the_version_and_the_id_and_nothing_else() {
+ let t = txt(FP).unwrap();
+ assert_eq!(t, vec![("v".to_string(), "1".to_string()), ("fp".to_string(), "ab12cd34ef56ab78".to_string())]);
+ }
+
+ #[test]
+ fn nothing_secret_can_reach_the_announcement() {
+ // The announcement is built from the name, the port and the fingerprint only: the token and the link are
+ // not even inputs. Check the output anyway, as the rule is what matters.
+ let ad = advert("Rhytam-PC", 47821, FP).unwrap();
+ let everything = format!("{:?}", ad).to_lowercase();
+ for secret in [TOKEN.to_lowercase(), "coucou://".to_string(), "token".to_string(), "password".to_string()] {
+ assert!(!everything.contains(&secret), "announcement contains {secret}");
+ }
+ // The full certificate fingerprint is not in it either, only the short id.
+ assert!(!everything.contains(&FP.to_lowercase()));
+ assert!(ad.txt.iter().all(|(k, v)| (k == "v" || k == "fp") && v.len() <= FP_ID_LEN));
+ assert!(!ad.instance.contains('/') && !ad.instance.contains('\\'), "no path");
+ }
+
+ #[test]
+ fn the_instance_is_the_computer_name_and_the_host_a_valid_label() {
+ let ad = advert("Rhytam's PC", 47821, FP).unwrap();
+ assert_eq!(ad.instance, "Rhytam's PC");
+ assert_eq!(ad.host, "Rhytam-s-PC.local.");
+ assert_eq!(ad.port, 47821);
+ assert_eq!(host_label("***"), "coucou");
+ assert_eq!(host_label(&"a".repeat(100)).len(), 63);
+ assert_eq!(advert(" ", 1, FP).unwrap().instance, "Coucou");
+ }
+
+ #[test]
+ fn it_is_announced_on_start_and_withdrawn_on_stop() {
+ let rec = Arc::new(Recorder::default());
+ let adv = Advertiser::new(rec.clone());
+ assert!(!adv.is_advertising());
+ adv.start("PC", 47821, FP).unwrap();
+ assert!(adv.is_advertising());
+ adv.stop();
+ assert!(!adv.is_advertising());
+ adv.stop(); // nothing more to withdraw
+ let log = rec.log.lock().unwrap();
+ assert_eq!(log.len(), 2);
+ assert!(log[0].starts_with("publish PC 47821"));
+ assert_eq!(log[1], "withdraw PC");
+ }
+
+ #[test]
+ fn announcing_again_replaces_the_old_announcement() {
+ let rec = Arc::new(Recorder::default());
+ let adv = Advertiser::new(rec.clone());
+ adv.start("PC", 47821, FP).unwrap();
+ adv.start("PC", 47822, FP).unwrap();
+ let log = rec.log.lock().unwrap().clone();
+ assert_eq!(log.iter().filter(|l| l.starts_with("withdraw")).count(), 1);
+ assert!(log.last().unwrap().contains("47822"));
+ }
+
+ #[test]
+ fn a_failing_network_is_an_error_not_a_crash_and_leaves_nothing_announced() {
+ let rec = Arc::new(Recorder::default());
+ *rec.fail.lock().unwrap() = true;
+ let adv = Advertiser::new(rec.clone());
+ assert!(adv.start("PC", 47821, FP).is_err());
+ assert!(!adv.is_advertising());
+ assert!(adv.start("PC", 47821, "not a fingerprint").is_err());
+ }
+
+ #[test]
+ fn nothing_is_announced_before_start() {
+ let rec = Arc::new(Recorder::default());
+ let _adv = Advertiser::new(rec.clone());
+ assert!(rec.log.lock().unwrap().is_empty());
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/hub.rs b/windows/src-tauri/src/phone_link/hub.rs
new file mode 100644
index 00000000..d97798a2
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/hub.rs
@@ -0,0 +1,1998 @@
+// What the phone is told, and what it may decide.
+//
+// The hub holds the last list of sessions and the one permission request that is
+// still waiting, as the island published them (phone_link_publish). It knows
+// nothing about sockets or Tauri: connections subscribe to it, and a decision
+// from a phone goes back to the app through the `Host` trait. That keeps every
+// rule of docs/ANDROID_LINK.md testable without a window.
+//
+// The rules that matter:
+// * a phone decision is applied only if its fingerprint is the one of the
+// request that is *still* pending (same session, tool, command and request);
+// * only one decision is ever applied per request;
+// * a request older than APPROVAL_TTL is dismissed, whatever the phone says;
+// * nothing here can block the agent: the desktop's own card keeps working,
+// and a phone that never answers changes nothing.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+
+use ring::digest;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use tokio::sync::mpsc;
+
+/// The desktop dismisses a request after this long (the phone offers it for 120 s).
+pub const APPROVAL_TTL_MS: u64 = 115_000;
+
+const MAX_SESSIONS: usize = 16;
+const MAX_COMMAND_CHARS: usize = 500;
+const MAX_TEXT_CHARS: usize = 200;
+/// Details (cap `details`): at most this many steps per session, each cut at MAX_TEXT_CHARS.
+pub const MAX_STEPS: usize = 20;
+const MAX_PROJECT_CHARS: usize = 64;
+/// A `sessions` line with details stays under this, so it never reaches the 64 KiB limit of a line
+/// (16 sessions of 20 steps of 200 characters would be 64 KB of text alone).
+pub const DETAILS_LINE_BUDGET: usize = 56 * 1024;
+
+/// File changes (cap `diffs`): the list of files of a session, and a file's lines on request.
+pub const MAX_FILES: usize = 20;
+const MAX_FILE_NAME_CHARS: usize = 80;
+/// One file's diff: at most this many lines, each cut at MAX_DIFF_LINE_CHARS, sent in parts of PART_LINES so
+/// no line of the link nears the 64 KiB limit.
+pub const MAX_DIFF_LINES: usize = 200;
+const MAX_DIFF_LINE_CHARS: usize = 400;
+const PART_LINES: usize = 100;
+/// A phone may ask for this many diffs in 10 seconds.
+const DIFF_ASKS_PER_10S: usize = 20;
+
+/// Service cards (cap `services`): read-only snapshots of what the island's service pills show, one switch per
+/// service. These are the only ids the link will ever carry.
+pub const SERVICE_IDS: [&str; 7] = [
+ "integration_stripe", "integration_github", "integration_vercel", "integration_n8n",
+ "integration_resend", "integration_notion", "integration_calcom",
+];
+const MAX_SERVICE_ITEMS: usize = 3;
+const MAX_SERVICE_TITLE_CHARS: usize = 24;
+const MAX_SERVICE_HEADLINE_CHARS: usize = 40;
+const MAX_SERVICE_REASON_CHARS: usize = 80;
+const MAX_SERVICE_ITEM_CHARS: usize = 60;
+
+/// Questions (cap `answers`): a question that does not fit these limits is left to the island, never cut,
+/// because the answer must carry the exact text and labels back to the agent.
+pub const MAX_QUESTIONS: usize = 4;
+pub const MAX_OPTIONS: usize = 8;
+const MAX_QUESTION_CHARS: usize = 500;
+const MAX_LABEL_CHARS: usize = 120;
+const MAX_DESCRIPTION_CHARS: usize = 300;
+
+/// The states the phone draws; anything else is sent as `idle`.
+const STATES: &[&str] = &[
+ "idle", "working", "thinking", "searching", "approval", "question", "error", "finished",
+ "ratelimit", "sleeping", "dizzy",
+];
+
+/// How a decision gets back to the agent. The app's implementation answers the
+/// waiting `coucou-hook` and closes the card on the island.
+pub trait Host: Send + Sync {
+ fn decide(&self, request_id: &str, allow: bool);
+ /// A phone answered a question Claude Code asked: each question's text mapped to the label picked (a list of
+ /// labels for a multi-select), the shape AskUserQuestion takes. Only called for the question still pending.
+ /// A phone (connection `sub_id`) asked for a file's diff: the island answers through [`Hub::send_diff`].
+ fn get_diff(&self, _sub_id: u64, _pill_id: &str, _file_id: u64) {}
+
+ fn answer(&self, _request_id: &str, _answers: &serde_json::Map<String, serde_json::Value>) {}
+}
+
+/// One file a session changed, as the island has it. Only its name (never a path) is kept.
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FileIn {
+ pub id: u64,
+ pub name: String,
+ pub added: u32,
+ pub removed: u32,
+ pub too_large: bool,
+ pub is_new: bool,
+}
+
+/// One file's diff, as the island answers a phone's request: lines as [kind, text], kind one of "+", "-", " ", "@".
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+pub struct DiffIn {
+ pub pill_id: String,
+ pub file_id: u64,
+ pub name: String,
+ pub added: u32,
+ pub removed: u32,
+ pub too_large: bool,
+ /// The island no longer has this diff.
+ pub gone: bool,
+ pub lines: Vec<(String, String)>,
+}
+
+/// One agent session, as the island reports it.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SessionIn {
+ pub pill_id: String,
+ pub agent: String,
+ pub state: String,
+ pub status_text: String,
+ pub step_index: u32,
+ pub step_count: u32,
+ /// Details, sent only to phones that asked for and were offered `details`.
+ pub steps: Vec<String>,
+ pub final_line: Option<String>,
+ /// The folder the session runs in; only its last segment is ever kept.
+ pub project: Option<String>,
+ pub color: Option<String>,
+ /// The files this session changed; sent only to phones that asked for and were offered `diffs`.
+ pub files: Vec<FileIn>,
+}
+
+impl Default for SessionIn {
+ fn default() -> Self {
+ Self {
+ pill_id: String::new(),
+ agent: String::new(),
+ state: "idle".into(),
+ status_text: String::new(),
+ step_index: 0,
+ step_count: 0,
+ steps: Vec::new(),
+ final_line: None,
+ project: None,
+ color: None,
+ files: Vec::new(),
+ }
+ }
+}
+
+/// The permission request waiting on the island.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApprovalIn {
+ pub request_id: String,
+ pub session_id: String,
+ pub pill_id: String,
+ pub tool: String,
+ pub command: String,
+}
+
+/// The values the island stores for Mochi's wardrobe ("auto" follows the seasons on the phone's own calendar).
+/// Same raw values as the Mac and the PC; anything else is not sent.
+pub const OUTFIT_CHOICES: [&str; 13] = [
+ "auto", "none", "partyHat", "beanie", "crown", "sunglasses", "roundGlasses",
+ "bow", "scarf", "witchHat", "pumpkin", "santaHat", "bunnyEars",
+];
+
+fn clean_services(cards: Vec<ServiceIn>) -> Vec<ServiceIn> {
+ let mut out: Vec<ServiceIn> = Vec::new();
+ for c in cards {
+ if !SERVICE_IDS.contains(&c.id.as_str()) || out.iter().any(|o| o.id == c.id) {
+ continue;
+ }
+ let one_line = |s: &str, max: usize| -> String { clip(&s.chars().filter(|c| !c.is_control()).collect::<String>(), max).trim().to_string() };
+ out.push(ServiceIn {
+ id: c.id,
+ title: one_line(&c.title, MAX_SERVICE_TITLE_CHARS),
+ headline: one_line(&c.headline, MAX_SERVICE_HEADLINE_CHARS),
+ reason: c.reason.as_deref().map(|r| one_line(r, MAX_SERVICE_REASON_CHARS)).filter(|r| !r.is_empty()),
+ items: c
+ .items
+ .iter()
+ .map(|i| ServiceItemIn { label: one_line(&i.label, MAX_SERVICE_ITEM_CHARS), detail: one_line(&i.detail, MAX_SERVICE_ITEM_CHARS) })
+ .filter(|i| !i.label.is_empty())
+ .take(MAX_SERVICE_ITEMS)
+ .collect(),
+ });
+ }
+ out
+}
+
+/// The `services` line for a phone whose user allowed `allowed`; None when none of the cards is allowed.
+fn services_line(cards: &[ServiceIn], allowed: &[String]) -> Option<Arc<str>> {
+ let list: Vec<serde_json::Value> = cards
+ .iter()
+ .filter(|c| allowed.contains(&c.id))
+ .map(|c| {
+ let mut v = json!({
+ "id": c.id, "title": c.title, "headline": c.headline,
+ "items": c.items.iter().map(|i| json!({ "label": i.label, "detail": i.detail })).collect::<Vec<_>>(),
+ });
+ if let Some(r) = &c.reason {
+ v["reason"] = json!(r);
+ }
+ v
+ })
+ .collect();
+ if list.is_empty() {
+ return None;
+ }
+ Some(json!({ "type": "services", "services": list }).to_string().into())
+}
+
+fn window_json(w: &WindowIn) -> Option<serde_json::Value> {
+ if !w.used_pct.is_finite() || w.resets_at == 0 {
+ return None;
+ }
+ Some(json!({ "pct": w.used_pct.clamp(0.0, 100.0).round() as u32, "resetsAt": w.resets_at }))
+}
+
+fn plan_json(p: &PlanIn) -> Option<serde_json::Value> {
+ let mut v = json!({});
+ if let Some(w) = p.five_hour.as_ref().and_then(window_json) {
+ v["fiveHour"] = w;
+ }
+ if let Some(w) = p.seven_day.as_ref().and_then(window_json) {
+ v["sevenDay"] = w;
+ }
+ if v.as_object().is_some_and(|o| o.is_empty()) {
+ return None;
+ }
+ if let Some(n) = p.reset_credits {
+ v["resetCredits"] = json!(n.min(99));
+ }
+ // "plus", "pro", "max 5x": letters, digits, spaces and dashes only, short.
+ if let Some(name) = p.plan_type.as_deref() {
+ let clean: String = name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == ' ' || *c == '-').take(20).collect();
+ if !clean.trim().is_empty() {
+ v["plan"] = json!(clean.trim());
+ }
+ }
+ if p.updated_at > 0 {
+ v["updatedAt"] = json!(p.updated_at);
+ }
+ Some(v)
+}
+
+/// None when the island has no number for either plan.
+fn usage_line(u: &UsageIn) -> Option<Arc<str>> {
+ let claude = u.claude.as_ref().and_then(plan_json);
+ let codex = u.codex.as_ref().and_then(plan_json);
+ if claude.is_none() && codex.is_none() {
+ return None;
+ }
+ let mut v = json!({ "type": "usage" });
+ if let Some(c) = claude {
+ v["claude"] = c;
+ }
+ if let Some(c) = codex {
+ v["codex"] = c;
+ }
+ Some(v.to_string().into())
+}
+
+fn prefs_line(outfit: &str) -> String {
+ json!({ "type": "prefs", "outfit": outfit }).to_string()
+}
+
+/// One window of a plan (5 hours or the week): how much is used and when it resets.
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+pub struct WindowIn {
+ pub used_pct: f64,
+ /// Epoch milliseconds.
+ pub resets_at: u64,
+}
+
+/// What the island knows of one plan (Claude or Codex).
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PlanIn {
+ pub five_hour: Option<WindowIn>,
+ pub seven_day: Option<WindowIn>,
+ pub reset_credits: Option<u32>,
+ pub plan_type: Option<String>,
+ /// When the numbers arrived (epoch ms).
+ pub updated_at: u64,
+}
+
+/// The plan usage the island shows in its header (cap `usage`).
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+pub struct UsageIn {
+ pub claude: Option<PlanIn>,
+ pub codex: Option<PlanIn>,
+}
+
+/// One line of a service card.
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(default)]
+pub struct ServiceItemIn {
+ pub label: String,
+ pub detail: String,
+}
+
+/// What one service pill shows, as the island summarises it: a headline, why (optional), up to 3 lines.
+#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
+#[serde(default)]
+pub struct ServiceIn {
+ pub id: String,
+ pub title: String,
+ pub headline: String,
+ pub reason: Option<String>,
+ pub items: Vec<ServiceItemIn>,
+}
+
+/// One option of a question, as the island has it.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+pub struct OptionIn {
+ pub label: String,
+ #[serde(default)]
+ pub description: String,
+}
+
+/// One question of an AskUserQuestion call.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct QuestionItemIn {
+ pub question: String,
+ pub options: Vec<OptionIn>,
+ #[serde(default)]
+ pub multi_select: bool,
+}
+
+/// The question Claude Code is waiting on, as the island has it (cap `answers`).
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct QuestionIn {
+ pub request_id: String,
+ pub session_id: String,
+ pub pill_id: String,
+ pub questions: Vec<QuestionItemIn>,
+}
+
+struct Question {
+ request_id: String,
+ fingerprint: String,
+ pill_id: String,
+ items: Vec<QuestionItemIn>,
+ created_at: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Session {
+ pill_id: String,
+ agent: String,
+ state: String,
+ status_text: String,
+ step_index: u32,
+ step_count: u32,
+ updated_at: u64,
+ // Not part of the v1 session: added by `detailed_line` for phones that have `details`.
+ #[serde(skip)]
+ steps: Vec<String>,
+ #[serde(skip)]
+ final_line: Option<String>,
+ #[serde(skip)]
+ project: Option<String>,
+ #[serde(skip)]
+ color: Option<String>,
+ #[serde(skip)]
+ files: Vec<FileIn>,
+}
+
+impl Session {
+ fn same_content(&self, other: &Session) -> bool {
+ Session { updated_at: 0, ..self.clone() } == Session { updated_at: 0, ..other.clone() }
+ }
+}
+
+struct Approval {
+ request_id: String,
+ fingerprint: String,
+ pill_id: String,
+ tool: String,
+ command: String,
+ /// The command was longer than [`MAX_COMMAND_CHARS`] and the phone is shown only the start.
+ truncated: bool,
+ created_at: u64,
+}
+
+/// What reaches a connection's writer.
+pub enum Out {
+ /// One JSON line, without its newline.
+ Line(Arc<str>),
+ /// Tell the phone why, then close.
+ Close { code: &'static str, message: &'static str },
+}
+
+struct Sub {
+ id: u64,
+ tx: mpsc::Sender<Out>,
+ /// Set when the hub gives up on a phone that cannot keep up, so its
+ /// connection can be closed (and the phone reconnect to a fresh picture)
+ /// instead of staying open and silently going stale.
+ evicted: Arc<AtomicBool>,
+ /// The phone asked for `details` and the user's switch was on when it connected.
+ details: bool,
+ /// The phone asked for `answers` and the user's switch was on when it connected.
+ answers: bool,
+ /// The phone asked for `prefs` (the outfit Mochi wears on the computer).
+ prefs: bool,
+ /// The phone asked for `diffs` and the user's switch was on when it connected.
+ diffs: bool,
+ /// The phone asked for `usage` and the user's switch was on when it connected.
+ usage: bool,
+ /// The phone asked for `relay` and the relay switch was on when it connected: it is sent the new access key
+ /// when the user rotates it (docs/RELAY_LINK.md section 6).
+ relay: bool,
+ /// The services this phone may see (the user's ticks when it connected); empty: none.
+ services: Vec<String>,
+ /// When this phone asked for a diff lately (ms), to keep it from flooding the island.
+ diff_asks: Vec<u64>,
+}
+
+/// What a connection may have been offered.
+#[derive(Debug, Clone, Default)]
+pub struct Caps {
+ pub details: bool,
+ pub answers: bool,
+ pub prefs: bool,
+ pub diffs: bool,
+ pub usage: bool,
+ pub relay: bool,
+ /// The services the user allowed for the phone (empty: the capability is not offered).
+ pub services: Vec<String>,
+}
+
+#[derive(Default)]
+struct Inner {
+ sessions: Vec<Session>,
+ approval: Option<Approval>,
+ question: Option<Question>,
+ /// What Mochi wears on the computer: one of [`OUTFIT_CHOICES`]; None until the island has said.
+ outfit: Option<&'static str>,
+ /// The last `usage` line (None: the island has nothing to say).
+ usage: Option<Arc<str>>,
+ /// The service cards the island has, cleaned (all of them: each phone gets only the ones its user allowed).
+ services: Vec<ServiceIn>,
+ subs: Vec<Sub>,
+ next_sub: u64,
+}
+
+/// What became of a decision from a phone.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Outcome {
+ Applied,
+ /// Not the pending request (another command, or already answered).
+ NoMatch,
+ /// The request was pending but is older than APPROVAL_TTL.
+ Late,
+ /// Neither `allow` nor `deny`.
+ Invalid,
+ /// `allow` for a request whose command was cut to fit the phone: refused, and the request stays pending so it is answered here.
+ TooLong,
+}
+
+pub struct Hub {
+ host: Arc<dyn Host>,
+ inner: Mutex<Inner>,
+}
+
+impl Hub {
+ pub fn new(host: Arc<dyn Host>) -> Arc<Hub> {
+ Arc::new(Hub { host, inner: Mutex::new(Inner::default()) })
+ }
+
+ /// The island's current picture. Sends the phones only what changed.
+ pub fn publish(&self, sessions: Vec<SessionIn>, approval: Option<ApprovalIn>, now: u64) {
+ let mut inner = self.inner.lock().unwrap();
+
+ // Sessions: stamp `updatedAt` where something changed.
+ let next: Vec<Session> = sessions
+ .into_iter()
+ .filter(|s| !s.pill_id.is_empty())
+ .take(MAX_SESSIONS)
+ .map(|s| {
+ let mut fresh = Session {
+ state: if STATES.contains(&s.state.as_str()) { s.state } else { "idle".into() },
+ pill_id: s.pill_id,
+ agent: clip(&s.agent, 64),
+ status_text: clip(&s.status_text, MAX_TEXT_CHARS),
+ step_index: s.step_index,
+ step_count: s.step_count,
+ updated_at: now,
+ steps: clean_steps(&s.steps),
+ final_line: s.final_line.as_deref().map(|l| clip(l, MAX_TEXT_CHARS)).filter(|l| !l.trim().is_empty()),
+ project: s.project.as_deref().and_then(project_name),
+ color: s.color.filter(|c| is_color(c)),
+ files: clean_files(&s.files),
+ };
+ if let Some(old) = inner.sessions.iter().find(|o| o.pill_id == fresh.pill_id) {
+ if old.same_content(&fresh) {
+ fresh.updated_at = old.updated_at;
+ }
+ }
+ fresh
+ })
+ .collect();
+ let sessions_changed = next != inner.sessions;
+ inner.sessions = next;
+ if sessions_changed {
+ broadcast_sessions(&mut inner);
+ }
+
+ // The pending request: a new one replaces the old, none retracts it.
+ let same = match (&inner.approval, &approval) {
+ (Some(a), Some(b)) => a.request_id == b.request_id,
+ (None, None) => true,
+ _ => false,
+ };
+ if same {
+ return;
+ }
+ if let Some(old) = inner.approval.take() {
+ let line = resolved_line(&old.fingerprint);
+ broadcast(&mut inner, &line);
+ }
+ if let Some(a) = approval.filter(|a| !a.request_id.is_empty()) {
+ let tool = clip(&a.tool, 64);
+ let truncated = a.command.chars().count() > MAX_COMMAND_CHARS;
+ let command = clip(&a.command, MAX_COMMAND_CHARS);
+ let approval = Approval {
+ fingerprint: fingerprint(&a.pill_id, &a.session_id, &tool, &command, &a.request_id),
+ request_id: a.request_id,
+ pill_id: a.pill_id,
+ tool,
+ command,
+ truncated,
+ created_at: now,
+ };
+ let line = approval_line(&approval);
+ inner.approval = Some(approval);
+ broadcast(&mut inner, &line);
+ }
+ }
+
+ /// Registers a connection that has authenticated. The returned lines bring it
+ /// up to date: the sessions, then the request still waiting, if any.
+ #[cfg(test)]
+ pub fn subscribe(&self, tx: mpsc::Sender<Out>, now: u64, details: bool) -> (u64, Arc<AtomicBool>) {
+ self.subscribe_with(tx, now, Caps { details, ..Caps::default() })
+ }
+
+ /// Like [`subscribe`], for a phone that may also have been offered `answers` and `prefs`.
+ pub fn subscribe_with(&self, tx: mpsc::Sender<Out>, now: u64, caps: Caps) -> (u64, Arc<AtomicBool>) {
+ let Caps { details, answers, prefs, diffs, usage, relay, services } = caps;
+ let mut inner = self.inner.lock().unwrap();
+ expire(&mut inner, now);
+ let id = inner.next_sub;
+ inner.next_sub += 1;
+ let first = session_line(&inner.sessions, details, diffs);
+ let _ = tx.try_send(Out::Line(first.into()));
+ if let Some(a) = &inner.approval {
+ let _ = tx.try_send(Out::Line(approval_line(a).into()));
+ }
+ if answers {
+ if let Some(q) = &inner.question {
+ let _ = tx.try_send(Out::Line(question_line(q).into()));
+ }
+ }
+ if prefs {
+ if let Some(o) = inner.outfit {
+ let _ = tx.try_send(Out::Line(prefs_line(o).into()));
+ }
+ }
+ if !services.is_empty() {
+ if let Some(line) = services_line(&inner.services, &services) {
+ let _ = tx.try_send(Out::Line(line));
+ }
+ }
+ if usage {
+ if let Some(line) = &inner.usage {
+ let _ = tx.try_send(Out::Line(line.clone()));
+ }
+ }
+ let evicted = Arc::new(AtomicBool::new(false));
+ inner.subs.push(Sub { id, tx, evicted: evicted.clone(), details, answers, prefs, diffs, usage, relay, services, diff_asks: Vec::new() });
+ (id, evicted)
+ }
+
+ pub fn unsubscribe(&self, id: u64) {
+ self.inner.lock().unwrap().subs.retain(|s| s.id != id);
+ }
+
+ /// The access key was rotated: phones that negotiated `relay` are told the new one, inside the authenticated
+ /// channel, so they follow without scanning again. Returns how many were told.
+ pub fn send_relay_access(&self, access: &str) -> usize {
+ let line: Arc<str> = json!({ "type": "relayAccess", "access": access }).to_string().into();
+ let mut told = 0;
+ self.inner.lock().unwrap().subs.retain(|s| {
+ if !s.relay {
+ return true;
+ }
+ let kept = s.tx.try_send(Out::Line(line.clone())).is_ok();
+ if kept {
+ told += 1;
+ } else {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+ told
+ }
+
+ /// Unpaired or switched off: every connection is told and closed.
+ pub fn kick_all(&self, code: &'static str, message: &'static str) {
+ let subs = std::mem::take(&mut self.inner.lock().unwrap().subs);
+ for s in subs {
+ let _ = s.tx.try_send(Out::Close { code, message });
+ }
+ }
+
+ pub fn clients(&self) -> usize {
+ self.inner.lock().unwrap().subs.len()
+ }
+
+ /// A phone's answer. Applied only for the request that is still pending.
+ pub fn decide(&self, fingerprint: &str, decision: &str, now: u64) -> Outcome {
+ let allow = match decision {
+ "allow" => true,
+ "deny" => false,
+ _ => return Outcome::Invalid,
+ };
+ let request_id = {
+ let mut inner = self.inner.lock().unwrap();
+ let late = match &inner.approval {
+ Some(a) if constant_eq(a.fingerprint.as_bytes(), fingerprint.as_bytes()) => {
+ // A command the phone could not show in full is never allowed from the phone, whatever the phone says.
+ if allow && a.truncated {
+ return Outcome::TooLong;
+ }
+ now.saturating_sub(a.created_at) > APPROVAL_TTL_MS
+ }
+ _ => return Outcome::NoMatch,
+ };
+ // Taken in every case: a request is answered once, or dismissed.
+ let a = inner.approval.take().expect("checked above");
+ let line = resolved_line(&a.fingerprint);
+ broadcast(&mut inner, &line);
+ if late {
+ return Outcome::Late;
+ }
+ a.request_id
+ };
+ // Outside the lock: the host answers the agent and touches the island.
+ self.host.decide(&request_id, allow);
+ Outcome::Applied
+ }
+}
+
+impl Hub {
+ /// What the island's service pills show. Each phone is sent only the services its user allowed, and a phone
+ /// whose own cards did not change is sent nothing.
+ pub fn publish_services(&self, cards: Vec<ServiceIn>) {
+ let cleaned = clean_services(cards);
+ let mut inner = self.inner.lock().unwrap();
+ if cleaned == inner.services {
+ return;
+ }
+ let old = std::mem::replace(&mut inner.services, cleaned);
+ let new = inner.services.clone();
+ inner.subs.retain(|s| {
+ if s.services.is_empty() {
+ return true;
+ }
+ let before = services_line(&old, &s.services);
+ let after = services_line(&new, &s.services);
+ if before == after {
+ return true;
+ }
+ // Nothing left to show: an empty list takes the cards away.
+ let line = after.unwrap_or_else(|| json!({ "type": "services", "services": [] }).to_string().into());
+ let kept = s.tx.try_send(Out::Line(line)).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+ }
+
+ /// The plan usage the island shows (percentages and reset times, nothing else). Only phones that have `usage`
+ /// hear of it, and a new one at once; two identical pictures are sent once.
+ pub fn publish_usage(&self, usage: UsageIn) {
+ let line = usage_line(&usage);
+ let mut inner = self.inner.lock().unwrap();
+ if inner.usage.as_deref() == line.as_deref() {
+ return;
+ }
+ inner.usage = line.clone();
+ let shared: Arc<str> = line.unwrap_or_else(|| json!({ "type": "usage" }).to_string().into());
+ inner.subs.retain(|s| {
+ if !s.usage {
+ return true;
+ }
+ let kept = s.tx.try_send(Out::Line(shared.clone())).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+ }
+
+ /// A phone asked for a file's diff. Passed on to the island only if the phone has `diffs` and is not asking too often.
+ pub fn request_diff(&self, sub_id: u64, pill_id: &str, file_id: u64, now: u64) {
+ {
+ let mut inner = self.inner.lock().unwrap();
+ let Some(sub) = inner.subs.iter_mut().find(|s| s.id == sub_id && s.diffs) else { return };
+ sub.diff_asks.retain(|t| now.saturating_sub(*t) < 10_000);
+ if sub.diff_asks.len() >= DIFF_ASKS_PER_10S {
+ return;
+ }
+ sub.diff_asks.push(now);
+ }
+ // Outside the lock: the host asks the island.
+ self.host.get_diff(sub_id, pill_id, file_id);
+ }
+
+ /// The island's answer to [`request_diff`]: sent to that phone only (and only if it still has `diffs`), cut to
+ /// the limits whatever the island sent, in parts that each fit a line.
+ pub fn send_diff(&self, sub_id: u64, diff: DiffIn) {
+ let mut inner = self.inner.lock().unwrap();
+ let Some(sub) = inner.subs.iter().find(|s| s.id == sub_id && s.diffs) else { return };
+ let truncated = diff.lines.len() > MAX_DIFF_LINES;
+ let rows: Vec<serde_json::Value> = diff
+ .lines
+ .iter()
+ .take(MAX_DIFF_LINES)
+ .map(|(k, text)| {
+ let kind = match k.as_str() {
+ "+" | "-" | "@" => k.as_str(),
+ _ => " ",
+ };
+ json!([kind, clip(text, MAX_DIFF_LINE_CHARS)])
+ })
+ .collect();
+ let parts: Vec<&[serde_json::Value]> = if rows.is_empty() { vec![&[][..]] } else { rows.chunks(PART_LINES).collect() };
+ let total = parts.len();
+ let name = clean_files(&[FileIn { name: diff.name.clone(), ..FileIn::default() }]).first().map(|f| f.name.clone()).unwrap_or_default();
+ let mut ok = true;
+ for (i, part) in parts.iter().enumerate() {
+ let line = json!({
+ "type": "diff", "pillId": clip(&diff.pill_id, 64), "fileId": diff.file_id, "name": name,
+ "added": diff.added, "removed": diff.removed, "tooLarge": diff.too_large, "gone": diff.gone,
+ "truncated": truncated, "part": i, "parts": total, "lines": part,
+ })
+ .to_string();
+ ok &= sub.tx.try_send(Out::Line(line.into())).is_ok();
+ }
+ if !ok {
+ sub.evicted.store(true, Ordering::SeqCst);
+ inner.subs.retain(|s| s.id != sub_id);
+ }
+ }
+
+ /// What Mochi wears on the computer ("auto" or an outfit, see [`OUTFIT_CHOICES`]); anything else is ignored.
+ /// Only phones that have `prefs` hear of it, and a new one at once.
+ pub fn publish_outfit(&self, outfit: &str) {
+ let Some(choice) = OUTFIT_CHOICES.iter().find(|c| **c == outfit) else { return };
+ let mut inner = self.inner.lock().unwrap();
+ if inner.outfit == Some(*choice) {
+ return;
+ }
+ inner.outfit = Some(*choice);
+ let shared: Arc<str> = prefs_line(choice).into();
+ inner.subs.retain(|s| {
+ if !s.prefs {
+ return true;
+ }
+ let kept = s.tx.try_send(Out::Line(shared.clone())).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+ }
+
+ /// The question waiting on the island (None: none). Only phones that have `answers` hear of it. One that
+ /// does not fit the limits, or whose options cannot be told apart, stays on the island.
+ pub fn publish_question(&self, question: Option<QuestionIn>, now: u64) {
+ let mut inner = self.inner.lock().unwrap();
+ let usable = question.filter(|q| !q.request_id.is_empty() && fits_the_limits(&q.questions));
+ let same = match (&inner.question, &usable) {
+ (Some(a), Some(b)) => a.request_id == b.request_id,
+ (None, None) => true,
+ _ => false,
+ };
+ if same {
+ return;
+ }
+ if let Some(old) = inner.question.take() {
+ let line = resolved_line(&old.fingerprint);
+ broadcast_to_answers(&mut inner, &line);
+ }
+ if let Some(q) = usable {
+ let texts: Vec<&str> = q.questions.iter().map(|i| i.question.as_str()).collect();
+ let question = Question {
+ fingerprint: fingerprint(&q.pill_id, &q.session_id, "AskUserQuestion", &texts.join("\n"), &q.request_id),
+ request_id: q.request_id,
+ pill_id: q.pill_id,
+ items: q.questions,
+ created_at: now,
+ };
+ let line = question_line(&question);
+ inner.question = Some(question);
+ broadcast_to_answers(&mut inner, &line);
+ }
+ }
+
+ /// A phone's answer to the question that is still pending. `picks` has one list of labels per question, in order.
+ /// It is applied only if every label is exactly one of that question's options, one label for a single choice and
+ /// at least one (each at most once) for a multiple choice; anything else changes nothing.
+ pub fn answer(&self, fingerprint: &str, picks: &[Vec<String>], now: u64) -> Outcome {
+ let (request_id, answers) = {
+ let mut inner = self.inner.lock().unwrap();
+ let (late, answers) = match &inner.question {
+ Some(q) if constant_eq(q.fingerprint.as_bytes(), fingerprint.as_bytes()) => {
+ let Some(answers) = build_answers(&q.items, picks) else { return Outcome::Invalid };
+ (now.saturating_sub(q.created_at) > APPROVAL_TTL_MS, answers)
+ }
+ _ => return Outcome::NoMatch,
+ };
+ // Taken in every case: a question is answered once, or dismissed.
+ let q = inner.question.take().expect("checked above");
+ let line = resolved_line(&q.fingerprint);
+ broadcast_to_answers(&mut inner, &line);
+ if late {
+ return Outcome::Late;
+ }
+ (q.request_id, answers)
+ };
+ self.host.answer(&request_id, &answers);
+ Outcome::Applied
+ }
+}
+
+fn fits_the_limits(items: &[QuestionItemIn]) -> bool {
+ !items.is_empty()
+ && items.len() <= MAX_QUESTIONS
+ && items.iter().all(|i| {
+ let labels: Vec<&str> = i.options.iter().map(|o| o.label.as_str()).collect();
+ !i.question.trim().is_empty()
+ && i.question.chars().count() <= MAX_QUESTION_CHARS
+ && !labels.is_empty()
+ && labels.len() <= MAX_OPTIONS
+ && labels.iter().all(|l| !l.trim().is_empty() && l.chars().count() <= MAX_LABEL_CHARS)
+ && i.options.iter().all(|o| o.description.chars().count() <= MAX_DESCRIPTION_CHARS)
+ // two options with the same label could not be told apart in an answer
+ && labels.iter().enumerate().all(|(n, l)| !labels[..n].contains(l))
+ })
+}
+
+fn build_answers(items: &[QuestionItemIn], picks: &[Vec<String>]) -> Option<serde_json::Map<String, serde_json::Value>> {
+ if picks.len() != items.len() {
+ return None;
+ }
+ let mut out = serde_json::Map::new();
+ for (item, chosen) in items.iter().zip(picks) {
+ if chosen.is_empty() || chosen.len() > item.options.len() || (!item.multi_select && chosen.len() != 1) {
+ return None;
+ }
+ for (n, label) in chosen.iter().enumerate() {
+ if !item.options.iter().any(|o| &o.label == label) || chosen[..n].contains(label) {
+ return None;
+ }
+ }
+ let value = if item.multi_select { json!(chosen) } else { json!(chosen[0]) };
+ out.insert(item.question.clone(), value);
+ }
+ Some(out)
+}
+
+fn question_line(q: &Question) -> String {
+ let questions: Vec<serde_json::Value> = q
+ .items
+ .iter()
+ .map(|i| {
+ json!({
+ "question": i.question, "multiSelect": i.multi_select,
+ "options": i.options.iter().map(|o| json!({ "label": o.label, "description": o.description })).collect::<Vec<_>>(),
+ })
+ })
+ .collect();
+ json!({ "type": "question", "pillId": q.pill_id, "fingerprint": q.fingerprint, "createdAt": q.created_at, "questions": questions }).to_string()
+}
+
+/// To the phones that have `answers` only: the others never learn a question existed.
+fn broadcast_to_answers(inner: &mut Inner, line: &str) {
+ let shared: Arc<str> = line.into();
+ inner.subs.retain(|s| {
+ if !s.answers {
+ return true;
+ }
+ let kept = s.tx.try_send(Out::Line(shared.clone())).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+}
+
+fn expire(inner: &mut Inner, now: u64) {
+ if inner.question.as_ref().is_some_and(|q| now.saturating_sub(q.created_at) > APPROVAL_TTL_MS) {
+ let q = inner.question.take().expect("checked above");
+ let line = resolved_line(&q.fingerprint);
+ broadcast_to_answers(inner, &line);
+ }
+ if inner.approval.as_ref().is_some_and(|a| now.saturating_sub(a.created_at) > APPROVAL_TTL_MS) {
+ let a = inner.approval.take().expect("checked above");
+ let line = resolved_line(&a.fingerprint);
+ broadcast(inner, &line);
+ }
+}
+
+/// Sends one line to every subscriber; one that cannot keep up (a full queue) or
+/// has gone is dropped rather than waited for.
+fn broadcast(inner: &mut Inner, line: &str) {
+ let shared: Arc<str> = line.into();
+ inner.subs.retain(|s| {
+ let kept = s.tx.try_send(Out::Line(shared.clone())).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+}
+
+fn sessions_line(sessions: &[Session]) -> String {
+ json!({ "type": "sessions", "sessions": sessions }).to_string()
+}
+
+/// The sessions with their details, for a phone that has the capability. Same fields as the v1 line plus
+/// `steps`, `finalLine`, `project` and `color` where there is something to say. Steps are dropped from the
+/// oldest first (and then from all sessions) until the line fits.
+fn detailed_line(sessions: &[Session], details: bool, diffs: bool) -> String {
+ let mut keep = MAX_STEPS;
+ loop {
+ let list: Vec<serde_json::Value> = sessions
+ .iter()
+ .map(|s| {
+ let mut v = serde_json::to_value(s).unwrap_or_default();
+ if details {
+ let steps = &s.steps[s.steps.len().saturating_sub(keep)..];
+ if !steps.is_empty() {
+ v["steps"] = json!(steps);
+ }
+ if let Some(l) = &s.final_line {
+ v["finalLine"] = json!(l);
+ }
+ if let Some(p) = &s.project {
+ v["project"] = json!(p);
+ }
+ if let Some(c) = &s.color {
+ v["color"] = json!(c);
+ }
+ }
+ if diffs && !s.files.is_empty() {
+ v["files"] = json!(s.files.iter().map(file_json).collect::<Vec<_>>());
+ }
+ v
+ })
+ .collect();
+ let line = json!({ "type": "sessions", "sessions": list }).to_string();
+ if line.len() <= DETAILS_LINE_BUDGET || keep == 0 {
+ return line;
+ }
+ keep /= 2;
+ }
+}
+
+fn file_json(f: &FileIn) -> serde_json::Value {
+ let mut v = json!({ "id": f.id, "name": f.name, "added": f.added, "removed": f.removed });
+ if f.too_large {
+ v["tooLarge"] = json!(true);
+ }
+ if f.is_new {
+ v["isNew"] = json!(true);
+ }
+ v
+}
+
+/// The `sessions` line a phone gets: the v1 line, or the one with what it was offered.
+fn session_line(sessions: &[Session], details: bool, diffs: bool) -> String {
+ if details || diffs {
+ detailed_line(sessions, details, diffs)
+ } else {
+ sessions_line(sessions)
+ }
+}
+
+/// Every phone gets the picture it asked for: the v1 line, or the one with details and/or file changes.
+fn broadcast_sessions(inner: &mut Inner) {
+ let mut lines: std::collections::HashMap<(bool, bool), Arc<str>> = std::collections::HashMap::new();
+ let sessions = std::mem::take(&mut inner.sessions);
+ for s in &inner.subs {
+ lines.entry((s.details, s.diffs)).or_insert_with(|| session_line(&sessions, s.details, s.diffs).into());
+ }
+ inner.sessions = sessions;
+ inner.subs.retain(|s| {
+ let line = lines[&(s.details, s.diffs)].clone();
+ let kept = s.tx.try_send(Out::Line(line)).is_ok();
+ if !kept {
+ s.evicted.store(true, Ordering::SeqCst);
+ }
+ kept
+ });
+}
+
+/// At most MAX_FILES files with a name; only the file's name, cut, never a path.
+fn clean_files(files: &[FileIn]) -> Vec<FileIn> {
+ let kept: Vec<FileIn> = files
+ .iter()
+ .filter_map(|f| {
+ let last = f.name.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().unwrap_or("").trim();
+ let name: String = last.chars().filter(|c| !c.is_control()).take(MAX_FILE_NAME_CHARS).collect();
+ (!name.is_empty()).then(|| FileIn { name, ..f.clone() })
+ })
+ .collect();
+ kept[kept.len().saturating_sub(MAX_FILES)..].to_vec()
+}
+
+/// The last MAX_STEPS non-empty steps, each cut to MAX_TEXT_CHARS.
+fn clean_steps(steps: &[String]) -> Vec<String> {
+ let kept: Vec<String> = steps.iter().filter(|s| !s.trim().is_empty()).map(|s| clip(s, MAX_TEXT_CHARS)).collect();
+ kept[kept.len().saturating_sub(MAX_STEPS)..].to_vec()
+}
+
+/// Only the last segment of a folder path: never a path, never anything that could hold a user name or
+/// a drive. None when nothing usable is left.
+pub fn project_name(path: &str) -> Option<String> {
+ let last = path.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().unwrap_or("");
+ let clean: String = last.chars().filter(|c| !c.is_control()).collect();
+ let clean = clip(clean.trim(), MAX_PROJECT_CHARS);
+ (!clean.is_empty() && clean != "." && clean != "..").then_some(clean)
+}
+
+/// "#RRGGBB" only.
+fn is_color(c: &str) -> bool {
+ c.len() == 7 && c.starts_with('#') && c[1..].bytes().all(|b| b.is_ascii_hexdigit())
+}
+
+fn approval_line(a: &Approval) -> String {
+ json!({
+ "type": "approval", "pillId": a.pill_id, "fingerprint": a.fingerprint,
+ "tool": a.tool, "command": a.command, "truncated": a.truncated, "createdAt": a.created_at,
+ })
+ .to_string()
+}
+
+fn resolved_line(fingerprint: &str) -> String {
+ json!({ "type": "approvalResolved", "fingerprint": fingerprint }).to_string()
+}
+
+/// The first `max` characters, on a character boundary.
+fn clip(s: &str, max: usize) -> String {
+ match s.char_indices().nth(max) {
+ Some((i, _)) => s[..i].to_string(),
+ None => s.to_string(),
+ }
+}
+
+/// The Mac's `ApprovalRelay.fingerprint`: lowercase hex SHA-256 of the fields
+/// joined by U+001F. `input_key` is the island's request id, so two requests for
+/// the same command still have different fingerprints and a late decision for the
+/// first can never answer the second.
+pub fn fingerprint(pill_id: &str, session_id: &str, tool: &str, command: &str, input_key: &str) -> String {
+ let joined = [pill_id, session_id, tool, command, input_key].join("\u{1f}");
+ hex(digest::digest(&digest::SHA256, joined.as_bytes()).as_ref())
+}
+
+pub fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// Constant-time equality, so a token or fingerprint cannot be guessed byte by byte.
+pub fn constant_eq(a: &[u8], b: &[u8]) -> bool {
+ // The length is not secret (tokens and fingerprints have a fixed size).
+ a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex as StdMutex;
+
+ #[derive(Default)]
+ struct Recorder(StdMutex<Vec<(String, bool)>>, StdMutex<Vec<(u64, String, u64)>>);
+ impl Host for Recorder {
+ fn decide(&self, request_id: &str, allow: bool) {
+ self.0.lock().unwrap().push((request_id.to_string(), allow));
+ }
+ fn get_diff(&self, sub_id: u64, pill_id: &str, file_id: u64) {
+ self.1.lock().unwrap().push((sub_id, pill_id.to_string(), file_id));
+ }
+ }
+
+ fn hub() -> (Arc<Hub>, Arc<Recorder>) {
+ let rec = Arc::new(Recorder::default());
+ (Hub::new(rec.clone()), rec)
+ }
+
+ fn approval(request: &str, command: &str) -> ApprovalIn {
+ ApprovalIn {
+ request_id: request.into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ tool: "Bash".into(),
+ command: command.into(),
+ }
+ }
+
+ fn session(state: &str) -> SessionIn {
+ SessionIn { pill_id: "integration_claude".into(), agent: "Claude Code".into(), state: state.into(), ..Default::default() }
+ }
+
+ fn drain(rx: &mut mpsc::Receiver<Out>) -> Vec<serde_json::Value> {
+ let mut v = Vec::new();
+ while let Ok(o) = rx.try_recv() {
+ if let Out::Line(l) = o {
+ v.push(serde_json::from_str(&l).unwrap());
+ }
+ }
+ v
+ }
+
+ fn fp_of(hub: &Hub) -> String {
+ hub.inner.lock().unwrap().approval.as_ref().unwrap().fingerprint.clone()
+ }
+
+ // ── session details (cap `details`) ─────────────────────────────────────────────
+
+ fn rich(pill: &str) -> SessionIn {
+ SessionIn {
+ pill_id: pill.into(),
+ agent: "Claude Code".into(),
+ state: "working".into(),
+ status_text: "Editing".into(),
+ step_index: 1,
+ step_count: 3,
+ steps: vec!["Read · a.rs".into(), "Edit · a.rs".into()],
+ final_line: Some("All done".into()),
+ project: Some("/home/me/work/coucou".into()),
+ color: Some("#2DD4BF".into()),
+ ..Default::default()
+ }
+ }
+
+ fn first_sessions(rx: &mut mpsc::Receiver<Out>) -> Vec<serde_json::Value> {
+ let lines = drain(rx);
+ lines[0]["sessions"].as_array().unwrap().clone()
+ }
+
+ #[test]
+ fn a_phone_without_details_gets_exactly_the_v1_fields() {
+ let (hub, _) = hub();
+ hub.publish(vec![rich("integration_claude")], None, 1_000);
+ let (tx, mut rx) = mpsc::channel(8);
+ hub.subscribe(tx, 1_001, false);
+ let s = &first_sessions(&mut rx)[0];
+ let mut keys: Vec<&str> = s.as_object().unwrap().keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ assert_eq!(keys, ["agent", "pillId", "state", "statusText", "stepCount", "stepIndex", "updatedAt"]);
+ }
+
+ #[test]
+ fn a_phone_with_details_gets_them_and_the_other_phone_does_not() {
+ let (hub, _) = hub();
+ let (tx1, mut plain) = mpsc::channel(8);
+ let (tx2, mut rich_rx) = mpsc::channel(8);
+ hub.subscribe(tx1, 0, false);
+ hub.subscribe(tx2, 0, true);
+ drain(&mut plain);
+ drain(&mut rich_rx);
+ hub.publish(vec![rich("integration_claude")], None, 1_000);
+ let p = &first_sessions(&mut plain)[0];
+ let r = &first_sessions(&mut rich_rx)[0];
+ assert!(p.get("steps").is_none() && p.get("finalLine").is_none() && p.get("project").is_none() && p.get("color").is_none());
+ assert_eq!(r["steps"], json!(["Read · a.rs", "Edit · a.rs"]));
+ assert_eq!(r["finalLine"], "All done");
+ assert_eq!(r["project"], "coucou");
+ assert_eq!(r["color"], "#2DD4BF");
+ // and the shared fields are the same for both
+ assert_eq!(p["statusText"], r["statusText"]);
+ }
+
+ #[test]
+ fn a_new_phone_with_details_is_brought_up_to_date_with_them() {
+ let (hub, _) = hub();
+ hub.publish(vec![rich("integration_claude")], None, 1_000);
+ let (tx, mut rx) = mpsc::channel(8);
+ hub.subscribe(tx, 1_001, true);
+ assert_eq!(first_sessions(&mut rx)[0]["project"], "coucou");
+ }
+
+ #[test]
+ fn a_change_in_details_alone_is_sent() {
+ let (hub, _) = hub();
+ let (tx, mut rx) = mpsc::channel(8);
+ hub.subscribe(tx, 0, true);
+ drain(&mut rx);
+ hub.publish(vec![rich("a")], None, 1_000);
+ assert_eq!(drain(&mut rx).len(), 1);
+ hub.publish(vec![rich("a")], None, 2_000);
+ assert!(drain(&mut rx).is_empty(), "same picture: nothing sent");
+ let mut changed = rich("a");
+ changed.final_line = Some("Another".into());
+ hub.publish(vec![changed], None, 3_000);
+ assert_eq!(drain(&mut rx).len(), 1);
+ }
+
+ #[test]
+ fn only_the_last_twenty_steps_are_kept_each_cut_short_and_empties_dropped() {
+ let mut s = rich("a");
+ s.steps = (0..30).map(|i| format!("step {i}")).chain([String::new(), " ".into(), "x".repeat(500)]).collect();
+ let steps = clean_steps(&s.steps);
+ assert_eq!(steps.len(), MAX_STEPS);
+ assert_eq!(steps.last().unwrap().chars().count(), MAX_TEXT_CHARS);
+ assert_eq!(steps[0], "step 11");
+ assert!(clean_steps(&[]).is_empty());
+ }
+
+ #[test]
+ fn the_project_is_a_folder_name_never_a_path() {
+ assert_eq!(project_name("/home/me/work/coucou").as_deref(), Some("coucou"));
+ assert_eq!(project_name("/home/me/work/coucou/").as_deref(), Some("coucou"));
+ assert_eq!(project_name("C:\\Users\\me\\proj").as_deref(), Some("proj"));
+ assert_eq!(project_name("C:\\Users\\me\\proj\\").as_deref(), Some("proj"));
+ assert_eq!(project_name("proj").as_deref(), Some("proj"));
+ assert_eq!(project_name("/a/b\tc\n").as_deref(), Some("bc"));
+ for none in ["", "/", "\\", "..", "/a/..", ".", " "] {
+ assert_eq!(project_name(none), None, "{none:?}");
+ }
+ let long = project_name(&format!("/x/{}", "é".repeat(200))).unwrap();
+ assert_eq!(long.chars().count(), MAX_PROJECT_CHARS);
+ for p in ["/home/me/secret/app", "C:\\Users\\me\\app", "relative/dir/app"] {
+ let name = project_name(p).unwrap();
+ assert!(!name.contains('/') && !name.contains('\\') && name == "app");
+ }
+ }
+
+ #[test]
+ fn only_a_six_digit_hex_colour_is_passed_on() {
+ for ok in ["#8AB4F8", "#000000", "#abcdef"] {
+ assert!(is_color(ok), "{ok}");
+ }
+ for bad in ["", "red", "8AB4F8", "#12", "#GGGGGG", "#12345678", "#8AB4F8;", "url(x)"] {
+ assert!(!is_color(bad), "{bad}");
+ }
+ let (hub, _) = hub();
+ let mut s = rich("a");
+ s.color = Some("red".into());
+ hub.publish(vec![s], None, 1_000);
+ let (tx, mut rx) = mpsc::channel(8);
+ hub.subscribe(tx, 1_001, true);
+ assert!(first_sessions(&mut rx)[0].get("color").is_none());
+ }
+
+ #[test]
+ fn sixteen_sessions_of_full_steps_still_fit_in_one_line() {
+ let big = |i: usize| SessionIn {
+ steps: (0..30).map(|n| format!("{n}: {}", "é".repeat(300))).collect(),
+ final_line: Some("f".repeat(400)),
+ ..rich(&format!("agent_{i}"))
+ };
+ let sessions: Vec<SessionIn> = (0..20).map(big).collect();
+ let (hub, _) = hub();
+ hub.publish(sessions, None, 1_000);
+ let (tx, mut rx) = mpsc::channel(8);
+ hub.subscribe(tx, 1_001, true);
+ let Out::Line(line) = rx.try_recv().unwrap() else { panic!() };
+ assert!(line.len() <= DETAILS_LINE_BUDGET, "{} bytes", line.len());
+ assert!(line.len() < 64 * 1024);
+ let v: serde_json::Value = serde_json::from_str(&line).unwrap();
+ let list = v["sessions"].as_array().unwrap();
+ assert_eq!(list.len(), MAX_SESSIONS);
+ // the newest steps are the ones kept
+ let steps = list[0]["steps"].as_array().unwrap();
+ assert!(!steps.is_empty() && steps.len() < MAX_STEPS);
+ assert!(steps.last().unwrap().as_str().unwrap().starts_with("29: "));
+ // and the short fields are all still there
+ assert_eq!(list[15]["project"], "coucou");
+ }
+
+ #[test]
+ fn the_fingerprint_is_the_macs_derivation() {
+ // Computed independently of this code:
+ // printf 'integration_claude\x1fs1\x1fBash\x1fnpm test\x1fr1' | sha256sum
+ assert_eq!(
+ fingerprint("integration_claude", "s1", "Bash", "npm test", "r1"),
+ "fa8a3bd8b520efb235b0d275403779ce580d2acbb934f4874f222f434b639c54"
+ );
+ }
+
+ #[test]
+ fn a_command_longer_than_the_phone_shows_is_flagged_and_cannot_be_allowed_from_the_phone() {
+ for len in [MAX_COMMAND_CHARS + 1, 10_000] {
+ let (hub, rec) = hub();
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 0, false);
+ drain(&mut rx);
+ let command = format!("{}{}", "a".repeat(MAX_COMMAND_CHARS - 1), "é".repeat(len - MAX_COMMAND_CHARS + 1));
+ hub.publish(vec![], Some(approval("r1", &command)), 1_000);
+ let line = drain(&mut rx).into_iter().find(|l| l["type"] == "approval").expect("the approval is sent");
+ assert_eq!(line["truncated"], true, "{len} characters");
+ assert_eq!(line["command"].as_str().unwrap().chars().count(), MAX_COMMAND_CHARS);
+ let fp = fp_of(&hub);
+ // Allow is refused, whatever the phone says; nothing reaches the agent and the request stays pending.
+ assert_eq!(hub.decide(&fp, "allow", 2_000), Outcome::TooLong);
+ assert!(rec.0.lock().unwrap().is_empty());
+ assert_eq!(fp_of(&hub), fp);
+ // Deny is always possible, and so is answering on the computer.
+ assert_eq!(hub.decide(&fp, "deny", 2_100), Outcome::Applied);
+ assert_eq!(*rec.0.lock().unwrap(), vec![("r1".to_string(), false)]);
+ }
+ }
+
+ #[test]
+ fn a_command_that_fits_is_not_flagged_and_can_be_allowed() {
+ for len in [0, 1, MAX_COMMAND_CHARS] {
+ let (hub, rec) = hub();
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 0, false);
+ drain(&mut rx);
+ hub.publish(vec![], Some(approval("r1", &"é".repeat(len))), 1_000);
+ let line = drain(&mut rx).into_iter().find(|l| l["type"] == "approval").unwrap();
+ assert_eq!(line["truncated"], false, "{len} characters");
+ assert_eq!(hub.decide(&fp_of(&hub), "allow", 2_000), Outcome::Applied);
+ assert_eq!(rec.0.lock().unwrap().len(), 1);
+ }
+ }
+
+ #[test]
+ fn a_phone_that_connects_later_is_also_told_the_command_is_cut() {
+ let (hub, _rec) = hub();
+ hub.publish(vec![], Some(approval("r1", &"x".repeat(10_000))), 1_000);
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 1_001, false);
+ let line = drain(&mut rx).into_iter().find(|l| l["type"] == "approval").expect("the pending request is offered");
+ assert_eq!(line["truncated"], true);
+ }
+
+ #[test]
+ fn a_matching_decision_is_applied_once() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ let fp = fp_of(&hub);
+ assert_eq!(hub.decide(&fp, "allow", 2_000), Outcome::Applied);
+ assert_eq!(*rec.0.lock().unwrap(), vec![("r1".to_string(), true)]);
+ // The second answer, from the same or another phone, finds nothing pending.
+ assert_eq!(hub.decide(&fp, "deny", 2_001), Outcome::NoMatch);
+ assert_eq!(rec.0.lock().unwrap().len(), 1);
+ }
+
+ #[test]
+ fn a_fingerprint_that_does_not_match_changes_nothing() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ // The same command asked again later is another request: its fingerprint differs.
+ let other = fingerprint("integration_claude", "s1", "Bash", "npm test", "r2");
+ assert_eq!(hub.decide(&other, "allow", 1_500), Outcome::NoMatch);
+ assert_eq!(hub.decide("", "allow", 1_500), Outcome::NoMatch);
+ assert_eq!(hub.decide(&"0".repeat(64), "allow", 1_500), Outcome::NoMatch);
+ assert!(rec.0.lock().unwrap().is_empty());
+ // The real one is still pending afterwards.
+ assert_eq!(hub.decide(&fp_of(&hub), "deny", 1_600), Outcome::Applied);
+ }
+
+ #[test]
+ fn a_decision_for_a_replaced_request_is_ignored() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "rm -rf build")), 1_000);
+ let first = fp_of(&hub);
+ hub.publish(vec![], Some(approval("r2", "ls")), 2_000);
+ assert_eq!(hub.decide(&first, "allow", 2_100), Outcome::NoMatch);
+ assert!(rec.0.lock().unwrap().is_empty());
+ }
+
+ #[test]
+ fn a_decision_after_the_island_answered_is_ignored() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ let fp = fp_of(&hub);
+ // Answered on the desktop: the island publishes no request any more.
+ hub.publish(vec![], None, 3_000);
+ assert_eq!(hub.decide(&fp, "allow", 3_500), Outcome::NoMatch);
+ assert!(rec.0.lock().unwrap().is_empty());
+ }
+
+ #[test]
+ fn a_late_decision_is_ignored_and_the_request_dismissed() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ let fp = fp_of(&hub);
+ assert_eq!(hub.decide(&fp, "allow", 1_000 + APPROVAL_TTL_MS + 1), Outcome::Late);
+ assert!(rec.0.lock().unwrap().is_empty());
+ assert_eq!(hub.decide(&fp, "allow", 1_000 + APPROVAL_TTL_MS + 2), Outcome::NoMatch);
+ }
+
+ #[test]
+ fn exactly_at_the_limit_is_still_in_time() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ assert_eq!(hub.decide(&fp_of(&hub), "allow", 1_000 + APPROVAL_TTL_MS), Outcome::Applied);
+ assert_eq!(rec.0.lock().unwrap().len(), 1);
+ }
+
+ #[test]
+ fn only_allow_and_deny_exist() {
+ let (hub, rec) = hub();
+ hub.publish(vec![], Some(approval("r1", "npm test")), 1_000);
+ let fp = fp_of(&hub);
+ for odd in ["always", "ALLOW", "", "allow ", "yes"] {
+ assert_eq!(hub.decide(&fp, odd, 1_100), Outcome::Invalid, "{odd:?}");
+ }
+ assert!(rec.0.lock().unwrap().is_empty());
+ // Still pending after the refused attempts.
+ assert_eq!(hub.decide(&fp, "deny", 1_200), Outcome::Applied);
+ assert_eq!(rec.0.lock().unwrap()[0], ("r1".to_string(), false));
+ }
+
+ #[test]
+ fn phones_are_told_what_changed_and_only_that() {
+ let (hub, _) = hub();
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.publish(vec![session("working")], None, 1_000);
+ hub.subscribe(tx, 1_001, false);
+ let first = drain(&mut rx);
+ assert_eq!(first.len(), 1);
+ assert_eq!(first[0]["type"], "sessions");
+ assert_eq!(first[0]["sessions"][0]["updatedAt"], 1_000);
+
+ // Nothing changed: nothing sent, and `updatedAt` stays.
+ hub.publish(vec![session("working")], None, 5_000);
+ assert!(drain(&mut rx).is_empty());
+
+ hub.publish(vec![session("finished")], None, 6_000);
+ let next = drain(&mut rx);
+ assert_eq!(next[0]["sessions"][0]["state"], "finished");
+ assert_eq!(next[0]["sessions"][0]["updatedAt"], 6_000);
+
+ hub.publish(vec![session("finished")], Some(approval("r1", "ls")), 7_000);
+ let a = drain(&mut rx);
+ assert_eq!(a.len(), 1);
+ assert_eq!(a[0]["type"], "approval");
+ assert_eq!(a[0]["command"], "ls");
+ assert_eq!(a[0]["createdAt"], 7_000);
+ let fp = a[0]["fingerprint"].as_str().unwrap().to_string();
+
+ hub.publish(vec![session("finished")], None, 8_000);
+ let gone = drain(&mut rx);
+ assert_eq!(gone[0]["type"], "approvalResolved");
+ assert_eq!(gone[0]["fingerprint"], fp);
+ }
+
+ #[test]
+ fn a_phone_that_connects_late_still_sees_the_pending_request() {
+ let (hub, _) = hub();
+ hub.publish(vec![session("approval")], Some(approval("r1", "ls")), 1_000);
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 2_000, false);
+ let lines = drain(&mut rx);
+ assert_eq!(lines.iter().map(|l| l["type"].as_str().unwrap()).collect::<Vec<_>>(), ["sessions", "approval"]);
+ // A request already past its time is not offered.
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 1_000 + APPROVAL_TTL_MS + 1, false);
+ assert_eq!(drain(&mut rx).iter().filter(|l| l["type"] == "approval").count(), 0);
+ }
+
+ #[test]
+ fn what_the_island_sends_is_bounded_and_cleaned() {
+ let (hub, _) = hub();
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe(tx, 0, false);
+ drain(&mut rx);
+ let many: Vec<SessionIn> = (0..40)
+ .map(|i| SessionIn { pill_id: format!("agent_{i}"), state: "not-a-state".into(), ..Default::default() })
+ .chain([SessionIn::default()]) // no pill id: dropped
+ .collect();
+ hub.publish(many, Some(approval("r1", &"é".repeat(5_000))), 1_000);
+ let lines = drain(&mut rx);
+ assert_eq!(lines[0]["sessions"].as_array().unwrap().len(), MAX_SESSIONS);
+ assert_eq!(lines[0]["sessions"][0]["state"], "idle");
+ assert_eq!(lines[1]["command"].as_str().unwrap().chars().count(), MAX_COMMAND_CHARS);
+ }
+
+ #[test]
+ fn a_phone_that_cannot_keep_up_is_dropped_not_waited_for() {
+ let (hub, _) = hub();
+ let (tx, _rx) = mpsc::channel(2); // never read
+ hub.subscribe(tx, 0, false);
+ assert_eq!(hub.clients(), 1);
+ for i in 0..5 {
+ hub.publish(vec![session("working")], None, 1_000);
+ hub.publish(vec![SessionIn { status_text: format!("{i}"), ..session("working") }], None, 1_000);
+ }
+ assert_eq!(hub.clients(), 0);
+ }
+
+ #[test]
+ fn a_phone_that_was_dropped_is_marked_so_its_connection_can_close() {
+ let (hub, _) = hub();
+ let (tx, _rx) = mpsc::channel(1); // never read
+ let (_, evicted) = hub.subscribe(tx, 0, false);
+ assert!(!evicted.load(Ordering::SeqCst));
+ for i in 0..4 {
+ hub.publish(vec![SessionIn { status_text: format!("{i}"), ..session("working") }], None, 1_000);
+ }
+ assert!(evicted.load(Ordering::SeqCst), "a dropped phone must be told apart from a healthy one");
+ // A healthy phone is never marked.
+ let (tx, mut rx) = mpsc::channel(16);
+ let (_, ok) = hub.subscribe(tx, 0, false);
+ hub.publish(vec![session("finished")], None, 2_000);
+ drain(&mut rx);
+ assert!(!ok.load(Ordering::SeqCst));
+ }
+
+ #[test]
+ fn kicking_tells_every_phone_why() {
+ let (hub, _) = hub();
+ let (tx, mut rx) = mpsc::channel(4);
+ hub.subscribe(tx, 0, false);
+ hub.kick_all("auth", "unpaired");
+ assert_eq!(hub.clients(), 0);
+ let mut saw = false;
+ while let Ok(o) = rx.try_recv() {
+ if let Out::Close { code, .. } = o {
+ saw = code == "auth";
+ }
+ }
+ assert!(saw);
+ }
+
+ #[test]
+ fn constant_time_comparison_still_compares() {
+ assert!(constant_eq(b"abc", b"abc"));
+ assert!(!constant_eq(b"abc", b"abd"));
+ assert!(!constant_eq(b"abc", b"abcd"));
+ assert!(!constant_eq(b"", b"a"));
+ }
+
+ // ── questions (cap `answers`) ───────────────────────────────────────────────────
+
+ #[derive(Default)]
+ struct AnswerRecorder(StdMutex<Vec<(String, serde_json::Value)>>);
+ impl Host for AnswerRecorder {
+ fn decide(&self, _: &str, _: bool) {}
+ fn answer(&self, request_id: &str, answers: &serde_json::Map<String, serde_json::Value>) {
+ self.0.lock().unwrap().push((request_id.to_string(), serde_json::Value::Object(answers.clone())));
+ }
+ }
+
+ fn ask(request: &str) -> QuestionIn {
+ QuestionIn {
+ request_id: request.into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ questions: vec![QuestionItemIn {
+ question: "Which?".into(),
+ options: vec![OptionIn { label: "A".into(), description: String::new() }, OptionIn { label: "B".into(), description: "bee".into() }],
+ multi_select: false,
+ }],
+ }
+ }
+
+ fn qhub() -> (Arc<Hub>, Arc<AnswerRecorder>, mpsc::Receiver<Out>) {
+ let rec = Arc::new(AnswerRecorder::default());
+ let hub = Hub::new(rec.clone());
+ let (tx, rx) = mpsc::channel(16);
+ hub.subscribe_with(tx, 1_000, Caps { answers: true, ..Caps::default() });
+ (hub, rec, rx)
+ }
+
+ fn qfp(hub: &Hub) -> String {
+ hub.inner.lock().unwrap().question.as_ref().unwrap().fingerprint.clone()
+ }
+
+ #[test]
+ fn an_answer_older_than_the_limit_is_not_applied() {
+ let (hub, rec, mut rx) = qhub();
+ hub.publish_question(Some(ask("r1")), 1_000);
+ let fp = qfp(&hub);
+ assert_eq!(hub.answer(&fp, &[vec!["A".into()]], 1_000 + APPROVAL_TTL_MS + 1), Outcome::Late);
+ assert!(rec.0.lock().unwrap().is_empty());
+ let lines = drain(&mut rx);
+ assert_eq!(lines.last().unwrap()["type"], "approvalResolved");
+ }
+
+ #[test]
+ fn a_new_question_replaces_the_old_and_none_withdraws_it() {
+ let (hub, rec, mut rx) = qhub();
+ hub.publish_question(Some(ask("r1")), 1_000);
+ let first = qfp(&hub);
+ hub.publish_question(Some(ask("r1")), 1_001); // the same request again: nothing new
+ hub.publish_question(Some(ask("r2")), 1_002);
+ let second = qfp(&hub);
+ assert_ne!(first, second);
+ assert_eq!(hub.answer(&first, &[vec!["A".into()]], 1_003), Outcome::NoMatch, "the old one cannot be answered any more");
+ hub.publish_question(None, 1_004);
+ assert_eq!(hub.answer(&second, &[vec!["A".into()]], 1_005), Outcome::NoMatch);
+ assert!(rec.0.lock().unwrap().is_empty());
+ let types: Vec<String> = drain(&mut rx).iter().map(|l| l["type"].as_str().unwrap().to_string()).collect();
+ assert_eq!(types.iter().filter(|t| *t == "question").count(), 2);
+ assert_eq!(types.iter().filter(|t| *t == "approvalResolved").count(), 2);
+ }
+
+ #[test]
+ fn the_question_and_a_permission_request_do_not_disturb_each_other() {
+ let (hub, rec, _rx) = qhub();
+ hub.publish(vec![], Some(approval("p1", "ls")), 1_000);
+ hub.publish_question(Some(ask("r1")), 1_000);
+ assert!(hub.inner.lock().unwrap().approval.is_some());
+ let fp = qfp(&hub);
+ assert_eq!(hub.answer(&fp, &[vec!["B".into()]], 1_001), Outcome::Applied);
+ assert!(hub.inner.lock().unwrap().approval.is_some(), "the permission request is untouched");
+ assert_eq!(rec.0.lock().unwrap()[0], ("r1".to_string(), json!({ "Which?": "B" })));
+ }
+
+ #[test]
+ fn a_question_that_waited_too_long_is_gone_for_a_phone_that_connects_now() {
+ let (hub, _rec, _rx) = qhub();
+ hub.publish_question(Some(ask("r1")), 1_000);
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe_with(tx, 1_000 + APPROVAL_TTL_MS + 1, Caps { answers: true, ..Caps::default() });
+ assert!(drain(&mut rx).iter().all(|l| l["type"] != "question"));
+ }
+ // ── prefs (the outfit) ──────────────────────────────────────────────────────────
+
+ #[test]
+ fn a_phone_with_prefs_hears_the_outfit_when_it_connects_and_whenever_it_changes() {
+ let (hub, _) = hub();
+ hub.publish_outfit("beanie");
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe_with(tx, 1_000, Caps { prefs: true, ..Caps::default() });
+ let first = drain(&mut rx);
+ assert!(first.iter().any(|l| l["type"] == "prefs" && l["outfit"] == "beanie"), "{first:?}");
+ hub.publish_outfit("crown");
+ let next = drain(&mut rx);
+ assert_eq!(next.len(), 1);
+ assert_eq!(next[0], serde_json::json!({ "type": "prefs", "outfit": "crown" }));
+ hub.publish_outfit("crown"); // the same again: nothing new
+ assert!(drain(&mut rx).is_empty());
+ }
+
+ #[test]
+ fn a_phone_without_prefs_never_hears_of_the_outfit() {
+ let (hub, _) = hub();
+ hub.publish_outfit("scarf");
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe_with(tx, 1_000, Caps { details: true, answers: true, ..Caps::default() });
+ hub.publish_outfit("bow");
+ assert!(drain(&mut rx).iter().all(|l| l["type"] != "prefs"));
+ }
+
+ #[test]
+ fn only_the_known_wardrobe_values_are_sent() {
+ let (hub, _) = hub();
+ let (tx, mut rx) = mpsc::channel(16);
+ hub.subscribe_with(tx, 1_000, Caps { prefs: true, ..Caps::default() });
+ drain(&mut rx);
+ for bad in ["", "topHat", "Beanie", "beanie ", "../../etc", "auto\nauto"] {
+ hub.publish_outfit(bad);
+ }
+ assert!(drain(&mut rx).is_empty());
+ for ok in OUTFIT_CHOICES {
+ hub.publish_outfit(ok);
+ }
+ assert_eq!(drain(&mut rx).len(), OUTFIT_CHOICES.len());
+ }
+
+ #[test]
+ fn the_outfit_list_is_the_one_of_the_island() {
+ let ts = include_str!("../../../src/mochi/wardrobe.ts");
+ let body = ts.split("export const OUTFIT_SELECTIONS = [").nth(1).unwrap().split("] as const").next().unwrap();
+ let ids: Vec<&str> = body.split('"').skip(1).step_by(2).collect();
+ assert_eq!(ids, OUTFIT_CHOICES.to_vec());
+ }
+ // ── file changes (cap `diffs`) ──────────────────────────────────────────────────
+
+ fn with_files(files: Vec<FileIn>) -> SessionIn {
+ SessionIn { files, ..session("working") }
+ }
+
+ fn file(id: u64, name: &str) -> FileIn {
+ FileIn { id, name: name.into(), added: 2, removed: 1, ..FileIn::default() }
+ }
+
+ fn sub_with(hub: &Hub, caps: Caps) -> (u64, mpsc::Receiver<Out>) {
+ let (tx, rx) = mpsc::channel(64);
+ let (id, _) = hub.subscribe_with(tx, 1_000, caps);
+ (id, rx)
+ }
+
+ #[test]
+ fn only_phones_that_negotiated_relay_hear_of_a_new_access_key() {
+ let (hub, _) = hub();
+ let (_, mut with) = sub_with(&hub, Caps { relay: true, ..Caps::default() });
+ let (_, mut without) = sub_with(&hub, Caps::default());
+ drain(&mut with);
+ drain(&mut without);
+ let access = "C".repeat(43);
+ assert_eq!(hub.send_relay_access(&access), 1);
+ let told = drain(&mut with);
+ assert_eq!(told, vec![serde_json::json!({ "type": "relayAccess", "access": access })]);
+ assert!(drain(&mut without).is_empty(), "a phone that did not ask is never sent it");
+ }
+
+ #[test]
+ fn the_list_of_files_goes_to_a_phone_with_diffs_and_to_nobody_else() {
+ let (hub, _) = hub();
+ let (_, mut plain) = sub_with(&hub, Caps::default());
+ let (_, mut details) = sub_with(&hub, Caps { details: true, ..Caps::default() });
+ let (_, mut diffs) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ drain(&mut plain);
+ drain(&mut details);
+ drain(&mut diffs);
+ hub.publish(vec![with_files(vec![file(3, "/home/me/private/proj/src/app.ts"), FileIn { too_large: true, is_new: true, ..file(4, "C:\\Users\\me\\notes.md") }])], None, 1_000);
+ let p = &drain(&mut plain)[0]["sessions"][0];
+ assert!(p.get("files").is_none(), "{p}");
+ assert!(drain(&mut details)[0]["sessions"][0].get("files").is_none());
+ let d = &drain(&mut diffs)[0]["sessions"][0];
+ assert_eq!(d["files"][0], serde_json::json!({ "id": 3, "name": "app.ts", "added": 2, "removed": 1 }));
+ assert_eq!(d["files"][1], serde_json::json!({ "id": 4, "name": "notes.md", "added": 2, "removed": 1, "tooLarge": true, "isNew": true }));
+ assert!(d.get("steps").is_none(), "diffs alone brings no details: {d}");
+ assert!(!d.to_string().contains("private") && !d.to_string().contains("Users"), "never a path: {d}");
+ }
+
+ #[test]
+ fn a_phone_with_both_gets_details_and_files_and_a_new_one_is_brought_up_to_date() {
+ let (hub, _) = hub();
+ hub.publish(vec![SessionIn { steps: vec!["Edit · a.rs".into()], ..with_files(vec![file(1, "a.rs")]) }], None, 1_000);
+ let (_, mut rx) = sub_with(&hub, Caps { details: true, diffs: true, ..Caps::default() });
+ let first = &drain(&mut rx)[0]["sessions"][0];
+ assert_eq!(first["files"][0]["name"], "a.rs");
+ assert_eq!(first["steps"][0], "Edit · a.rs");
+ }
+
+ #[test]
+ fn at_most_twenty_files_each_with_a_cut_name() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ drain(&mut rx);
+ let many: Vec<FileIn> = (0..30).map(|i| file(i, &format!("{}{i}.rs", "n".repeat(200)))).collect();
+ hub.publish(vec![with_files(many)], None, 1_000);
+ let files = drain(&mut rx)[0]["sessions"][0]["files"].as_array().unwrap().clone();
+ assert_eq!(files.len(), MAX_FILES);
+ assert_eq!(files[0]["id"], 10, "the newest ones are kept");
+ assert!(files.iter().all(|f| f["name"].as_str().unwrap().chars().count() <= 80));
+ }
+
+ #[test]
+ fn a_change_in_the_files_alone_is_sent() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ hub.publish(vec![with_files(vec![file(1, "a.rs")])], None, 1_000);
+ drain(&mut rx);
+ hub.publish(vec![with_files(vec![file(1, "a.rs"), file(2, "b.rs")])], None, 1_001);
+ assert_eq!(drain(&mut rx).len(), 1);
+ }
+
+ fn lines(n: usize) -> Vec<(String, String)> {
+ (0..n).map(|i| ((if i % 2 == 0 { "+" } else { "-" }).to_string(), format!("line {i}"))).collect()
+ }
+
+ fn diff_in(rows: Vec<(String, String)>) -> DiffIn {
+ DiffIn { pill_id: "integration_claude".into(), file_id: 3, name: "/x/y/app.ts".into(), added: 5, removed: 4, lines: rows, ..DiffIn::default() }
+ }
+
+ #[test]
+ fn a_diff_goes_to_the_phone_that_asked_cut_to_the_limits_in_parts() {
+ let (hub, _) = hub();
+ let (id, mut rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ let (_, mut other) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ drain(&mut rx);
+ drain(&mut other);
+ let mut rows = lines(250);
+ rows[0].1 = "x".repeat(900);
+ rows[1].0 = "weird".into();
+ hub.send_diff(id, diff_in(rows));
+ let parts = drain(&mut rx);
+ assert!(drain(&mut other).is_empty(), "only the phone that asked");
+ assert_eq!(parts.len(), 2);
+ assert_eq!((parts[0]["part"].as_u64(), parts[0]["parts"].as_u64()), (Some(0), Some(2)));
+ assert_eq!(parts[0]["lines"].as_array().unwrap().len(), 100);
+ assert_eq!(parts[1]["lines"].as_array().unwrap().len(), 100, "200 lines at most");
+ assert_eq!(parts[0]["truncated"], true);
+ assert_eq!(parts[0]["name"], "app.ts");
+ assert_eq!(parts[0]["lines"][0][1].as_str().unwrap().chars().count(), 400);
+ assert_eq!(parts[0]["lines"][1][0], " ", "an unknown kind is a context line");
+ assert!(parts.iter().all(|p| p.to_string().len() < 60 * 1024));
+ }
+
+ #[test]
+ fn a_small_diff_is_one_part_and_an_empty_one_still_answers() {
+ let (hub, _) = hub();
+ let (id, mut rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ drain(&mut rx);
+ hub.send_diff(id, diff_in(lines(3)));
+ let one = drain(&mut rx);
+ assert_eq!(one.len(), 1);
+ assert_eq!(one[0]["truncated"], false);
+ hub.send_diff(id, DiffIn { gone: true, ..diff_in(vec![]) });
+ let gone = drain(&mut rx);
+ assert_eq!(gone.len(), 1);
+ assert_eq!((gone[0]["gone"].clone(), gone[0]["parts"].clone()), (serde_json::json!(true), serde_json::json!(1)));
+ }
+
+ #[test]
+ fn a_phone_without_diffs_is_never_sent_one_and_cannot_ask() {
+ let (hub, host) = hub();
+ let (id, mut rx) = sub_with(&hub, Caps { details: true, answers: true, prefs: true, ..Caps::default() });
+ drain(&mut rx);
+ hub.request_diff(id, "integration_claude", 3, 1_000);
+ assert!(host.1.lock().unwrap().is_empty());
+ hub.send_diff(id, diff_in(lines(3)));
+ assert!(drain(&mut rx).is_empty());
+ }
+
+ #[test]
+ fn a_request_reaches_the_island_with_the_connection_and_is_rate_limited() {
+ let (hub, host) = hub();
+ let (id, _rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ for _ in 0..30 {
+ hub.request_diff(id, "integration_claude", 3, 5_000);
+ }
+ assert_eq!(host.1.lock().unwrap().len(), DIFF_ASKS_PER_10S);
+ assert_eq!(host.1.lock().unwrap()[0], (id, "integration_claude".to_string(), 3));
+ hub.request_diff(id, "integration_claude", 3, 16_000); // ten seconds later: asking is allowed again
+ assert_eq!(host.1.lock().unwrap().len(), DIFF_ASKS_PER_10S + 1);
+ }
+
+ #[test]
+ fn an_answer_for_a_phone_that_left_goes_nowhere() {
+ let (hub, _) = hub();
+ let (id, rx) = sub_with(&hub, Caps { diffs: true, ..Caps::default() });
+ hub.unsubscribe(id);
+ drop(rx);
+ hub.send_diff(id, diff_in(lines(3))); // must not panic
+ }
+ // ── plan usage (cap `usage`) ────────────────────────────────────────────────────
+
+ fn win(pct: f64, at: u64) -> Option<WindowIn> {
+ Some(WindowIn { used_pct: pct, resets_at: at })
+ }
+
+ fn usage_in() -> UsageIn {
+ UsageIn {
+ claude: Some(PlanIn { five_hour: win(42.4, 1_900_000_000_000), seven_day: win(7.0, 1_900_500_000_000), updated_at: 5, ..PlanIn::default() }),
+ codex: Some(PlanIn { seven_day: win(99.6, 1_900_500_000_000), reset_credits: Some(2), plan_type: Some("plus\n<b>".into()), ..PlanIn::default() }),
+ }
+ }
+
+ #[test]
+ fn a_phone_with_usage_gets_rounded_percentages_and_only_those() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, Caps { usage: true, ..Caps::default() });
+ let (_, mut other) = sub_with(&hub, Caps { details: true, diffs: true, answers: true, prefs: true, ..Caps::default() });
+ drain(&mut rx);
+ drain(&mut other);
+ hub.publish_usage(usage_in());
+ let u = drain(&mut rx);
+ assert_eq!(u.len(), 1);
+ assert_eq!(u[0]["type"], "usage");
+ assert_eq!(u[0]["claude"]["fiveHour"], serde_json::json!({ "pct": 42, "resetsAt": 1_900_000_000_000u64 }));
+ assert_eq!(u[0]["claude"]["updatedAt"], 5);
+ assert_eq!(u[0]["codex"]["sevenDay"]["pct"], 100);
+ assert!(u[0]["codex"].get("fiveHour").is_none());
+ assert_eq!(u[0]["codex"]["resetCredits"], 2);
+ assert_eq!(u[0]["codex"]["plan"], "plusb", "only letters, digits, spaces and dashes");
+ assert!(drain(&mut other).is_empty(), "a phone without usage never hears of it");
+ }
+
+ #[test]
+ fn a_new_phone_is_brought_up_to_date_and_a_repeat_is_not_sent() {
+ let (hub, _) = hub();
+ hub.publish_usage(usage_in());
+ let (_, mut rx) = sub_with(&hub, Caps { usage: true, ..Caps::default() });
+ assert!(drain(&mut rx).iter().any(|l| l["type"] == "usage" && l["claude"].is_object()));
+ hub.publish_usage(usage_in());
+ assert!(drain(&mut rx).is_empty());
+ }
+
+ #[test]
+ fn nothing_known_clears_it_and_junk_numbers_are_left_out() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, Caps { usage: true, ..Caps::default() });
+ hub.publish_usage(usage_in());
+ drain(&mut rx);
+ hub.publish_usage(UsageIn::default());
+ let cleared = drain(&mut rx);
+ assert_eq!(cleared, vec![serde_json::json!({ "type": "usage" })]);
+ let junk = UsageIn { claude: Some(PlanIn { five_hour: win(f64::NAN, 5), seven_day: win(10.0, 0), ..PlanIn::default() }), codex: None };
+ hub.publish_usage(junk);
+ assert!(drain(&mut rx).is_empty(), "nothing usable: still cleared, nothing new to say");
+ hub.publish_usage(UsageIn { claude: Some(PlanIn { five_hour: win(-20.0, 7), ..PlanIn::default() }), codex: None });
+ assert_eq!(drain(&mut rx)[0]["claude"]["fiveHour"]["pct"], 0);
+ let (_, mut late) = sub_with(&hub, Caps { usage: true, ..Caps::default() });
+ assert!(drain(&mut late).iter().any(|l| l["claude"]["fiveHour"]["pct"] == 0), "a new phone is told what there is");
+ hub.publish_usage(UsageIn::default());
+ assert_eq!(drain(&mut late), vec![serde_json::json!({ "type": "usage" })]);
+ let (_, mut after) = sub_with(&hub, Caps { usage: true, ..Caps::default() });
+ assert!(drain(&mut after).iter().all(|l| l["type"] != "usage"), "after a clear a new phone is told nothing");
+ }
+ // ── service cards (cap `services`) ──────────────────────────────────────────────
+
+ fn card(id: &str, headline: &str, items: &[(&str, &str)]) -> ServiceIn {
+ ServiceIn {
+ id: id.into(),
+ title: id.trim_start_matches("integration_").into(),
+ headline: headline.into(),
+ reason: None,
+ items: items.iter().map(|(l, d)| ServiceItemIn { label: (*l).into(), detail: (*d).into() }).collect(),
+ }
+ }
+
+ fn allowed(ids: &[&str]) -> Caps {
+ Caps { services: ids.iter().map(|s| s.to_string()).collect(), ..Caps::default() }
+ }
+
+ #[test]
+ fn a_phone_is_sent_only_the_services_its_user_allowed() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, allowed(&["integration_stripe"]));
+ let (_, mut none) = sub_with(&hub, Caps::default());
+ drain(&mut rx);
+ drain(&mut none);
+ hub.publish_services(vec![card("integration_stripe", "12.50 EUR", &[("Payment", "+9.00")]), card("integration_notion", "3 pages", &[("Secret plan", "1h")])]);
+ let got = drain(&mut rx);
+ assert_eq!(got.len(), 1);
+ let list = got[0]["services"].as_array().unwrap();
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0]["id"], "integration_stripe");
+ assert!(!got[0].to_string().contains("Secret plan"), "{}", got[0]);
+ assert!(drain(&mut none).is_empty());
+ }
+
+ #[test]
+ fn a_new_phone_is_brought_up_to_date_and_a_change_elsewhere_is_not_sent_to_it() {
+ let (hub, _) = hub();
+ hub.publish_services(vec![card("integration_stripe", "1", &[]), card("integration_github", "2 stars", &[])]);
+ let (_, mut rx) = sub_with(&hub, allowed(&["integration_stripe"]));
+ assert!(drain(&mut rx).iter().any(|l| l["type"] == "services"));
+ // GitHub changes; this phone only has Stripe: it hears nothing.
+ hub.publish_services(vec![card("integration_stripe", "1", &[]), card("integration_github", "3 stars", &[])]);
+ assert!(drain(&mut rx).is_empty());
+ hub.publish_services(vec![card("integration_stripe", "2", &[]), card("integration_github", "3 stars", &[])]);
+ assert_eq!(drain(&mut rx).len(), 1);
+ }
+
+ #[test]
+ fn when_the_allowed_service_goes_away_the_list_is_emptied() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, allowed(&["integration_stripe"]));
+ hub.publish_services(vec![card("integration_stripe", "1", &[])]);
+ drain(&mut rx);
+ hub.publish_services(vec![]);
+ assert_eq!(drain(&mut rx), vec![serde_json::json!({ "type": "services", "services": [] })]);
+ }
+
+ #[test]
+ fn unknown_ids_are_dropped_and_texts_are_cut_to_one_short_line() {
+ let (hub, _) = hub();
+ let (_, mut rx) = sub_with(&hub, allowed(&["integration_stripe", "integration_evil"]));
+ drain(&mut rx);
+ let long = "x".repeat(300);
+ hub.publish_services(vec![
+ card("integration_evil", "no", &[]),
+ ServiceIn { reason: Some(format!("a\nb {long}")), ..card("integration_stripe", &format!("{long}\n"), &[("a", "1"), ("b", "2"), ("c", "3"), ("d", "4"), ("", "empty label")]) },
+ card("integration_stripe", "a duplicate", &[]),
+ ]);
+ let v = &drain(&mut rx)[0]["services"][0];
+ assert_eq!(v["headline"].as_str().unwrap().chars().count(), 40);
+ assert!(v["reason"].as_str().unwrap().chars().count() <= 80 && !v["reason"].as_str().unwrap().contains('\n'));
+ assert_eq!(v["items"].as_array().unwrap().len(), 3);
+ assert_eq!(drain(&mut rx).len(), 0);
+ assert!(!hub.inner.lock().unwrap().services.iter().any(|s| s.id == "integration_evil"));
+ }
+
+ #[test]
+ fn the_service_ids_are_those_of_the_pill_catalog() {
+ let ts = include_str!("../../../src/core/pills.ts");
+ for id in SERVICE_IDS {
+ assert!(ts.contains(&format!("\"{id}\"")), "{id}");
+ }
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/interop.rs b/windows/src-tauri/src/phone_link/interop.rs
new file mode 100644
index 00000000..9b955c5b
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/interop.rs
@@ -0,0 +1,204 @@
+// The real phone link server, run for the Android app's tests.
+//
+// Not a test of its own: it is `#[ignore]`d, and android/.../RustDesktopInteropTest.kt
+// starts it (`cargo test ... -- --ignored --nocapture interop_server`) to try the
+// Kotlin client against this implementation. It prints one JSON line (the port,
+// the certificate fingerprint, the pairing link), then obeys one command per line
+// on stdin and reports what the desktop would do on stdout:
+//
+// sessions publish two sample sessions
+// approval <id> <command> a permission request starts waiting
+// clear the request was answered at the desk
+// repair <token> pair again with a new token (phones are kicked)
+// chat on|off the (fake) chat switch; phones learn of it when they connect
+// details on|off the "session details" switch, same
+// quit
+//
+// DECISION allow|deny <id> printed when a phone's decision is applied
+
+use std::io::BufRead;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use super::chat::{BoxFuture, ChatBackend, ChatConfig, ChatFail, ChatLink, ModelOption};
+use super::hub::{ApprovalIn, DiffIn, FileIn, Host, Hub, PlanIn, ServiceIn, ServiceItemIn, SessionIn, UsageIn, WindowIn};
+use super::server::Features;
+use super::pairing::{self, tests::MemStore};
+use super::server;
+
+struct Printing;
+impl Host for Printing {
+ fn get_diff(&self, sub_id: u64, pill_id: &str, file_id: u64) {
+ // The Kotlin test hears this and answers with the command `diff <conn> <file>`.
+ println!("GETDIFF {sub_id} {pill_id} {file_id}");
+ }
+
+ fn decide(&self, request_id: &str, allow: bool) {
+ println!("DECISION {} {request_id}", if allow { "allow" } else { "deny" });
+ }
+}
+
+struct Switches {
+ details: AtomicBool,
+ diffs: AtomicBool,
+ usage: AtomicBool,
+ services: std::sync::Mutex<Vec<String>>,
+}
+impl Features for Switches {
+ fn details(&self) -> bool {
+ self.details.load(Ordering::SeqCst)
+ }
+ fn diffs(&self) -> bool {
+ self.diffs.load(Ordering::SeqCst)
+ }
+ fn usage(&self) -> bool {
+ self.usage.load(Ordering::SeqCst)
+ }
+ fn services(&self) -> Vec<String> {
+ self.services.lock().unwrap().clone()
+ }
+}
+
+/// A stand-in provider for the Kotlin client to talk to: no key, no network, no cost.
+/// `/error` fails like a provider error, `/auth` like a refused key, `/slow` never ends.
+struct FakeChat {
+ on: AtomicBool,
+}
+
+impl ChatBackend for FakeChat {
+ fn config(&self) -> ChatConfig {
+ ChatConfig {
+ enabled: self.on.load(Ordering::SeqCst),
+ allowed: vec![
+ ModelOption { id: "anthropic/fake-claude".into(), provider: "anthropic".into(), label: "Anthropic · fake-claude".into() },
+ ModelOption { id: "openai/fake-gpt".into(), provider: "openai".into(), label: "OpenAI · fake-gpt".into() },
+ ],
+ }
+ }
+
+ fn send(&self, model_id: &str, text: String, deltas: tokio::sync::mpsc::UnboundedSender<String>) -> BoxFuture<Result<String, ChatFail>> {
+ let model = model_id.to_string();
+ Box::pin(async move {
+ if text.starts_with("/error") {
+ return Err(ChatFail::Provider);
+ }
+ if text.starts_with("/auth") {
+ return Err(ChatFail::Auth);
+ }
+ if text.starts_with("/slow") {
+ let mut so_far = String::new();
+ loop {
+ so_far.push_str("slow ");
+ let _ = deltas.send(so_far.clone());
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+ let answer = format!("echo from {model}: {text}");
+ let mut so_far = String::new();
+ for word in answer.split_inclusive(' ') {
+ so_far.push_str(word);
+ let _ = deltas.send(so_far.clone());
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ Ok(answer)
+ })
+ }
+
+ fn reset(&self) {
+ println!("CHAT reset");
+ }
+}
+
+#[test]
+#[ignore = "driven by android/app/src/test/.../RustDesktopInteropTest.kt"]
+fn interop_server() {
+ let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
+ runtime.block_on(async {
+ let identity = pairing::load_or_create_identity(&MemStore::default()).unwrap();
+ let token = std::env::var("COUCOU_INTEROP_TOKEN").unwrap_or_else(|_| "interop-token-0123456789abcdef".into());
+ let hub = Hub::new(Arc::new(Printing));
+ let fake = Arc::new(FakeChat { on: AtomicBool::new(false) });
+ let switches = Arc::new(Switches { details: AtomicBool::new(false), diffs: AtomicBool::new(false), usage: AtomicBool::new(false), services: std::sync::Mutex::new(Vec::new()) });
+ let shared = server::Shared::with_features(
+ hub.clone(), token.clone(), "Rust desktop".into(), Some(ChatLink::new(fake.clone())), switches.clone(),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let handle = server::serve(listener, server::tls_acceptor(&identity).unwrap(), shared.clone());
+ let link = pairing::pairing_link("127.0.0.1", port, &identity.fingerprint, &token, "Rust desktop");
+ println!("{}", serde_json::json!({ "listening": port, "fp": identity.fingerprint, "link": link }));
+
+ let (tx, rx) = std::sync::mpsc::channel::<String>();
+ std::thread::spawn(move || {
+ for line in std::io::stdin().lock().lines().map_while(Result::ok) {
+ if tx.send(line).is_err() {
+ break;
+ }
+ }
+ });
+
+ loop {
+ let Ok(line) = rx.try_recv() else {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ continue;
+ };
+ let mut words = line.splitn(3, ' ');
+ match (words.next(), words.next(), words.next()) {
+ (Some("sessions"), _, _) => hub.publish(
+ vec![
+ SessionIn { pill_id: "integration_claude".into(), agent: "Claude Code".into(), state: "working".into(), status_text: "Editing files".into(), step_index: 2, step_count: 6,
+ steps: vec!["Read · README.md".into(), "Edit · src/app.ts".into()],
+ final_line: Some("Fixed the bug".into()),
+ // a full path, to prove only the folder's name leaves the computer
+ project: Some("/home/someone/private/proj".into()),
+ color: Some("#2DD4BF".into()),
+ // a full path: only the file's name leaves the computer
+ files: vec![FileIn { id: 7, name: "/home/someone/private/proj/src/app.ts".into(), added: 3, removed: 1, ..Default::default() }],
+ },
+ SessionIn { pill_id: "agent_gemini".into(), agent: "Gemini CLI".into(), state: "sleeping".into(), ..Default::default() },
+ ],
+ None,
+ server::now_ms(),
+ ),
+ (Some("approval"), Some(id), Some(command)) => hub.publish(
+ vec![],
+ Some(ApprovalIn { request_id: id.into(), session_id: "interop".into(), pill_id: "integration_claude".into(), tool: "Bash".into(), command: command.into() }),
+ server::now_ms(),
+ ),
+ (Some("clear"), _, _) => hub.publish(vec![], None, server::now_ms()),
+ (Some("repair"), Some(new_token), _) => {
+ *shared.token.lock().unwrap() = new_token.to_string();
+ hub.kick_all("auth", "unpaired");
+ }
+ (Some("chat"), Some(state), _) => fake.on.store(state == "on", Ordering::SeqCst),
+ // `services stripe,notion` ticks those (empty: none); `servicecards` publishes a Stripe and a Notion card.
+ (Some("services"), ticks, _) => {
+ *switches.services.lock().unwrap() = ticks.unwrap_or("").split(',').filter(|s| !s.is_empty()).map(|s| format!("integration_{s}")).collect();
+ }
+ (Some("servicecards"), _, _) => hub.publish_services(vec![
+ ServiceIn { id: "integration_stripe".into(), title: "Stripe".into(), headline: "12.50 EUR".into(), reason: Some("Payments".into()), items: vec![ServiceItemIn { label: "Payment".into(), detail: "+9.00 · 2m".into() }] },
+ ServiceIn { id: "integration_notion".into(), title: "Notion".into(), headline: "3".into(), reason: None, items: vec![ServiceItemIn { label: "Private page".into(), detail: "1m".into() }] },
+ ]),
+ (Some("usage"), Some(state), _) => switches.usage.store(state == "on", Ordering::SeqCst),
+ (Some("usagepct"), Some(pct), _) => hub.publish_usage(UsageIn {
+ claude: Some(PlanIn { five_hour: Some(WindowIn { used_pct: pct.parse().unwrap_or(0.0), resets_at: 1_900_000_000_000 }), plan_type: Some("max".into()), ..PlanIn::default() }),
+ codex: None,
+ }),
+ (Some("diffs"), Some(state), _) => switches.diffs.store(state == "on", Ordering::SeqCst),
+ (Some("diff"), Some(conn), Some(lines)) => {
+ // `lines` is how many sample lines to send (to try the limits and the parts).
+ let n: usize = lines.parse().unwrap_or(3);
+ let rows = (0..n).map(|i| (if i % 3 == 0 { "+" } else if i % 3 == 1 { "-" } else { " " }.to_string(), format!("line {i} of the file"))).collect();
+ hub.send_diff(conn.parse().unwrap_or(0), DiffIn { pill_id: "integration_claude".into(), file_id: 7, name: "/private/dir/app.ts".into(), added: 3, removed: 1, lines: rows, ..Default::default() });
+ }
+ (Some("outfit"), Some(value), _) => hub.publish_outfit(value),
+ (Some("details"), Some(state), _) => switches.details.store(state == "on", Ordering::SeqCst),
+ (Some("quit"), _, _) => break,
+ _ => println!("? {line}"),
+ }
+ println!("OK {line}");
+ }
+ handle.stop();
+ });
+}
diff --git a/windows/src-tauri/src/phone_link/mod.rs b/windows/src-tauri/src/phone_link/mod.rs
new file mode 100644
index 00000000..279bdc8c
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/mod.rs
@@ -0,0 +1,852 @@
+// Copyright (c) 2026 Rhytam Biswas. MIT License, like the rest of Coucou; see android/LICENSE for the text.
+// The phone link: lets the Android app ("Coucou for Android") see the agents'
+// sessions and answer permission requests from the phone.
+// Protocol: docs/ANDROID_LINK.md.
+//
+// Off by default and opt-in (Settings → Phone). While it is on, a TLS server
+// listens on the local network; while it is off nothing listens, nothing is
+// published and no timer runs. No telemetry: the only traffic is between this
+// computer and the phone paired with it.
+//
+// The island keeps owning the sessions and the pending request. It publishes a
+// picture of them (`phone_link_publish`), the hub works out what changed, and a
+// phone's decision comes back through `TauriHost`, which answers the waiting
+// `coucou-hook` exactly as a click on the island would — but only for the request
+// that is still pending (hub.rs). The desktop's own card keeps working all along.
+
+mod admission;
+mod chat;
+mod chat_backend;
+mod discovery;
+mod hub;
+#[cfg(test)]
+mod interop;
+mod pairing;
+mod relay_client;
+mod relay_crypto;
+mod server;
+#[cfg(test)]
+mod tests;
+
+use std::net::{Ipv4Addr, SocketAddr, TcpListener as StdListener};
+use std::sync::{Arc, Mutex};
+
+use serde::Serialize;
+use tauri::{AppHandle, Emitter, Manager, State, WebviewWindow};
+
+use crate::{island, log, pipe, recap, secrets, settings, Shared};
+use hub::{ApprovalIn, Host, Hub, SessionIn};
+use pairing::SecretStore;
+
+/// The port the pairing link offers; another is taken if it is busy.
+pub const DEFAULT_PORT: u16 = 47821;
+
+/// The OS keystore (secrets.rs).
+struct Keystore;
+
+impl SecretStore for Keystore {
+ fn get(&self, key: &str) -> Option<String> {
+ secrets::get_internal(key)
+ }
+ fn set(&self, key: &str, value: &str) -> Result<(), String> {
+ secrets::set_internal(key, value)
+ }
+}
+
+/// A phone's decision, applied as a click on the island would be.
+struct TauriHost {
+ app: AppHandle,
+}
+
+impl Host for TauriHost {
+ fn get_diff(&self, sub_id: u64, pill_id: &str, file_id: u64) {
+ // The island has the diffs; it answers with phone_link_send_diff. Nothing about the file is logged.
+ let _ = self.app.emit_to(island::WINDOW_LABEL, "phone-link-getdiff", serde_json::json!({ "conn": sub_id, "pillId": pill_id, "fileId": file_id }));
+ }
+
+ fn answer(&self, request_id: &str, answers: &serde_json::Map<String, serde_json::Value>) {
+ log::line(format!("phone link: answered a question id={request_id}")); // never what was picked
+ recap::forget_request(&self.app, request_id);
+ let map: std::collections::HashMap<String, serde_json::Value> = answers.clone().into_iter().collect();
+ pipe::answer_question(&self.app, request_id, &map);
+ let _ = self.app.emit_to(island::WINDOW_LABEL, "phone-link-decided", request_id.to_string());
+ }
+
+ fn decide(&self, request_id: &str, allow: bool) {
+ let word = if allow { "allow" } else { "deny" };
+ log::line(format!("phone link: decision id={request_id} {word}"));
+ recap::record_decision(&self.app, request_id, word);
+ pipe::answer(&self.app, request_id, word);
+ // The card on the island closes; it was answered elsewhere.
+ let _ = self.app.emit_to(island::WINDOW_LABEL, "phone-link-decided", request_id.to_string());
+ }
+}
+
+struct Running {
+ handle: server::Handle,
+ shared: Arc<server::Shared>,
+ port: u16,
+ identity: pairing::Identity,
+}
+
+/// The switches in Settings → Android phone, read when a phone connects.
+struct TauriFeatures {
+ app: AppHandle,
+}
+
+impl server::Features for TauriFeatures {
+ fn details(&self) -> bool {
+ self.app.state::<Shared>().settings.lock().unwrap().phone_details
+ }
+ fn answers(&self) -> bool {
+ self.app.state::<Shared>().settings.lock().unwrap().phone_answers
+ }
+ fn diffs(&self) -> bool {
+ self.app.state::<Shared>().settings.lock().unwrap().phone_diffs
+ }
+ fn usage(&self) -> bool {
+ self.app.state::<Shared>().settings.lock().unwrap().phone_usage
+ }
+ fn relay(&self) -> bool {
+ self.app.state::<Shared>().settings.lock().unwrap().phone_relay
+ }
+ fn services(&self) -> Vec<String> {
+ // Only ids the link knows, whatever the file held.
+ let ticked = self.app.state::<Shared>().settings.lock().unwrap().phone_services.clone();
+ hub::SERVICE_IDS.iter().filter(|id| ticked.iter().any(|t| t == *id)).map(|id| id.to_string()).collect()
+ }
+}
+
+pub struct PhoneLink {
+ app: AppHandle,
+ hub: Arc<Hub>,
+ /// Chat from the phone; offered to phones only while the user's switch is on (chat.rs).
+ chat: Arc<chat::ChatLink>,
+ store: Arc<dyn SecretStore>,
+ /// The announcement on the local network (discovery.rs): exists only while the link runs.
+ advertiser: discovery::Advertiser,
+ running: Mutex<Option<Running>>,
+ error: Mutex<Option<String>>,
+ /// The connection to the user's relay (relay_client.rs): exists only while the link runs AND the relay switch is on.
+ relay: Mutex<Option<relay_client::Handle>>,
+}
+
+impl PhoneLink {
+ pub fn new(app: AppHandle) -> Self {
+ Self {
+ chat: chat::ChatLink::new(Arc::new(chat_backend::AppChat::new(app.clone()))),
+ hub: Hub::new(Arc::new(TauriHost { app: app.clone() })),
+ app,
+ store: Arc::new(Keystore),
+ advertiser: discovery::Advertiser::new(Arc::new(discovery::MdnsPublisher::new())),
+ running: Mutex::new(None),
+ error: Mutex::new(None),
+ relay: Mutex::new(None),
+ }
+ }
+
+ /// (Re)starts the relay connection from the settings and the keystore, or stops it. Never fails the link: a
+ /// problem is only a status the user can read in Settings.
+ fn sync_relay(&self) {
+ if let Some(old) = self.relay.lock().unwrap().take() {
+ old.stop();
+ }
+ let Some(shared) = self.running.lock().unwrap().as_ref().map(|r| r.shared.clone()) else { return };
+ let (on, url) = {
+ let s = self.app.state::<Shared>();
+ let s = s.settings.lock().unwrap();
+ (s.phone_relay, s.phone_relay_url.clone())
+ };
+ if !on {
+ return;
+ }
+ let Ok(target) = relay_client::Target::parse(&url) else {
+ log::line("phone link: relay address not valid, not connecting");
+ return;
+ };
+ let Ok(creds) = relay_client::credentials(&*self.store) else {
+ log::line("phone link: relay needs an access key, not connecting");
+ return;
+ };
+ let handle = tauri::async_runtime::block_on(async move { relay_client::start(shared, target, creds) });
+ log::line("phone link: connecting to the relay");
+ *self.relay.lock().unwrap() = Some(handle);
+ }
+
+ /// Starts listening. Fails without side effects if the keystore is missing:
+ /// nothing is ever kept on disk instead.
+ pub fn start(&self) -> Result<(), String> {
+ let mut running = self.running.lock().unwrap();
+ if running.is_some() {
+ return Ok(());
+ }
+ let result = self.start_inner();
+ match result {
+ Ok(r) => {
+ log::line(format!("phone link: listening on port {}", r.port));
+ // So the phone can find this computer again after a Wi-Fi change. The link works without it.
+ match self.advertiser.start(&pairing::computer_name(), r.port, &r.identity.fingerprint) {
+ Ok(()) => log::line("phone link: announced on the local network"),
+ Err(e) => log::line(format!("phone link: not announced on the local network: {e}")),
+ }
+ *running = Some(r);
+ *self.error.lock().unwrap() = None;
+ drop(running);
+ self.sync_relay();
+ Ok(())
+ }
+ Err(e) => {
+ log::line(format!("phone link: could not start: {e}"));
+ *self.error.lock().unwrap() = Some(e.clone());
+ Err(e)
+ }
+ }
+ }
+
+ fn start_inner(&self) -> Result<Running, String> {
+ let identity = pairing::load_or_create_identity(&*self.store)
+ .map_err(|e| format!("no secure storage for the certificate: {e}"))?;
+ let token = pairing::token(&*self.store).map_err(|e| format!("no secure storage for the pairing code: {e}"))?;
+ let std_listener = StdListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, DEFAULT_PORT)))
+ .or_else(|_| StdListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))))
+ .map_err(|e| format!("cannot listen: {e}"))?;
+ std_listener.set_nonblocking(true).map_err(|e| e.to_string())?;
+ let port = std_listener.local_addr().map_err(|e| e.to_string())?.port();
+ let acceptor = server::tls_acceptor(&identity)?;
+ let shared = server::Shared::with_features(
+ self.hub.clone(), token, pairing::computer_name(), Some(self.chat.clone()), Arc::new(TauriFeatures { app: self.app.clone() }),
+ );
+ let handle = {
+ let shared = shared.clone();
+ tauri::async_runtime::block_on(async move {
+ let listener = tokio::net::TcpListener::from_std(std_listener).map_err(|e| e.to_string())?;
+ Ok::<_, String>(server::serve(listener, acceptor, shared))
+ })?
+ };
+ Ok(Running { handle, shared, port, identity })
+ }
+
+ pub fn stop(&self) {
+ if let Some(relay) = self.relay.lock().unwrap().take() {
+ relay.stop();
+ }
+ self.advertiser.stop();
+ if let Some(r) = self.running.lock().unwrap().take() {
+ r.handle.stop();
+ log::line("phone link: stopped");
+ }
+ }
+}
+
+// ── Commands ──────────────────────────────────────────────────────────────────
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Status {
+ pub enabled: bool,
+ pub running: bool,
+ pub port: u16,
+ /// This computer's address on the local network, as the phone will be told.
+ pub host: String,
+ pub name: String,
+ pub clients: usize,
+ pub error: Option<String>,
+ /// The relay connection ("Away from home Wi-Fi"); `off` when it is not switched on.
+ pub relay_state: relay_client::State,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Pairing {
+ pub link: String,
+ pub qr_svg: String,
+ pub host: String,
+ pub port: u16,
+ pub name: String,
+ /// The relay's address when the link also carries the relay fields; the phone shows it as the host.
+ pub relay: Option<String>,
+}
+
+fn status_of(link: &PhoneLink, enabled: bool) -> Status {
+ let running = link.running.lock().unwrap();
+ Status {
+ enabled,
+ running: running.is_some(),
+ port: running.as_ref().map_or(0, |r| r.port),
+ host: pairing::lan_address().map(|ip| ip.to_string()).unwrap_or_default(),
+ name: pairing::computer_name(),
+ clients: link.hub.clients(),
+ error: link.error.lock().unwrap().clone(),
+ relay_state: link.relay.lock().unwrap().as_ref().map_or(relay_client::State::Off, |h| h.state()),
+ }
+}
+
+#[tauri::command]
+pub fn phone_link_status(link: State<PhoneLink>, shared: State<Shared>) -> Status {
+ let enabled = shared.settings.lock().unwrap().phone_link;
+ status_of(&link, enabled)
+}
+
+/// Turns the link on or off. Only ever from the switch in Settings → Phone (the calling window is checked).
+#[tauri::command]
+pub fn phone_link_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<Status, String> {
+ // It starts a network server: only the switch in Settings may do it.
+ only_settings(&window)?;
+ if enabled {
+ link.start()?;
+ } else {
+ link.stop();
+ }
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_link = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ let _ = app.emit("settings-changed", updated);
+ Ok(status_of(&link, enabled))
+}
+
+/// The pairing link and its QR code. Only the settings window may ask: the token
+/// is the secret that lets a phone in.
+#[tauri::command]
+pub fn phone_link_pairing(window: WebviewWindow, link: State<PhoneLink>) -> Result<Pairing, String> {
+ only_settings(&window)?;
+ let running = link.running.lock().unwrap();
+ let r = running.as_ref().ok_or("the phone link is off")?;
+ pairing_of(&link, r)
+}
+
+fn pairing_of(link: &PhoneLink, r: &Running) -> Result<Pairing, String> {
+ let host = pairing::lan_address().map(|ip| ip.to_string()).ok_or("no local network address found")?;
+ let name = r.shared.name.clone();
+ let token = r.shared.token.lock().unwrap().clone();
+ let (on, url) = {
+ let s = link.app.state::<Shared>();
+ let s = s.settings.lock().unwrap();
+ (s.phone_relay, s.phone_relay_url.clone())
+ };
+ // The relay fields go in only when the switch is on and everything for it is there.
+ let relay = if on { relay_client::Target::parse(&url).ok().zip(relay_client::credentials(&*link.store).ok()) } else { None };
+ let (link_text, relay_host) = match &relay {
+ Some((target, creds)) => {
+ let shown = target.display();
+ let key = creds.key.to_base64url();
+ let fields = pairing::RelayLink { url: &shown, room: &creds.room, key: &key, access: &creds.access };
+ (pairing::pairing_link_with_relay(&host, r.port, &r.identity.fingerprint, &token, &name, &fields), Some(target.host.clone()))
+ }
+ None => (pairing::pairing_link(&host, r.port, &r.identity.fingerprint, &token, &name), None),
+ };
+ let qr_svg = pairing::qr_svg(&link_text).unwrap_or_default();
+ Ok(Pairing { link: link_text, qr_svg, host, port: r.port, name, relay: relay_host })
+}
+
+/// Cuts every connected phone off, then makes a new token and a new relay room and key. The phones go first and unconditionally: if a
+/// secret cannot be stored (a locked keystore), the user must still see "Pair again" take effect on the connections, and the error is
+/// reported afterwards instead of leaving the phones connected.
+fn renew_pairing(hub: &Hub, token: &Mutex<String>, store: &dyn SecretStore) -> Result<(), String> {
+ hub.kick_all("auth", "unpaired");
+ *token.lock().unwrap() = pairing::new_token(store)?;
+ // "Pair again" also makes a new room and a new K: a phone that held the old ones can no longer reach this computer
+ // through the relay, whatever it still remembers.
+ relay_client::new_pairing(store)?;
+ Ok(())
+}
+
+/// A new pairing code: the phone that had the old one is disconnected and must
+/// pair again.
+#[tauri::command]
+pub fn phone_link_new_pairing(window: WebviewWindow, link: State<PhoneLink>) -> Result<Pairing, String> {
+ only_settings(&window)?;
+ let running = link.running.lock().unwrap();
+ let r = running.as_ref().ok_or("the phone link is off")?;
+ renew_pairing(&link.hub, &r.shared.token, &*link.store)?;
+ log::line("phone link: new pairing code, phones disconnected");
+ let result = pairing_of(&link, r);
+ drop(running);
+ link.sync_relay();
+ result
+}
+
+// ── Away from home Wi-Fi: the relay (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RelayStatus {
+ pub enabled: bool,
+ /// The relay's address as entered (not a secret).
+ pub url: String,
+ /// An access key is stored. The key itself is never sent back to the window.
+ pub has_access: bool,
+ pub state: relay_client::State,
+}
+
+fn relay_status_of(link: &PhoneLink, shared: &Shared) -> RelayStatus {
+ let s = shared.settings.lock().unwrap();
+ RelayStatus {
+ enabled: s.phone_relay,
+ url: s.phone_relay_url.clone(),
+ has_access: relay_client::access_key(&*link.store).is_some(),
+ state: link.relay.lock().unwrap().as_ref().map_or(relay_client::State::Off, |h| h.state()),
+ }
+}
+
+#[tauri::command]
+pub fn phone_relay_status(link: State<PhoneLink>, shared: State<Shared>) -> RelayStatus {
+ relay_status_of(&link, &shared)
+}
+
+/// The relay switch and its address. Off by default and never on without a valid address and an access key.
+/// Turning it on or changing the address reconnects; the phones already paired over the LAN keep working.
+#[tauri::command]
+pub fn phone_relay_set(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+ url: String,
+) -> Result<RelayStatus, String> {
+ only_settings(&window)?;
+ let url = url.trim().to_string();
+ let clean = if url.is_empty() { String::new() } else { relay_client::Target::parse(&url).map_err(String::from)?.display() };
+ if enabled {
+ if clean.is_empty() {
+ return Err("Enter the relay address first".into());
+ }
+ if relay_client::access_key(&*link.store).is_none() {
+ return Err("Enter the relay's access key first".into());
+ }
+ }
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_relay = enabled;
+ current.phone_relay_url = clean;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.sync_relay();
+ log::line(format!("phone link: relay {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(relay_status_of(&link, &shared))
+}
+
+/// The relay's access key, write-only: stored in the OS keystore and never sent back to the window. Empty clears it
+/// (and switches the relay off, since it cannot connect without one).
+#[tauri::command]
+pub fn phone_relay_set_access(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ access: String,
+) -> Result<RelayStatus, String> {
+ only_settings(&window)?;
+ relay_client::set_access_key(&*link.store, &access)?;
+ if relay_client::access_key(&*link.store).is_none() {
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_relay = false;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ let _ = app.emit("settings-changed", updated);
+ }
+ // Phones paired for the relay follow the new key by themselves (LAN or relay); others re-scan.
+ if let Some(access) = relay_client::access_key(&*link.store) {
+ let told = link.hub.send_relay_access(&access);
+ log::line(format!("phone link: relay access key changed, {told} phone(s) told"));
+ }
+ link.sync_relay();
+ Ok(relay_status_of(&link, &shared))
+}
+
+// ── Session details for the phone: the switch (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DetailsStatus {
+ pub enabled: bool,
+}
+
+#[tauri::command]
+pub fn phone_details_status(shared: State<Shared>) -> DetailsStatus {
+ DetailsStatus { enabled: shared.settings.lock().unwrap().phone_details }
+}
+
+/// "Show session details on the phone". Off by default. A change disconnects the phones once so they
+/// reconnect and are told (or not) about the capability.
+#[tauri::command]
+pub fn phone_details_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<DetailsStatus, String> {
+ only_settings(&window)?;
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_details = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.hub.kick_all("closed", "details setting changed");
+ log::line(format!("phone link: details {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(DetailsStatus { enabled })
+}
+
+// ── Answering questions from the phone: the switch (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AnswersStatus {
+ pub enabled: bool,
+}
+
+#[tauri::command]
+pub fn phone_answers_status(shared: State<Shared>) -> AnswersStatus {
+ AnswersStatus { enabled: shared.settings.lock().unwrap().phone_answers }
+}
+
+/// "Let the phone answer Claude Code's questions". Off by default. A change disconnects the phones once so they
+/// reconnect and are told (or not) about the capability. The phone confirms every answer with its screen lock.
+#[tauri::command]
+pub fn phone_answers_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<AnswersStatus, String> {
+ only_settings(&window)?;
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_answers = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.hub.kick_all("closed", "answers setting changed");
+ log::line(format!("phone link: answering questions {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(AnswersStatus { enabled })
+}
+
+// ── File changes on the phone: the switch (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DiffsStatus {
+ pub enabled: bool,
+}
+
+#[tauri::command]
+pub fn phone_diffs_status(shared: State<Shared>) -> DiffsStatus {
+ DiffsStatus { enabled: shared.settings.lock().unwrap().phone_diffs }
+}
+
+/// "Show the files an agent changed on the phone". Off by default. A change disconnects the phones once so they
+/// reconnect and are told (or not) about the capability.
+#[tauri::command]
+pub fn phone_diffs_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<DiffsStatus, String> {
+ only_settings(&window)?;
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_diffs = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.hub.kick_all("closed", "diffs setting changed");
+ log::line(format!("phone link: file changes on the phone {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(DiffsStatus { enabled })
+}
+
+// ── Plan usage on the phone: the switch (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UsageStatus {
+ pub enabled: bool,
+}
+
+#[tauri::command]
+pub fn phone_usage_status(shared: State<Shared>) -> UsageStatus {
+ UsageStatus { enabled: shared.settings.lock().unwrap().phone_usage }
+}
+
+/// "Show my Claude and Codex plan usage on the phone". Off by default. A change disconnects the phones once so they
+/// reconnect and are told (or not) about the capability.
+#[tauri::command]
+pub fn phone_usage_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<UsageStatus, String> {
+ only_settings(&window)?;
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_usage = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.hub.kick_all("closed", "usage setting changed");
+ log::line(format!("phone link: plan usage on the phone {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(UsageStatus { enabled })
+}
+
+// ── Service cards on the phone: one tick per service (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ServicesStatus {
+ /// The services allowed for the phone.
+ pub services: Vec<String>,
+}
+
+#[tauri::command]
+pub fn phone_services_status(shared: State<Shared>) -> ServicesStatus {
+ let ticked = shared.settings.lock().unwrap().phone_services.clone();
+ ServicesStatus { services: hub::SERVICE_IDS.iter().filter(|id| ticked.iter().any(|t| t == *id)).map(|id| id.to_string()).collect() }
+}
+
+/// "Show these services on the phone". None by default, read-only. A change disconnects the phones once so they
+/// reconnect and are told (or not) about the capability.
+#[tauri::command]
+pub fn phone_services_set(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ services: Vec<String>,
+) -> Result<ServicesStatus, String> {
+ only_settings(&window)?;
+ let allowed: Vec<String> = hub::SERVICE_IDS.iter().filter(|id| services.iter().any(|s| s == *id)).map(|id| id.to_string()).collect();
+ let updated = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_services = allowed.clone();
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ current.clone()
+ };
+ link.hub.kick_all("closed", "services setting changed");
+ log::line(format!("phone link: {} service(s) on the phone", allowed.len()));
+ let _ = app.emit("settings-changed", updated);
+ Ok(ServicesStatus { services: allowed })
+}
+
+/// What the island's service pills show, for phones whose user allowed those services.
+#[tauri::command]
+pub fn phone_link_publish_services(window: WebviewWindow, link: State<PhoneLink>, services: Vec<hub::ServiceIn>) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.publish_services(services);
+ Ok(())
+}
+
+/// The plan usage the island shows, for phones that have `usage`.
+#[tauri::command]
+pub fn phone_link_publish_usage(window: WebviewWindow, link: State<PhoneLink>, usage: hub::UsageIn) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.publish_usage(usage);
+ Ok(())
+}
+
+/// The island's answer to a phone's request for a file's diff (event "phone-link-getdiff").
+#[tauri::command]
+pub fn phone_link_send_diff(window: WebviewWindow, link: State<PhoneLink>, conn: u64, diff: hub::DiffIn) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.send_diff(conn, diff);
+ Ok(())
+}
+
+// ── Chat from the phone: the switch and the list of models (Settings → Android phone) ──
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ChatStatus {
+ pub enabled: bool,
+ /// Allowed models as "provider/model".
+ pub models: Vec<String>,
+}
+
+/// The window a command that changes something may be called from. Every such command checks it, and `tests.rs` reads this file to
+/// prove that none was added without a check.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Caller {
+ Settings,
+ Island,
+}
+
+fn caller_allowed(label: &str, who: Caller) -> bool {
+ match who {
+ Caller::Settings => label == "settings",
+ Caller::Island => label == island::WINDOW_LABEL,
+ }
+}
+
+fn only_settings(window: &WebviewWindow) -> Result<(), String> {
+ if caller_allowed(window.label(), Caller::Settings) {
+ Ok(())
+ } else {
+ Err("only the settings window may change what the phone can use".into())
+ }
+}
+
+/// The island is the one window that knows the sessions and the pending request; what it publishes goes to phones, so no other
+/// window may publish.
+fn only_island(window: &WebviewWindow) -> Result<(), String> {
+ if caller_allowed(window.label(), Caller::Island) {
+ Ok(())
+ } else {
+ Err("only the island may publish to the phone".into())
+ }
+}
+
+#[tauri::command]
+pub fn phone_chat_status(shared: State<Shared>) -> ChatStatus {
+ let s = shared.settings.lock().unwrap();
+ ChatStatus { enabled: s.phone_chat, models: chat_backend::clean_models(&s.phone_chat_models) }
+}
+
+/// The switch "Let the phone chat with my AI providers". Off by default. A change disconnects the
+/// phones so they reconnect and are told (or not) about the capability; turning it off also stops a
+/// running answer and forgets the phone's conversation.
+#[tauri::command]
+pub fn phone_chat_set_enabled(
+ app: AppHandle,
+ window: WebviewWindow,
+ link: State<PhoneLink>,
+ shared: State<Shared>,
+ enabled: bool,
+) -> Result<ChatStatus, String> {
+ only_settings(&window)?;
+ let (updated, status) = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_chat = enabled;
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ let status = ChatStatus { enabled, models: chat_backend::clean_models(&current.phone_chat_models) };
+ (current.clone(), status)
+ };
+ if !enabled {
+ link.chat.shutdown();
+ }
+ link.hub.kick_all("closed", "chat setting changed");
+ log::line(format!("phone link: chat {}", if enabled { "on" } else { "off" }));
+ let _ = app.emit("settings-changed", updated);
+ Ok(status)
+}
+
+/// Which models the phone may use. Anything that is not a known provider's model is dropped.
+#[tauri::command]
+pub fn phone_chat_set_models(
+ app: AppHandle,
+ window: WebviewWindow,
+ shared: State<Shared>,
+ models: Vec<String>,
+) -> Result<ChatStatus, String> {
+ only_settings(&window)?;
+ let cleaned = chat_backend::clean_models(&models);
+ let (updated, status) = {
+ let mut current = shared.settings.lock().unwrap();
+ current.phone_chat_models = cleaned.clone();
+ if let Err(err) = settings::save(&current) {
+ log::line(format!("could not save settings: {err}"));
+ }
+ (current.clone(), ChatStatus { enabled: current.phone_chat, models: cleaned })
+ };
+ let _ = app.emit("settings-changed", updated);
+ Ok(status)
+}
+
+/// The question Claude Code is waiting on (None: none), for phones that may answer it.
+#[tauri::command]
+pub fn phone_link_publish_question(window: WebviewWindow, link: State<PhoneLink>, question: Option<hub::QuestionIn>) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.publish_question(question, server::now_ms());
+ Ok(())
+}
+
+/// What Mochi wears on the computer, for phones that asked for `prefs`.
+#[tauri::command]
+pub fn phone_link_publish_prefs(window: WebviewWindow, link: State<PhoneLink>, outfit: String) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.publish_outfit(&outfit);
+ Ok(())
+}
+
+/// The island's picture of its sessions and of the request waiting for an answer.
+#[tauri::command]
+pub fn phone_link_publish(window: WebviewWindow, link: State<PhoneLink>, sessions: Vec<SessionIn>, approval: Option<ApprovalIn>) -> Result<(), String> {
+ only_island(&window)?;
+ if link.running.lock().unwrap().is_none() {
+ return Ok(());
+ }
+ link.hub.publish(sessions, approval, server::now_ms());
+ Ok(())
+}
+
+/// The app is quitting: withdraw the announcement so phones forget this computer at once.
+pub fn stop_on_exit(app: &AppHandle) {
+ if let Some(link) = app.try_state::<PhoneLink>() {
+ link.stop();
+ }
+}
+
+/// Called once at launch: the link comes back if the user had turned it on.
+pub fn start_if_enabled(app: &AppHandle) {
+ let enabled = app.state::<Shared>().settings.lock().unwrap().phone_link;
+ if enabled {
+ let link = app.state::<PhoneLink>();
+ // A failure is kept in the status and the log; the setting stays on so
+ // the user sees why in Settings instead of finding it silently off.
+ let _ = link.start();
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/pairing.rs b/windows/src-tauri/src/phone_link/pairing.rs
new file mode 100644
index 00000000..7a7b5bf1
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/pairing.rs
@@ -0,0 +1,330 @@
+// The phone link's identity: a TLS certificate made once, and the pairing token.
+//
+// Both live in the OS keystore (Credential Manager, Secret Service), never in a
+// file and never in settings.json. If the keystore is not there the link simply
+// does not start — there is no fallback to disk.
+//
+// The certificate is self-signed and has no name: the phone does not check a
+// host name or an authority, it accepts exactly the certificate whose SHA-256 it
+// was given in the pairing link (certificate pinning). So it only has to be
+// generated once and kept; if it is lost, phones pair again.
+
+use ring::digest;
+use ring::rand::{SecureRandom, SystemRandom};
+
+use super::hub::hex;
+
+pub(super) const CERT_KEY: &str = "phone-link-cert";
+pub(super) const PRIVATE_KEY: &str = "phone-link-key";
+pub(super) const TOKEN_KEY: &str = "phone-link-token";
+
+/// Where the secrets are kept. The app's implementation is the OS keystore
+/// (secrets.rs); tests use memory.
+pub trait SecretStore: Send + Sync {
+ fn get(&self, key: &str) -> Option<String>;
+ fn set(&self, key: &str, value: &str) -> Result<(), String>;
+}
+
+/// The certificate and its key, as the TLS server needs them.
+#[derive(Clone)]
+pub struct Identity {
+ pub cert_der: Vec<u8>,
+ pub key_der: Vec<u8>,
+ /// Lowercase hex SHA-256 of the certificate: the `fp` of the pairing link.
+ pub fingerprint: String,
+}
+
+/// The certificate already made, else a new one — stored before it is used.
+pub fn load_or_create_identity(store: &dyn SecretStore) -> Result<Identity, String> {
+ if let (Some(cert), Some(key)) = (store.get(CERT_KEY), store.get(PRIVATE_KEY)) {
+ if let (Some(cert_der), Some(key_der)) = (unhex(&cert), unhex(&key)) {
+ // A key that no longer parses means a damaged entry: start over.
+ if rcgen::KeyPair::try_from(key_der.as_slice()).is_ok() {
+ let fingerprint = hex(digest::digest(&digest::SHA256, &cert_der).as_ref());
+ return Ok(Identity { cert_der, key_der, fingerprint });
+ }
+ }
+ }
+ let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).map_err(|e| e.to_string())?;
+ let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).map_err(|e| e.to_string())?;
+ params.distinguished_name.push(rcgen::DnType::CommonName, "Coucou phone link");
+ params.not_before = rcgen::date_time_ymd(2024, 1, 1);
+ params.not_after = rcgen::date_time_ymd(2124, 1, 1);
+ let cert = params.self_signed(&key_pair).map_err(|e| e.to_string())?;
+ let cert_der = cert.der().to_vec();
+ let key_der = key_pair.serialize_der();
+ // Key first: a certificate without its key is useless, the reverse is harmless.
+ store.set(PRIVATE_KEY, &hex(&key_der))?;
+ store.set(CERT_KEY, &hex(&cert_der))?;
+ let fingerprint = hex(digest::digest(&digest::SHA256, &cert_der).as_ref());
+ Ok(Identity { cert_der, key_der, fingerprint })
+}
+
+/// The pairing token: the stored one, else a new one.
+pub fn token(store: &dyn SecretStore) -> Result<String, String> {
+ if let Some(t) = store.get(TOKEN_KEY).filter(|t| is_token(t)) {
+ return Ok(t);
+ }
+ new_token(store)
+}
+
+/// A fresh token. Whatever phone held the old one is locked out.
+pub fn new_token(store: &dyn SecretStore) -> Result<String, String> {
+ let token = random_token()?;
+ store.set(TOKEN_KEY, &token)?;
+ Ok(token)
+}
+
+/// 16 to 128 characters of `[A-Za-z0-9_-]` (docs/ANDROID_LINK.md).
+pub fn is_token(s: &str) -> bool {
+ (16..=128).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
+}
+
+fn random_token() -> Result<String, String> {
+ const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+ let mut bytes = [0u8; 32];
+ SystemRandom::new().fill(&mut bytes).map_err(|_| "no secure random source".to_string())?;
+ // 64 symbols, so a byte's low six bits are uniform: 32 symbols = 192 bits.
+ Ok(bytes.iter().map(|b| ALPHABET[(b & 63) as usize] as char).collect())
+}
+
+/// `coucou://pair?v=1&host=…&port=…&fp=…&token=…&name=…`
+pub fn pairing_link(host: &str, port: u16, fingerprint: &str, token: &str, name: &str) -> String {
+ format!(
+ "coucou://pair?v=1&host={}&port={port}&fp={fingerprint}&token={token}&name={}",
+ percent_encode(host),
+ percent_encode(name)
+ )
+}
+
+/// What the pairing link carries so the phone can also reach this computer through the user's relay
+/// (docs/RELAY_LINK.md section 2). All four are present together or not at all.
+pub struct RelayLink<'a> {
+ pub url: &'a str,
+ pub room: &'a str,
+ pub key: &'a str,
+ pub access: &'a str,
+}
+
+/// The link with the relay fields appended. Whoever holds this link holds K: it is shown only in Settings.
+pub fn pairing_link_with_relay(host: &str, port: u16, fingerprint: &str, token: &str, name: &str, relay: &RelayLink) -> String {
+ format!(
+ "{}&relay={}&room={}&key={}&access={}",
+ pairing_link(host, port, fingerprint, token, name),
+ percent_encode(relay.url),
+ relay.room,
+ relay.key,
+ relay.access
+ )
+}
+
+fn percent_encode(s: &str) -> String {
+ let mut out = String::new();
+ for b in s.bytes() {
+ if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~' | b':') {
+ out.push(b as char);
+ } else {
+ out.push_str(&format!("%{b:02X}"));
+ }
+ }
+ out
+}
+
+/// The link as a QR code, an SVG the settings window shows.
+pub fn qr_svg(link: &str) -> Option<String> {
+ let code = qrcode::QrCode::new(link.as_bytes()).ok()?;
+ Some(
+ code.render::<qrcode::render::svg::Color>()
+ .min_dimensions(220, 220)
+ .quiet_zone(true)
+ .dark_color(qrcode::render::svg::Color("#000000"))
+ .light_color(qrcode::render::svg::Color("#ffffff"))
+ .build(),
+ )
+}
+
+fn unhex(s: &str) -> Option<Vec<u8>> {
+ if s.len() % 2 == 1 || s.is_empty() || !s.is_ascii() {
+ return None;
+ }
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()).collect()
+}
+
+/// This computer's address on the local network: the one the OS would use to
+/// reach the outside. Connecting a UDP socket sends nothing; it only makes the
+/// OS pick the interface.
+pub fn lan_address() -> Option<std::net::IpAddr> {
+ let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
+ socket.connect("192.0.2.1:9").ok()?;
+ let ip = socket.local_addr().ok()?.ip();
+ (!ip.is_unspecified() && !ip.is_loopback()).then_some(ip)
+}
+
+/// The name the phone shows for this computer.
+pub fn computer_name() -> String {
+ let name = std::env::var("COMPUTERNAME")
+ .or_else(|_| std::env::var("HOSTNAME"))
+ .ok()
+ .filter(|n| !n.trim().is_empty())
+ .or_else(|| std::fs::read_to_string("/etc/hostname").ok().map(|n| n.trim().to_string()))
+ .filter(|n| !n.is_empty())
+ .unwrap_or_else(|| "Coucou".to_string());
+ name.chars().take(48).collect()
+}
+
+#[cfg(test)]
+pub mod tests {
+ use super::*;
+ use std::collections::HashMap;
+ use std::sync::Mutex;
+
+ #[derive(Default)]
+ pub struct MemStore(pub Mutex<HashMap<String, String>>);
+ impl SecretStore for MemStore {
+ fn get(&self, key: &str) -> Option<String> {
+ self.0.lock().unwrap().get(key).cloned()
+ }
+ fn set(&self, key: &str, value: &str) -> Result<(), String> {
+ self.0.lock().unwrap().insert(key.into(), value.into());
+ Ok(())
+ }
+ }
+
+ /// A store that accepts only what the real keystore accepts (`secrets::INTERNAL_KEYS`), and can be told to refuse every write.
+ #[derive(Default)]
+ pub struct StrictStore {
+ pub inner: MemStore,
+ pub refuse_writes: std::sync::atomic::AtomicBool,
+ }
+ impl SecretStore for StrictStore {
+ fn get(&self, key: &str) -> Option<String> {
+ if !crate::secrets::is_internal(key) {
+ return None;
+ }
+ self.inner.get(key)
+ }
+ fn set(&self, key: &str, value: &str) -> Result<(), String> {
+ if !crate::secrets::is_internal(key) {
+ return Err(format!("unknown key {key}"));
+ }
+ if self.refuse_writes.load(std::sync::atomic::Ordering::SeqCst) {
+ return Err("the keystore is locked".into());
+ }
+ self.inner.set(key, value)
+ }
+ }
+
+ #[test]
+ fn the_certificate_is_made_once_and_then_kept() {
+ let store = MemStore::default();
+ let first = load_or_create_identity(&store).unwrap();
+ let again = load_or_create_identity(&store).unwrap();
+ assert_eq!(first.cert_der, again.cert_der);
+ assert_eq!(first.fingerprint, again.fingerprint);
+ assert_eq!(first.fingerprint.len(), 64);
+ // It is the SHA-256 of the DER, which is what the phone pins.
+ assert_eq!(first.fingerprint, hex(digest::digest(&digest::SHA256, &first.cert_der).as_ref()));
+ }
+
+ #[test]
+ fn a_damaged_key_means_a_new_identity_not_a_crash() {
+ let store = MemStore::default();
+ let first = load_or_create_identity(&store).unwrap();
+ store.set(PRIVATE_KEY, "zz-not-hex").unwrap();
+ let next = load_or_create_identity(&store).unwrap();
+ assert_ne!(first.fingerprint, next.fingerprint);
+ // And the new one is what is kept from now on.
+ assert_eq!(load_or_create_identity(&store).unwrap().fingerprint, next.fingerprint);
+ }
+
+ #[test]
+ fn nothing_secret_is_written_anywhere_but_the_store() {
+ let store = MemStore::default();
+ let id = load_or_create_identity(&store).unwrap();
+ let t = token(&store).unwrap();
+ let kept = store.0.lock().unwrap();
+ assert_eq!(kept.get(PRIVATE_KEY).unwrap(), &hex(&id.key_der));
+ assert_eq!(kept.get(TOKEN_KEY).unwrap(), &t);
+ }
+
+ #[test]
+ fn tokens_are_valid_random_and_replaced_on_demand() {
+ let store = MemStore::default();
+ let a = token(&store).unwrap();
+ assert!(is_token(&a), "{a}");
+ assert_eq!(token(&store).unwrap(), a, "the token is kept");
+ let b = new_token(&store).unwrap();
+ assert!(is_token(&b));
+ assert_ne!(a, b);
+ assert_eq!(token(&store).unwrap(), b);
+ // A damaged stored token is replaced rather than used.
+ store.set(TOKEN_KEY, "short").unwrap();
+ assert!(is_token(&token(&store).unwrap()));
+ }
+
+ #[test]
+ fn the_token_alphabet_matches_the_protocol() {
+ assert!(is_token(&"a".repeat(16)));
+ assert!(is_token(&"A-_9".repeat(32)));
+ assert!(!is_token(&"a".repeat(15)));
+ assert!(!is_token(&"a".repeat(129)));
+ assert!(!is_token("aaaaaaaaaaaaaaa!"));
+ assert!(!is_token("aaaaaaaaaaaaaaa "));
+ assert!(!is_token(""));
+ }
+
+ #[test]
+ fn the_link_has_every_field_and_encodes_the_name() {
+ let link = pairing_link("192.168.1.20", 47821, &"ab".repeat(32), "tok_en-1234567890abcd", "Léa's PC & co");
+ assert_eq!(
+ link,
+ format!(
+ "coucou://pair?v=1&host=192.168.1.20&port=47821&fp={}&token=tok_en-1234567890abcd&name=L%C3%A9a%27s%20PC%20%26%20co",
+ "ab".repeat(32)
+ )
+ );
+ }
+
+ #[test]
+ fn the_relay_fields_follow_the_lan_ones_and_nothing_is_lost() {
+ let base = pairing_link("192.168.1.20", 47821, &"ab".repeat(32), "tok_en-1234567890abcd", "PC");
+ let relay = RelayLink {
+ url: "wss://relay.example.workers.dev:8443",
+ room: "AAAAAAAAAAAAAAAAAAAAAA",
+ key: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
+ access: "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
+ };
+ let link = pairing_link_with_relay("192.168.1.20", 47821, &"ab".repeat(32), "tok_en-1234567890abcd", "PC", &relay);
+ assert!(link.starts_with(&base), "an older phone reads the same LAN part");
+ assert_eq!(
+ &link[base.len()..],
+ "&relay=wss:%2F%2Frelay.example.workers.dev:8443&room=AAAAAAAAAAAAAAAAAAAAAA&key=BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB&access=CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
+ );
+ }
+
+ #[test]
+ fn the_longest_realistic_link_still_fits_what_the_phone_accepts_and_a_qr_code() {
+ // 48 accented characters in the name (9 characters each once percent-encoded) and a long relay host.
+ let name = "é".repeat(48);
+ let host = format!("{}.{}.workers.dev", "a".repeat(63), "b".repeat(63));
+ let relay = RelayLink {
+ url: &format!("wss://{host}:8443"),
+ room: &"A".repeat(22),
+ key: &"B".repeat(43),
+ access: &"C".repeat(43),
+ };
+ let link = pairing_link_with_relay("2001:db8:aaaa:bbbb:cccc:dddd:eeee:ffff", 47821, &"ab".repeat(32), &"t".repeat(128), &name, &relay);
+ assert!(link.len() < 2048, "the phone refuses a link of 2,048 characters or more (PairingScan.MAX_LINK): {}", link.len());
+ assert!(qr_svg(&link).is_some(), "and the QR code can hold it");
+ // The ordinary case is far shorter, so the code stays easy to scan.
+ let usual = pairing_link_with_relay("192.168.1.20", 47821, &"ab".repeat(32), &"t".repeat(32), "My PC", &RelayLink { url: "wss://coucou-link.me.workers.dev", room: &"A".repeat(22), key: &"B".repeat(43), access: &"C".repeat(43) });
+ assert!(usual.len() < 450, "{}", usual.len());
+ }
+
+ #[test]
+ fn the_qr_is_an_svg_of_the_link() {
+ let svg = qr_svg(&pairing_link("192.168.1.20", 47821, &"ab".repeat(32), &"t".repeat(32), "PC")).unwrap();
+ assert!(svg.starts_with("<?xml") || svg.contains("<svg"));
+ assert!(!svg.contains("script"));
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/relay_client.rs b/windows/src-tauri/src/phone_link/relay_client.rs
new file mode 100644
index 00000000..8fbeec1c
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/relay_client.rs
@@ -0,0 +1,1068 @@
+// The phone link through a relay (docs/RELAY_LINK.md), computer side.
+//
+// Off unless the user turns on "Away from home Wi-Fi" in Settings → Android phone and gives a relay address and its
+// access key. The computer then opens ONE outbound WebSocket to the user's own relay and waits. When the phone sends
+// `init` (a MAC under a key only the pairing holds), the computer answers `accept`, derives fresh per-direction
+// session keys and from then on runs the ordinary protocol v1 conversation (server.rs `run_with`) over the decrypted
+// frames, exactly as it runs it over TLS on the LAN. Fingerprints, 120 s offers, decide-once and the per-feature
+// switches are therefore the same code; the relay is only a pipe that cannot read or forge anything.
+//
+// Nothing here blocks the agent: it is its own task, a failure only changes the status line, and nothing secret is
+// ever logged (a log line names a state, never a key, a room or an address).
+
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use futures_util::{SinkExt, StreamExt};
+use serde::Serialize;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::net::TcpStream;
+use tokio::task::JoinHandle;
+use tokio_rustls::rustls::pki_types::ServerName;
+use tokio_rustls::rustls::version::{TLS12, TLS13};
+use tokio_rustls::rustls::{crypto::ring as ring_provider, ClientConfig, RootCertStore};
+use tokio_rustls::TlsConnector;
+use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
+use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
+use tokio_tungstenite::tungstenite::Message;
+use tokio_tungstenite::WebSocketStream;
+
+use super::pairing::SecretStore;
+use super::relay_crypto::{self as crypto, PairingKey, Session};
+use super::server::{self, Shared};
+
+pub(super) const ROOM_KEY: &str = "phone-relay-room";
+pub(super) const PAIRING_KEY: &str = "phone-relay-key";
+pub(super) const ACCESS_KEY: &str = "phone-relay-access";
+
+/// How often the computer sends the text `ping` the relay answers by itself, and how long silence is tolerated.
+const HEARTBEAT: Duration = Duration::from_secs(25);
+const SILENCE: Duration = Duration::from_secs(80);
+/// After this many bad handshake frames the computer stops answering `init` for [`QUIET`].
+const BAD_HANDSHAKES: u32 = 3;
+const QUIET: Duration = Duration::from_secs(10);
+const FIRST_RETRY: Duration = Duration::from_secs(2);
+const LONG_RETRY: Duration = Duration::from_secs(60);
+
+// ── Where the relay is ───────────────────────────────────────────────────────────────────────────
+
+/// A relay address: `wss://host[:port]`, nothing else. `ws://` is accepted for a relay on this same computer only
+/// (development and the tests), never across a network.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Target {
+ pub tls: bool,
+ pub host: String,
+ pub port: u16,
+}
+
+impl Target {
+ pub fn parse(text: &str) -> Result<Target, &'static str> {
+ let text = text.trim();
+ let (tls, rest) = if let Some(r) = text.strip_prefix("wss://") {
+ (true, r)
+ } else if let Some(r) = text.strip_prefix("ws://") {
+ (false, r)
+ } else {
+ return Err("The address must start with wss://");
+ };
+ let rest = rest.strip_suffix('/').unwrap_or(rest);
+ if rest.is_empty() || rest.contains(['/', '?', '#', '@', ' ', '\\']) {
+ return Err("Use only the address, like wss://relay.example.workers.dev");
+ }
+ let (host, port) = match rest.rsplit_once(':') {
+ Some((h, p)) if !h.ends_with(':') && !h.is_empty() && !p.is_empty() && !h.starts_with('[') => {
+ (h, p.parse::<u16>().map_err(|_| "That port is not valid")?)
+ }
+ Some((h, p)) if h.starts_with('[') && h.ends_with(']') => (h, p.parse::<u16>().map_err(|_| "That port is not valid")?),
+ _ => (rest, if tls { 443 } else { 80 }),
+ };
+ let name_ok = host == "[::1]" || (host.len() <= 253 && host.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-'));
+ if !name_ok || host.starts_with('.') || host.starts_with('-') || host.contains("..") {
+ return Err("That is not a valid address");
+ }
+ if port == 0 {
+ return Err("That port is not valid");
+ }
+ if !tls && !matches!(host, "localhost" | "127.0.0.1" | "[::1]") {
+ return Err("The address must start with wss://");
+ }
+ Ok(Target { tls, host: host.to_string(), port })
+ }
+
+ /// The address as it is written into the pairing link (the default port is left out).
+ pub fn display(&self) -> String {
+ let scheme = if self.tls { "wss" } else { "ws" };
+ let default = if self.tls { 443 } else { 80 };
+ if self.port == default {
+ format!("{scheme}://{}", self.host)
+ } else {
+ format!("{scheme}://{}:{}", self.host, self.port)
+ }
+ }
+}
+
+// ── The secrets (OS keystore only) ───────────────────────────────────────────────────────────────
+
+/// The three things a relay connection needs. Never printed (Debug is redacted) and never written to a file.
+pub struct Credentials {
+ pub room: String,
+ pub key: PairingKey,
+ pub access: String,
+}
+
+impl std::fmt::Debug for Credentials {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Credentials(..)")
+ }
+}
+
+fn random_bytes<const N: usize>() -> Result<[u8; N], String> {
+ use ring::rand::{SecureRandom, SystemRandom};
+ let mut bytes = [0u8; N];
+ SystemRandom::new().fill(&mut bytes).map_err(|_| "no secure random source".to_string())?;
+ Ok(bytes)
+}
+
+fn is_room(s: &str) -> bool {
+ s.len() == 22 && crypto::base64url_decode(s).is_some_and(|b| b.len() == 16)
+}
+
+/// The access key as the user pastes it: 32 bytes, base64url without padding (43 characters).
+pub fn is_access_key(s: &str) -> bool {
+ s.len() == 43 && crypto::base64url_decode(s).is_some_and(|b| b.len() == 32)
+}
+
+/// This pairing's room and K: the stored ones, else new ones (made once, kept until "Pair again").
+pub fn pairing(store: &dyn SecretStore) -> Result<(String, PairingKey), String> {
+ let room = store.get(ROOM_KEY).filter(|r| is_room(r));
+ let key = store.get(PAIRING_KEY).and_then(|k| PairingKey::from_base64url(&k));
+ if let (Some(room), Some(key)) = (room, key) {
+ return Ok((room, key));
+ }
+ new_pairing(store)
+}
+
+/// A new room and a new K. Whatever phone held the old ones can no longer read or write anything.
+pub fn new_pairing(store: &dyn SecretStore) -> Result<(String, PairingKey), String> {
+ let room = crypto::base64url_encode(&random_bytes::<16>()?);
+ let key = PairingKey::from_bytes(random_bytes::<32>()?);
+ store.set(ROOM_KEY, &room)?;
+ store.set(PAIRING_KEY, &key.to_base64url())?;
+ Ok((room, key))
+}
+
+pub fn access_key(store: &dyn SecretStore) -> Option<String> {
+ store.get(ACCESS_KEY).filter(|a| is_access_key(a))
+}
+
+/// Stores a new access key (write-only in the UI). Empty clears it.
+pub fn set_access_key(store: &dyn SecretStore, value: &str) -> Result<(), String> {
+ let value = value.trim();
+ if !value.is_empty() && !is_access_key(value) {
+ return Err("The access key is 43 characters of letters, digits, - and _".into());
+ }
+ store.set(ACCESS_KEY, value)
+}
+
+pub fn credentials(store: &dyn SecretStore) -> Result<Credentials, String> {
+ let access = access_key(store).ok_or("no access key")?;
+ let (room, key) = pairing(store)?;
+ Ok(Credentials { room, key, access })
+}
+
+// ── Status ───────────────────────────────────────────────────────────────────────────────────────
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum State {
+ Off,
+ /// Reaching the relay.
+ Connecting,
+ /// Connected to the relay, no phone yet.
+ Waiting,
+ /// A phone completed the handshake.
+ Linked,
+ /// The relay did not accept the access key (or it was rotated).
+ AccessRefused,
+ /// The relay could not be reached.
+ Unreachable,
+ /// The room is held by someone else, or another copy of this computer took its place.
+ RoomTaken,
+ /// The relay is limiting new connections from here.
+ TooMany,
+}
+
+#[derive(Clone)]
+pub struct StatusCell(Arc<Mutex<State>>);
+
+impl StatusCell {
+ fn new(s: State) -> Self {
+ StatusCell(Arc::new(Mutex::new(s)))
+ }
+ pub fn get(&self) -> State {
+ *self.0.lock().unwrap()
+ }
+ fn set(&self, s: State) {
+ *self.0.lock().unwrap() = s;
+ }
+}
+
+// ── The running client ───────────────────────────────────────────────────────────────────────────
+
+/// A running relay client; dropping it does not stop it, `stop` does.
+pub struct Handle {
+ task: JoinHandle<()>,
+ status: StatusCell,
+}
+
+impl Handle {
+ pub fn state(&self) -> State {
+ self.status.get()
+ }
+ pub fn stop(self) {
+ self.task.abort();
+ self.status.set(State::Off);
+ }
+}
+
+/// Starts the client. Must be called inside the async runtime.
+pub fn start(shared: Arc<Shared>, target: Target, creds: Credentials) -> Handle {
+ let status = StatusCell::new(State::Connecting);
+ let task = tokio::spawn(supervise(shared, target, Arc::new(creds), status.clone()));
+ Handle { task, status }
+}
+
+trait Io: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}
+impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> Io for T {}
+type Ws = WebSocketStream<Box<dyn Io>>;
+
+enum Failure {
+ Refused,
+ Unreachable,
+ TooMany,
+}
+
+async fn supervise(shared: Arc<Shared>, target: Target, creds: Arc<Credentials>, status: StatusCell) {
+ let mut delay = FIRST_RETRY;
+ loop {
+ status.set(State::Connecting);
+ let started = Instant::now();
+ let next = match connect(&target, &creds).await {
+ Ok(ws) => {
+ status.set(State::Waiting);
+ match run_connection(ws, &shared, &creds, &status).await {
+ End::Refused => {
+ status.set(State::AccessRefused);
+ LONG_RETRY
+ }
+ End::Taken => {
+ status.set(State::RoomTaken);
+ LONG_RETRY
+ }
+ End::Lost => {
+ // A connection that lasted is not a failing relay: start the back-off again.
+ if started.elapsed() > Duration::from_secs(30) {
+ delay = FIRST_RETRY;
+ }
+ status.set(State::Unreachable);
+ delay
+ }
+ }
+ }
+ Err(Failure::Refused) => {
+ status.set(State::AccessRefused);
+ LONG_RETRY
+ }
+ Err(Failure::TooMany) => {
+ status.set(State::TooMany);
+ LONG_RETRY
+ }
+ Err(Failure::Unreachable) => {
+ status.set(State::Unreachable);
+ delay
+ }
+ };
+ tokio::time::sleep(next).await;
+ delay = (delay * 2).min(LONG_RETRY);
+ }
+}
+
+fn tls_config() -> Arc<ClientConfig> {
+ let roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+ let config = ClientConfig::builder_with_provider(Arc::new(ring_provider::default_provider()))
+ .with_protocol_versions(&[&TLS13, &TLS12])
+ .expect("the ring provider supports TLS 1.2 and 1.3")
+ .with_root_certificates(roots)
+ .with_no_client_auth();
+ Arc::new(config)
+}
+
+async fn connect(target: &Target, creds: &Credentials) -> Result<Ws, Failure> {
+ let attempt = async {
+ let tcp = TcpStream::connect((target.host.trim_matches(['[', ']']), target.port)).await.map_err(|_| Failure::Unreachable)?;
+ let _ = tcp.set_nodelay(true);
+ let stream: Box<dyn Io> = if target.tls {
+ let name = ServerName::try_from(target.host.clone()).map_err(|_| Failure::Unreachable)?;
+ Box::new(TlsConnector::from(tls_config()).connect(name, tcp).await.map_err(|_| Failure::Unreachable)?)
+ } else {
+ Box::new(tcp)
+ };
+ let url = format!("{}://{}:{}/v1/room/{}?role=pc", if target.tls { "wss" } else { "ws" }, target.host, target.port, creds.room);
+ let mut request = url.into_client_request().map_err(|_| Failure::Unreachable)?;
+ let headers = request.headers_mut();
+ let bad = |_| Failure::Unreachable;
+ headers.insert("Authorization", format!("Bearer {}", creds.access).parse().map_err(bad)?);
+ headers.insert(
+ "Sec-WebSocket-Protocol",
+ format!("coucou.v1, coucou.join.{}", crypto::join_proof(&creds.key)).parse().map_err(bad)?,
+ );
+ let config = WebSocketConfig::default().max_message_size(Some(crypto::MAX_FRAME + 1024)).max_frame_size(Some(crypto::MAX_FRAME + 1024));
+ match tokio_tungstenite::client_async_with_config(request, stream, Some(config)).await {
+ Ok((ws, _)) => Ok(ws),
+ Err(tokio_tungstenite::tungstenite::Error::Http(response)) => Err(match response.status().as_u16() {
+ 401 | 403 => Failure::Refused,
+ 429 => Failure::TooMany,
+ _ => Failure::Unreachable,
+ }),
+ Err(_) => Err(Failure::Unreachable),
+ }
+ };
+ tokio::time::timeout(Duration::from_secs(15), attempt).await.unwrap_or(Err(Failure::Unreachable))
+}
+
+enum End {
+ /// The relay no longer accepts the access key.
+ Refused,
+ /// The room is held by someone else, or this computer's place was taken.
+ Taken,
+ /// The connection ended; try again.
+ Lost,
+}
+
+/// One phone's encrypted conversation: the session keys and the in-memory pipe into the protocol server.
+struct Live {
+ session: Session,
+ /// Decrypted lines go to the server here.
+ to_server: tokio::io::WriteHalf<tokio::io::DuplexStream>,
+ /// Lines the server produced come from here.
+ from_server: tokio::io::Lines<BufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>>,
+ server: JoinHandle<()>,
+ /// The phone proved it holds K (a data frame decrypted).
+ proven: bool,
+}
+
+impl Drop for Live {
+ fn drop(&mut self) {
+ self.server.abort();
+ }
+}
+
+async fn next_out(live: &mut Option<Live>) -> Option<String> {
+ match live {
+ Some(l) => l.from_server.next_line().await.ok().flatten(),
+ None => std::future::pending().await,
+ }
+}
+
+async fn run_connection(mut ws: Ws, shared: &Arc<Shared>, creds: &Credentials, status: &StatusCell) -> End {
+ let mut live: Option<Live> = None;
+ let mut bad = 0u32;
+ let mut quiet_until: Option<Instant> = None;
+ let mut last_heard = Instant::now();
+ let mut heartbeat = tokio::time::interval(HEARTBEAT);
+ heartbeat.tick().await;
+ loop {
+ tokio::select! {
+ incoming = ws.next() => {
+ let Some(Ok(message)) = incoming else { return End::Lost };
+ last_heard = Instant::now();
+ match message {
+ Message::Binary(frame) => {
+ let frame: &[u8] = &frame;
+ if frame.len() > 1 && frame[1] == crypto::T_INIT {
+ if quiet_until.is_some_and(|t| Instant::now() < t) {
+ continue;
+ }
+ match crypto::accept_init(&creds.key, &creds.room, frame, crypto::fresh_nonce()) {
+ Ok((accept, session)) => {
+ bad = 0;
+ // Only the newest init is answered; the previous conversation ends.
+ live = None;
+ let Some(ticket) = shared.admit_relay() else { continue };
+ let (near, far) = tokio::io::duplex(2 * crypto::MAX_FRAME);
+ let (read, write) = tokio::io::split(near);
+ let shared = shared.clone();
+ let server = tokio::spawn(async move {
+ server::run_with(far, &shared, Some(Arc::new(ticket))).await;
+ });
+ live = Some(Live { session, to_server: write, from_server: BufReader::new(read).lines(), server, proven: false });
+ status.set(State::Waiting);
+ if ws.send(Message::Binary(accept.into())).await.is_err() {
+ return End::Lost;
+ }
+ }
+ Err(_) => {
+ bad += 1;
+ if bad >= BAD_HANDSHAKES {
+ bad = 0;
+ quiet_until = Some(Instant::now() + QUIET);
+ }
+ }
+ }
+ } else if let Some(l) = live.as_mut() {
+ match l.session.open(frame) {
+ Ok(line) => {
+ if !l.proven {
+ l.proven = true;
+ status.set(State::Linked);
+ }
+ if l.to_server.write_all(&line).await.is_err() || l.to_server.write_all(b"\n").await.is_err() {
+ live = None;
+ status.set(State::Waiting);
+ }
+ }
+ Err(_) => {
+ // Any fault ends the conversation; the phone starts again with a new init.
+ live = None;
+ status.set(State::Waiting);
+ }
+ }
+ } else {
+ bad += 1;
+ if bad >= BAD_HANDSHAKES {
+ bad = 0;
+ quiet_until = Some(Instant::now() + QUIET);
+ }
+ }
+ }
+ Message::Text(text) => {
+ // The relay's hints (never trusted for anything but the status line) and its `pong`.
+ if text.as_str().contains("\"offline\"") && live.is_some() {
+ live = None;
+ status.set(State::Waiting);
+ }
+ }
+ Message::Close(frame) => {
+ let reason = frame.map(|f| (f.code, f.reason.to_string()));
+ return match reason {
+ Some((_, r)) if r == "join proof" || r == "replaced" => End::Taken,
+ Some((_, r)) if r == "access key changed" => End::Refused,
+ Some((CloseCode::Policy, _)) => End::Taken,
+ _ => End::Lost,
+ };
+ }
+ _ => {}
+ }
+ }
+ out = next_out(&mut live) => {
+ let Some(line) = out else {
+ // The server ended this conversation (a bad token, the link turned off…); its last line was sent.
+ live = None;
+ status.set(State::Waiting);
+ continue;
+ };
+ if let Some(l) = live.as_mut() {
+ match l.session.seal(line.as_bytes()) {
+ Ok(frame) => {
+ if ws.send(Message::Binary(frame.into())).await.is_err() {
+ return End::Lost;
+ }
+ }
+ Err(_) => {
+ live = None; // too long or the counter is used up: the phone re-handshakes
+ status.set(State::Waiting);
+ }
+ }
+ }
+ }
+ _ = heartbeat.tick() => {
+ if last_heard.elapsed() > SILENCE {
+ return End::Lost;
+ }
+ if ws.send(Message::Text("ping".into())).await.is_err() {
+ return End::Lost;
+ }
+ }
+ }
+ }
+}
+
+
+// ── Tests ────────────────────────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::phone_link::hub::{ApprovalIn, Hub};
+ use crate::phone_link::pairing::tests::MemStore;
+ use serde_json::{json, Value};
+ use std::future::Future;
+ use tokio::net::TcpListener;
+ use tokio::sync::mpsc;
+ use tokio_tungstenite::tungstenite::handshake::server::{ErrorResponse, Request, Response};
+ use tokio_tungstenite::tungstenite::http::StatusCode;
+
+ const TOKEN: &str = "test-token-0123456789abcdef";
+
+ fn block_on<F: Future>(f: F) -> F::Output {
+ tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
+ }
+
+ #[derive(Default)]
+ struct Recorder(Mutex<Vec<(String, bool)>>);
+ impl super::super::hub::Host for Recorder {
+ fn decide(&self, request_id: &str, allow: bool) {
+ self.0.lock().unwrap().push((request_id.to_string(), allow));
+ }
+ }
+
+ // ── a stand-in relay: it hands each socket the computer opens to the test, which plays the phone ──
+
+ #[derive(Default, Clone)]
+ struct Seen {
+ auth: Arc<Mutex<Vec<String>>>,
+ protocols: Arc<Mutex<Vec<String>>>,
+ paths: Arc<Mutex<Vec<String>>>,
+ }
+
+ type Server = WebSocketStream<TcpStream>;
+
+ async fn fake_relay(refuse: Option<u16>) -> (u16, Seen, mpsc::UnboundedReceiver<Server>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let seen = Seen::default();
+ let (tx, rx) = mpsc::unbounded_channel();
+ let seen2 = seen.clone();
+ tokio::spawn(async move {
+ loop {
+ let Ok((tcp, _)) = listener.accept().await else { return };
+ let seen = seen2.clone();
+ let callback = move |req: &Request, mut resp: Response| -> Result<Response, ErrorResponse> {
+ let header = |n: &str| req.headers().get(n).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
+ seen.auth.lock().unwrap().push(header("authorization"));
+ seen.protocols.lock().unwrap().push(header("sec-websocket-protocol"));
+ seen.paths.lock().unwrap().push(req.uri().to_string());
+ if let Some(code) = refuse {
+ let mut r = ErrorResponse::new(None);
+ *r.status_mut() = StatusCode::from_u16(code).unwrap();
+ return Err(r);
+ }
+ resp.headers_mut().insert("sec-websocket-protocol", "coucou.v1".parse().unwrap());
+ Ok(resp)
+ };
+ if let Ok(ws) = tokio_tungstenite::accept_hdr_async(tcp, callback).await {
+ let _ = tx.send(ws);
+ }
+ }
+ });
+ (port, seen, rx)
+ }
+
+ struct Rig {
+ creds_key: String,
+ room: String,
+ access: String,
+ seen: Seen,
+ conns: mpsc::UnboundedReceiver<Server>,
+ hub: Arc<Hub>,
+ host: Arc<Recorder>,
+ shared: Arc<Shared>,
+ handle: Handle,
+ }
+
+ impl Rig {
+ async fn start() -> Rig {
+ let (port, seen, conns) = fake_relay(None).await;
+ Rig::start_at(port, seen, conns).await
+ }
+
+ async fn start_at(port: u16, seen: Seen, conns: mpsc::UnboundedReceiver<Server>) -> Rig {
+ let store = MemStore::default();
+ set_access_key(&store, &crypto::base64url_encode(&[7u8; 32])).unwrap();
+ let creds = credentials(&store).unwrap();
+ let (room, creds_key, access) = (creds.room.clone(), creds.key.to_base64url(), creds.access.clone());
+ let host = Arc::new(Recorder::default());
+ let hub = Hub::new(host.clone());
+ let shared = Shared::with_features(hub.clone(), TOKEN.to_string(), "Test PC".to_string(), None, Arc::new(server::NoFeatures));
+ let handle = start(shared.clone(), Target { tls: false, host: "127.0.0.1".into(), port }, creds);
+ Rig { creds_key, room, access, seen, conns, hub, host, shared, handle }
+ }
+
+ fn key(&self) -> PairingKey {
+ PairingKey::from_base64url(&self.creds_key).unwrap()
+ }
+
+ async fn socket(&mut self) -> Server {
+ tokio::time::timeout(Duration::from_secs(5), self.conns.recv()).await.expect("the computer connects").unwrap()
+ }
+
+ async fn wait_state(&self, want: State) {
+ for _ in 0..200 {
+ if self.handle.state() == want {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ panic!("state is {:?}, wanted {:?}", self.handle.state(), want);
+ }
+ }
+
+ /// The test as the phone: it completes the handshake over a relay socket.
+ struct Phone {
+ ws: Server,
+ session: Session,
+ }
+
+ impl Phone {
+ async fn join(rig: &Rig, mut ws: Server) -> Phone {
+ let n = crypto::fresh_nonce();
+ ws.send(Message::Binary(crypto::init_frame(&rig.key(), &rig.room, n).into())).await.unwrap();
+ let accept = loop {
+ match tokio::time::timeout(Duration::from_secs(5), ws.next()).await.expect("accept arrives").unwrap().unwrap() {
+ Message::Binary(b) => break b,
+ _ => continue,
+ }
+ };
+ let session = crypto::finish_handshake(&rig.key(), &rig.room, &n, &accept).unwrap();
+ Phone { ws, session }
+ }
+
+ async fn send(&mut self, v: Value) {
+ let frame = self.session.seal(v.to_string().as_bytes()).unwrap();
+ self.ws.send(Message::Binary(frame.into())).await.unwrap();
+ }
+
+ async fn recv(&mut self) -> Value {
+ loop {
+ match tokio::time::timeout(Duration::from_secs(5), self.ws.next()).await.expect("a frame arrives").unwrap().unwrap() {
+ Message::Binary(b) => return serde_json::from_slice(&self.session.open(&b).unwrap()).unwrap(),
+ _ => continue,
+ }
+ }
+ }
+
+ async fn expect(&mut self, kind: &str) -> Value {
+ for _ in 0..20 {
+ let v = self.recv().await;
+ if v["type"] == kind {
+ return v;
+ }
+ }
+ panic!("no {kind}");
+ }
+
+ async fn hello(&mut self) -> Value {
+ self.send(json!({ "type": "hello", "v": 1, "token": TOKEN, "caps": [] })).await;
+ self.expect("welcome").await
+ }
+
+ /// True when nothing arrives for a moment.
+ async fn silent(&mut self) -> bool {
+ tokio::time::timeout(Duration::from_millis(300), self.ws.next()).await.is_err()
+ }
+ }
+
+ // ── addresses and secrets ──
+
+ #[test]
+ fn only_a_wss_address_with_nothing_else_is_accepted() {
+ let ok = |s: &str| Target::parse(s).unwrap();
+ assert_eq!(ok("wss://relay.example.workers.dev"), Target { tls: true, host: "relay.example.workers.dev".into(), port: 443 });
+ assert_eq!(ok(" wss://relay.example.workers.dev/ ").port, 443);
+ assert_eq!(ok("wss://relay.example.com:8443").port, 8443);
+ assert_eq!(ok("wss://relay.example.com:8443").display(), "wss://relay.example.com:8443");
+ assert_eq!(ok("wss://relay.example.com").display(), "wss://relay.example.com");
+ // Plain ws:// is for a relay on this same computer only.
+ assert!(!ok("ws://127.0.0.1:8787").tls);
+ assert!(!ok("ws://localhost:8787").tls);
+ for bad in [
+ "", "relay.example.com", "https://relay.example.com", "http://relay.example.com", "ws://relay.example.com",
+ "ws://192.168.1.5:8787", "wss://", "wss://user:[email protected]", "wss://relay.example.com/path", "wss://relay.example.com/?x=1",
+ "wss://relay.example.com#frag", "wss://relay example.com", "wss://-bad.example.com", "wss://a..b", "wss://relay.example.com:0",
+ "wss://relay.example.com:99999", "wss://relay.example.com:", "wss://rélay.example.com", "wss://relay.example.com\\x",
+ ] {
+ assert!(Target::parse(bad).is_err(), "{bad:?} must be refused");
+ }
+ }
+
+ #[test]
+ fn the_pairing_is_made_once_kept_and_replaced_on_demand() {
+ let store = MemStore::default();
+ let (room, key) = pairing(&store).unwrap();
+ assert!(is_room(&room));
+ let (room2, key2) = pairing(&store).unwrap();
+ assert_eq!((room.clone(), key.to_base64url()), (room2, key2.to_base64url()), "kept");
+ let (room3, key3) = new_pairing(&store).unwrap();
+ assert_ne!(room, room3);
+ assert_ne!(key.to_base64url(), key3.to_base64url());
+ assert_eq!(pairing(&store).unwrap().0, room3);
+ // A damaged value is replaced, never used.
+ store.set(ROOM_KEY, "short").unwrap();
+ assert!(is_room(&pairing(&store).unwrap().0));
+ }
+
+ #[test]
+ fn the_access_key_is_checked_stored_and_never_printed() {
+ let store = MemStore::default();
+ assert!(access_key(&store).is_none());
+ assert!(credentials(&store).is_err(), "no access key, no connection");
+ let good = crypto::base64url_encode(&[9u8; 32]);
+ assert_eq!(good.len(), 43);
+ set_access_key(&store, &format!(" {good} ")).unwrap();
+ assert_eq!(access_key(&store).as_deref(), Some(good.as_str()));
+ for bad in ["short", &"a".repeat(44), &format!("{}=", &good[..42]), &format!("{}!", &good[..42])] {
+ assert!(set_access_key(&store, bad).is_err(), "{bad:?}");
+ }
+ assert_eq!(access_key(&store).as_deref(), Some(good.as_str()), "a refused value changes nothing");
+ let creds = credentials(&store).unwrap();
+ let shown = format!("{creds:?}");
+ assert!(!shown.contains(&good) && !shown.contains(&creds.room) && !shown.contains(&creds.key.to_base64url()), "{shown}");
+ set_access_key(&store, "").unwrap();
+ assert!(access_key(&store).is_none(), "empty clears it");
+ }
+
+ // ── the connection ──
+
+ #[test]
+ fn it_presents_the_access_key_the_join_proof_and_the_room() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let _ws = rig.socket().await;
+ assert_eq!(rig.seen.auth.lock().unwrap()[0], format!("Bearer {}", rig.access));
+ assert_eq!(rig.seen.protocols.lock().unwrap()[0], format!("coucou.v1, coucou.join.{}", crypto::join_proof(&rig.key())));
+ assert_eq!(rig.seen.paths.lock().unwrap()[0], format!("/v1/room/{}?role=pc", rig.room));
+ rig.wait_state(State::Waiting).await;
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn a_phone_pairs_through_the_relay_and_the_usual_conversation_runs() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut phone = Phone::join(&rig, ws).await;
+ let welcome = phone.hello().await;
+ assert_eq!(welcome["desktop"], "Test PC");
+ assert_eq!(rig.handle.state(), State::Linked);
+ phone.send(json!({ "type": "ping" })).await;
+ phone.expect("pong").await;
+
+ rig.hub.publish(
+ vec![],
+ Some(ApprovalIn {
+ request_id: "req-1".into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ tool: "Bash".into(),
+ command: "npm run build".into(),
+ }),
+ server::now_ms(),
+ );
+ let approval = phone.expect("approval").await;
+ let fp = approval["fingerprint"].as_str().unwrap().to_string();
+ assert_eq!(fp, super::super::hub::fingerprint("integration_claude", "s1", "Bash", "npm run build", "req-1"));
+ // A decision for another fingerprint does nothing; the right one is applied once.
+ phone.send(json!({ "type": "decision", "fingerprint": "0".repeat(64), "decision": "allow" })).await;
+ phone.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ phone.expect("approvalResolved").await;
+ assert_eq!(rig.host.0.lock().unwrap().clone(), vec![("req-1".to_string(), true)]);
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn the_wrong_token_is_refused_through_the_relay_like_on_the_lan() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut phone = Phone::join(&rig, ws).await;
+ phone.send(json!({ "type": "hello", "v": 1, "token": "wrong-token-0123456789abcdef", "caps": [] })).await;
+ let err = phone.expect("error").await;
+ assert_eq!(err["code"], "auth");
+ assert!(rig.host.0.lock().unwrap().is_empty());
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn nothing_is_served_before_the_phone_proves_it_holds_the_key() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let mut ws = rig.socket().await;
+ // Data without a handshake, a wrong-MAC init, and garbage: all ignored, no answer.
+ let mut other = crypto::init_frame(&PairingKey::from_bytes([1u8; 32]), &rig.room, crypto::fresh_nonce());
+ ws.send(Message::Binary(other.clone().into())).await.unwrap();
+ other[2] ^= 1;
+ ws.send(Message::Binary(other.into())).await.unwrap();
+ ws.send(Message::Binary(vec![1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3].into())).await.unwrap();
+ ws.send(Message::Binary(vec![].into())).await.unwrap();
+ assert!(tokio::time::timeout(Duration::from_millis(300), ws.next()).await.is_err(), "no answer to a stranger");
+ assert_eq!(rig.shared.admission_counts().0, 0, "no slot was used");
+ assert_eq!(rig.hub.clients(), 0);
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn three_bad_handshakes_silence_init_for_a_while() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let mut ws = rig.socket().await;
+ let wrong = PairingKey::from_bytes([2u8; 32]);
+ for _ in 0..3 {
+ ws.send(Message::Binary(crypto::init_frame(&wrong, &rig.room, crypto::fresh_nonce()).into())).await.unwrap();
+ }
+ // Even the right key is not answered during the quiet period.
+ let n = crypto::fresh_nonce();
+ ws.send(Message::Binary(crypto::init_frame(&rig.key(), &rig.room, n).into())).await.unwrap();
+ assert!(tokio::time::timeout(Duration::from_millis(400), ws.next()).await.is_err());
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn a_tampered_replayed_or_reordered_frame_ends_the_conversation() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut phone = Phone::join(&rig, ws).await;
+ phone.hello().await;
+ // A recorded frame sent again.
+ let frame = phone.session.seal(json!({ "type": "ping" }).to_string().as_bytes()).unwrap();
+ phone.ws.send(Message::Binary(frame.clone().into())).await.unwrap();
+ phone.expect("pong").await;
+ phone.ws.send(Message::Binary(frame.into())).await.unwrap();
+ // The server connection was dropped: the slot is given back and nothing more is answered.
+ for _ in 0..100 {
+ if rig.hub.clients() == 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert_eq!(rig.hub.clients(), 0);
+ assert_eq!(rig.shared.admission_counts().0, 0, "the slot is given back");
+ phone.send(json!({ "type": "ping" })).await; // the old session is dead (its counter is unexpected now)
+ assert!(phone.silent().await);
+ // Only a fresh handshake starts a conversation again.
+ let ws = phone.ws;
+ let mut again = Phone::join(&rig, ws).await;
+ again.hello().await;
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn a_new_init_replaces_the_conversation_and_old_keys_are_useless() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut first = Phone::join(&rig, ws).await;
+ first.hello().await;
+ let old_session = std::mem::replace(&mut first.session, {
+ // Keep the old keys to try them after the new handshake.
+ let n = crypto::fresh_nonce();
+ first.ws.send(Message::Binary(crypto::init_frame(&rig.key(), &rig.room, n).into())).await.unwrap();
+ let accept = loop {
+ // Frames of the old conversation may still be in flight; the accept is the one of type 2.
+ if let Message::Binary(b) = first.ws.next().await.unwrap().unwrap() {
+ if b[1] == crypto::T_ACCEPT {
+ break b;
+ }
+ }
+ };
+ crypto::finish_handshake(&rig.key(), &rig.room, &n, &accept).unwrap()
+ });
+ // The new session works…
+ first.hello().await;
+ assert_eq!(rig.hub.clients(), 1, "exactly one conversation");
+ assert_eq!(rig.shared.admission_counts().0, 1);
+ // …and a frame sealed under the old keys does not.
+ let mut stale = old_session;
+ let frame = stale.seal(json!({ "type": "ping" }).to_string().as_bytes()).unwrap();
+ first.ws.send(Message::Binary(frame.into())).await.unwrap();
+ for _ in 0..100 {
+ if rig.hub.clients() == 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert_eq!(rig.hub.clients(), 0, "a fault ends the conversation");
+ assert_eq!(rig.shared.admission_counts().0, 0);
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn when_the_relay_says_the_phone_left_the_conversation_ends() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut phone = Phone::join(&rig, ws).await;
+ phone.hello().await;
+ assert_eq!(rig.hub.clients(), 1);
+ phone.ws.send(Message::Text(r#"{"peer":"offline"}"#.into())).await.unwrap();
+ for _ in 0..100 {
+ if rig.hub.clients() == 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert_eq!(rig.hub.clients(), 0);
+ assert_eq!(rig.shared.admission_counts().0, 0);
+ rig.wait_state(State::Waiting).await;
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn the_relay_connection_counts_as_one_source_in_the_admission_policy() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let ws = rig.socket().await;
+ let mut phone = Phone::join(&rig, ws).await;
+ assert_eq!(rig.shared.admission_counts().0, 1, "one slot for the conversation");
+ phone.hello().await;
+ assert_eq!(rig.shared.admission_counts().0, 1);
+ // A flood of inits does not grow it: only the newest conversation holds a slot.
+ for _ in 0..5 {
+ let n = crypto::fresh_nonce();
+ phone.ws.send(Message::Binary(crypto::init_frame(&rig.key(), &rig.room, n).into())).await.unwrap();
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(rig.shared.admission_counts().0 <= 1);
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn the_status_names_why_the_relay_was_not_reached() {
+ block_on(async {
+ for (code, want) in [(401u16, State::AccessRefused), (429, State::TooMany), (404, State::Unreachable)] {
+ let (port, seen, conns) = fake_relay(Some(code)).await;
+ let rig = Rig::start_at(port, seen, conns).await;
+ rig.wait_state(want).await;
+ rig.handle.stop();
+ }
+ // Nothing listening at all.
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let rig = Rig::start_at(port, Seen::default(), mpsc::unbounded_channel().1).await;
+ rig.wait_state(State::Unreachable).await;
+ rig.handle.stop();
+ });
+ }
+
+ #[test]
+ fn stopping_cuts_the_connection_and_shows_off() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let mut ws = rig.socket().await;
+ let status = rig.handle.status.clone();
+ rig.handle.stop();
+ assert_eq!(status.get(), State::Off);
+ let ended = tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ match ws.next().await {
+ None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
+ _ => {}
+ }
+ }
+ })
+ .await;
+ assert!(ended.is_ok(), "the socket is closed when the client stops");
+ });
+ }
+
+ #[test]
+ fn the_source_never_logs_or_prints() {
+ let source = include_str!("relay_client.rs");
+ let code = &source[..source.find("// ── Tests").unwrap()];
+ for forbidden in ["log::", "println!", "eprintln!", "dbg!", "tracing::", "format!(\"{:?}\", creds", "{creds:?}"] {
+ assert!(!code.contains(forbidden), "relay_client.rs must not use {forbidden}");
+ }
+ }
+
+ #[test]
+ fn after_pair_again_the_old_pairing_gets_no_answer_and_the_new_one_works() {
+ block_on(async {
+ let (port, _seen, mut conns) = fake_relay(None).await;
+ let store = MemStore::default();
+ set_access_key(&store, &crypto::base64url_encode(&[7u8; 32])).unwrap();
+ let old = credentials(&store).unwrap();
+ let (old_room, old_key) = (old.room.clone(), PairingKey::from_base64url(&old.key.to_base64url()).unwrap());
+ // "Pair again": a new room and key, then the client reconnects with them (what the PC does).
+ let (new_room, _) = new_pairing(&store).unwrap();
+ assert_ne!(old_room, new_room);
+ let host = Arc::new(Recorder::default());
+ let hub = Hub::new(host.clone());
+ let shared = Shared::with_features(hub.clone(), TOKEN.to_string(), "Test PC".to_string(), None, Arc::new(server::NoFeatures));
+ let handle = start(shared.clone(), Target { tls: false, host: "127.0.0.1".into(), port }, credentials(&store).unwrap());
+ let mut ws = tokio::time::timeout(Duration::from_secs(5), conns.recv()).await.unwrap().unwrap();
+ // The phone that still holds the old room and K is not answered.
+ ws.send(Message::Binary(crypto::init_frame(&old_key, &old_room, crypto::fresh_nonce()).into())).await.unwrap();
+ ws.send(Message::Binary(crypto::init_frame(&old_key, &new_room, crypto::fresh_nonce()).into())).await.unwrap();
+ assert!(tokio::time::timeout(Duration::from_millis(300), ws.next()).await.is_err(), "no answer for the old pairing");
+ assert_eq!(shared.admission_counts().0, 0);
+ // The new pairing is answered.
+ let new_key = credentials(&store).unwrap().key;
+ let n = crypto::fresh_nonce();
+ ws.send(Message::Binary(crypto::init_frame(&new_key, &new_room, n).into())).await.unwrap();
+ let accept = loop {
+ if let Message::Binary(b) = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap() {
+ break b;
+ }
+ };
+ assert!(crypto::finish_handshake(&new_key, &new_room, &n, &accept).is_ok());
+ handle.stop();
+ });
+ }
+
+ // ── End to end through a real relay (run by android/relay/tools/e2e.sh, never by `cargo test`) ──
+
+ /// The computer's half of the end-to-end check: connects to the relay at `COUCOU_E2E_RELAY_URL` with the fixed test
+ /// credentials the Kotlin phone test also has, offers one approval and waits for the phone's decision. Ignored by
+ /// default; the script runs it together with the phone side, against the real Worker or the Node twin.
+ #[test]
+ #[ignore = "needs a running relay and the Kotlin phone test: android/relay/tools/e2e.sh"]
+ fn e2e_the_computer_side_for_the_phone_test() {
+ let url = std::env::var("COUCOU_E2E_RELAY_URL").expect("COUCOU_E2E_RELAY_URL");
+ let store = MemStore::default();
+ store.set(ROOM_KEY, &crypto::base64url_encode(&[0x11; 16])).unwrap();
+ store.set(PAIRING_KEY, &crypto::base64url_encode(&[0x22; 32])).unwrap();
+ set_access_key(&store, &crypto::base64url_encode(&[0x33; 32])).unwrap();
+ block_on(async {
+ let host = Arc::new(Recorder::default());
+ let hub = Hub::new(host.clone());
+ let shared = Shared::with_features(hub.clone(), "e2e-token-0123456789abcdef".to_string(), "E2E PC".to_string(), None, Arc::new(server::NoFeatures));
+ let handle = start(shared, Target::parse(&url).unwrap(), credentials(&store).unwrap());
+ // The phone side is a Gradle run that may take minutes to compile on a cold runner, and an approval expires after about two
+ // minutes: ask for the decision only once the phone is connected.
+ let mut connecting = 0;
+ while hub.clients() == 0 && connecting < 6000 {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ connecting += 1;
+ }
+ hub.publish(
+ vec![],
+ Some(ApprovalIn {
+ request_id: "e2e-req".into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ tool: "Bash".into(),
+ command: "echo end-to-end".into(),
+ }),
+ server::now_ms(),
+ );
+ let mut waited = 0;
+ while host.0.lock().unwrap().is_empty() && waited < 1200 {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ waited += 1;
+ }
+ assert_eq!(host.0.lock().unwrap().clone(), vec![("e2e-req".to_string(), true)], "the phone's decision reached the computer");
+ handle.stop();
+ });
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/relay_crypto.rs b/windows/src-tauri/src/phone_link/relay_crypto.rs
new file mode 100644
index 00000000..c226ae15
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/relay_crypto.rs
@@ -0,0 +1,770 @@
+// The end-to-end encrypted channel for the relay link (docs/RELAY_LINK.md, sections 4 and 5).
+//
+// Pure: bytes in, bytes out. No sockets, no clock, no files, no logging. The relay client (stage R3) feeds it the binary
+// frames it gets from the WebSocket and sends the frames it returns. Everything is checked against
+// android/relay/test-vectors.json, which the Kotlin twin (android/.../link/RelayCrypto.kt) reads too.
+//
+// What it guarantees, in short:
+// * a data frame is AES-256-GCM under a key that is fresh for this connection and specific to one direction;
+// * the nonce is `direction ‖ 000 ‖ counter`, and the counter only goes up by one, so a (key, nonce) pair never repeats;
+// * a frame is accepted only if its counter is exactly the next expected one: a repeat, a gap or a jump is a fault;
+// * after any fault the session is dead (`Faulted`): the caller drops it and the phone starts a new handshake;
+// * secrets print as "..", are wiped when dropped, and nothing here writes them anywhere.
+
+// The phone's half of the handshake (`init_frame`, `finish_handshake`) is compiled for tests only: the computer never plays the phone.
+
+use ring::{aead, hkdf, hmac};
+
+pub const LABEL: &str = "coucou-relay/v1";
+pub const VER: u8 = 1;
+pub const T_INIT: u8 = 1;
+pub const T_ACCEPT: u8 = 2;
+pub const T_DATA: u8 = 3;
+/// What the relay accepts in one WebSocket message.
+pub const MAX_FRAME: usize = 66_000;
+/// A protocol v1 line, as on the LAN.
+pub const MAX_LINE: usize = 65_536;
+/// The last counter a session may use (2^32 - 1); then the phone re-handshakes.
+pub const LAST_COUNTER: u64 = u32::MAX as u64;
+const HEADER: usize = 10;
+const TAG: usize = 16;
+const NONCE_LEN: usize = 16;
+const MAC_LEN: usize = 32;
+const BLOCK: usize = 128;
+
+/// Who sends a frame: the key and the first byte of the nonce depend on it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Dir {
+ PhoneToHost = 1,
+ HostToPhone = 2,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ChannelError {
+ /// Too short, an unknown version or an unexpected frame type.
+ BadHeader,
+ /// The authentication tag (or a handshake MAC) did not verify: wrong key, wrong room, wrong direction, altered or truncated.
+ BadTag,
+ /// The counter is not the next expected one (repeat, gap, jump) or is past the last allowed.
+ BadCounter,
+ /// The decrypted padding is not the agreed shape.
+ BadPadding,
+ TooLong,
+ /// The session used its last counter; start a new handshake.
+ Exhausted,
+ /// An earlier fault ended this session.
+ Faulted,
+}
+
+// ── secrets ─────────────────────────────────────────────────────────────────────
+
+/// 32 secret bytes: redacted when printed, wiped when dropped. Never `Clone`, never `Display`.
+pub struct Secret32([u8; 32]);
+
+impl Secret32 {
+ pub fn as_bytes(&self) -> &[u8; 32] {
+ &self.0
+ }
+}
+
+impl std::fmt::Debug for Secret32 {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Secret32(..)")
+ }
+}
+
+impl Drop for Secret32 {
+ fn drop(&mut self) {
+ wipe(&mut self.0);
+ }
+}
+
+fn wipe(bytes: &mut [u8]) {
+ for b in bytes.iter_mut() {
+ // SAFETY: a plain write to a valid byte; volatile so the compiler cannot drop it as a dead store.
+ unsafe { std::ptr::write_volatile(b, 0) };
+ }
+}
+
+/// K, the pairing key, from the pairing link (43 base64url characters) or made fresh.
+pub struct PairingKey(Secret32);
+
+impl PairingKey {
+ pub fn from_bytes(bytes: [u8; 32]) -> Self {
+ PairingKey(Secret32(bytes))
+ }
+ pub fn from_base64url(text: &str) -> Option<Self> {
+ let bytes = base64url_decode(text)?;
+ Some(PairingKey::from_bytes(bytes.try_into().ok()?))
+ }
+ pub fn to_base64url(&self) -> String {
+ base64url_encode(self.0.as_bytes())
+ }
+ fn bytes(&self) -> &[u8; 32] {
+ self.0.as_bytes()
+ }
+}
+
+impl std::fmt::Debug for PairingKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("PairingKey(..)")
+ }
+}
+
+// ── derivation ──────────────────────────────────────────────────────────────────
+
+struct Len(usize);
+impl hkdf::KeyType for Len {
+ fn len(&self) -> usize {
+ self.0
+ }
+}
+
+/// HKDF-SHA-256 (RFC 5869).
+fn hkdf_sha256(ikm: &[u8], salt: &[u8], info: &[u8], out: &mut [u8]) {
+ let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(ikm);
+ let info = [info];
+ let okm = prk.expand(&info, Len(out.len())).expect("HKDF output length is within 255 blocks");
+ okm.fill(out).expect("HKDF fill");
+}
+
+fn derive32(k: &PairingKey, salt: &[u8], what: &str) -> Secret32 {
+ let mut out = [0u8; 32];
+ hkdf_sha256(k.bytes(), salt, format!("{LABEL} {what}").as_bytes(), &mut out);
+ Secret32(out)
+}
+
+/// `K_auth`: MACs the two handshake frames.
+pub fn k_auth(k: &PairingKey) -> Secret32 {
+ derive32(k, &[], "auth")
+}
+
+/// `K_join`: presented to the relay as a join proof; one-way from K.
+pub fn k_join(k: &PairingKey) -> Secret32 {
+ derive32(k, &[], "join")
+}
+
+/// The join proof for the `coucou.join.<…>` sub-protocol.
+pub fn join_proof(k: &PairingKey) -> String {
+ base64url_encode(k_join(k).as_bytes())
+}
+
+/// The two session keys, `(phone → host, host → phone)`, from K and the two fresh nonces.
+fn session_keys(k: &PairingKey, n_phone: &[u8; NONCE_LEN], n_host: &[u8; NONCE_LEN]) -> (Secret32, Secret32) {
+ let mut salt = [0u8; NONCE_LEN * 2];
+ salt[..NONCE_LEN].copy_from_slice(n_phone);
+ salt[NONCE_LEN..].copy_from_slice(n_host);
+ let mut out = [0u8; 64];
+ hkdf_sha256(k.bytes(), &salt, format!("{LABEL} session").as_bytes(), &mut out);
+ let mut a = [0u8; 32];
+ let mut b = [0u8; 32];
+ a.copy_from_slice(&out[..32]);
+ b.copy_from_slice(&out[32..]);
+ wipe(&mut out);
+ (Secret32(a), Secret32(b))
+}
+
+/// `direction ‖ 0x00 0x00 0x00 ‖ counter` (12 bytes).
+pub fn nonce_for(dir: Dir, counter: u64) -> [u8; 12] {
+ let mut n = [0u8; 12];
+ n[0] = dir as u8;
+ n[4..].copy_from_slice(&counter.to_be_bytes());
+ n
+}
+
+fn header(frame_type: u8, counter: u64) -> [u8; HEADER] {
+ let mut h = [0u8; HEADER];
+ h[0] = VER;
+ h[1] = frame_type;
+ h[2..].copy_from_slice(&counter.to_be_bytes());
+ h
+}
+
+fn aad(room: &str, dir: Dir, header: &[u8; HEADER]) -> Vec<u8> {
+ let mut a = Vec::with_capacity(LABEL.len() + room.len() + 1 + HEADER);
+ a.extend_from_slice(LABEL.as_bytes());
+ a.extend_from_slice(room.as_bytes());
+ a.push(dir as u8);
+ a.extend_from_slice(header);
+ a
+}
+
+// ── handshake ───────────────────────────────────────────────────────────────────
+
+fn mac(k_auth: &Secret32, parts: &[&[u8]]) -> hmac::Tag {
+ let key = hmac::Key::new(hmac::HMAC_SHA256, k_auth.as_bytes());
+ let mut msg = Vec::new();
+ for p in parts {
+ msg.extend_from_slice(p);
+ }
+ hmac::sign(&key, &msg)
+}
+
+fn mac_ok(k_auth: &Secret32, parts: &[&[u8]], tag: &[u8]) -> bool {
+ let key = hmac::Key::new(hmac::HMAC_SHA256, k_auth.as_bytes());
+ let mut msg = Vec::new();
+ for p in parts {
+ msg.extend_from_slice(p);
+ }
+ hmac::verify(&key, &msg, tag).is_ok() // constant time
+}
+
+/// A fresh 16-byte handshake nonce.
+pub fn fresh_nonce() -> [u8; NONCE_LEN] {
+ use ring::rand::SecureRandom;
+ let mut n = [0u8; NONCE_LEN];
+ ring::rand::SystemRandom::new().fill(&mut n).expect("the system random source works");
+ n
+}
+
+fn parse_handshake(frame: &[u8], wanted: u8) -> Result<([u8; NONCE_LEN], &[u8]), ChannelError> {
+ if frame.len() != HEADER + NONCE_LEN + MAC_LEN || frame[0] != VER || frame[1] != wanted || frame[2..HEADER] != 0u64.to_be_bytes() {
+ return Err(ChannelError::BadHeader);
+ }
+ let mut nonce = [0u8; NONCE_LEN];
+ nonce.copy_from_slice(&frame[HEADER..HEADER + NONCE_LEN]);
+ Ok((nonce, &frame[HEADER + NONCE_LEN..]))
+}
+
+/// The phone's first frame, and the nonce it must remember to check the answer.
+#[cfg(test)]
+pub fn init_frame(k: &PairingKey, room: &str, n_phone: [u8; NONCE_LEN]) -> Vec<u8> {
+ let tag = mac(&k_auth(k), &[b"init", room.as_bytes(), &n_phone]);
+ let mut f = header(T_INIT, 0).to_vec();
+ f.extend_from_slice(&n_phone);
+ f.extend_from_slice(tag.as_ref());
+ f
+}
+
+/// The computer's side: checks an `init`, answers with `accept`, and returns the session it will talk in.
+pub fn accept_init(k: &PairingKey, room: &str, init: &[u8], n_host: [u8; NONCE_LEN]) -> Result<(Vec<u8>, Session), ChannelError> {
+ let (n_phone, tag) = parse_handshake(init, T_INIT)?;
+ let auth = k_auth(k);
+ if !mac_ok(&auth, &[b"init", room.as_bytes(), &n_phone], tag) {
+ return Err(ChannelError::BadTag);
+ }
+ let reply = mac(&auth, &[b"accept", room.as_bytes(), &n_phone, &n_host]);
+ let mut f = header(T_ACCEPT, 0).to_vec();
+ f.extend_from_slice(&n_host);
+ f.extend_from_slice(reply.as_ref());
+ let (p2h, h2p) = session_keys(k, &n_phone, &n_host);
+ Ok((f, Session::new(Dir::HostToPhone, room, p2h, h2p)))
+}
+
+/// The phone's side: checks that the `accept` answers **its current** nonce, and returns the session.
+#[cfg(test)]
+pub fn finish_handshake(k: &PairingKey, room: &str, n_phone: &[u8; NONCE_LEN], accept: &[u8]) -> Result<Session, ChannelError> {
+ let (n_host, tag) = parse_handshake(accept, T_ACCEPT)?;
+ if !mac_ok(&k_auth(k), &[b"accept", room.as_bytes(), n_phone, &n_host], tag) {
+ return Err(ChannelError::BadTag);
+ }
+ let (p2h, h2p) = session_keys(k, n_phone, &n_host);
+ Ok(Session::new(Dir::PhoneToHost, room, p2h, h2p))
+}
+
+// ── the session ─────────────────────────────────────────────────────────────────
+
+/// One connection's keys and counters. `send` is the direction this side writes, `recv` the one it reads.
+pub struct Session {
+ room: String,
+ send_dir: Dir,
+ send_key: Secret32,
+ recv_key: Secret32,
+ send_counter: u64,
+ recv_next: u64,
+ send_done: bool,
+ faulted: bool,
+}
+
+impl std::fmt::Debug for Session {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Session(..)")
+ }
+}
+
+fn recv_dir(send: Dir) -> Dir {
+ match send {
+ Dir::PhoneToHost => Dir::HostToPhone,
+ Dir::HostToPhone => Dir::PhoneToHost,
+ }
+}
+
+impl Session {
+ fn new(me: Dir, room: &str, p2h: Secret32, h2p: Secret32) -> Session {
+ let (send_key, recv_key) = if me == Dir::PhoneToHost { (p2h, h2p) } else { (h2p, p2h) };
+ Session { room: room.to_string(), send_dir: me, send_key, recv_key, send_counter: 0, recv_next: 0, send_done: false, faulted: false }
+ }
+
+ /// Encrypts one protocol v1 line (UTF-8 JSON, without the newline) into a binary frame.
+ pub fn seal(&mut self, line: &[u8]) -> Result<Vec<u8>, ChannelError> {
+ if self.faulted {
+ return Err(ChannelError::Faulted);
+ }
+ if line.len() > MAX_LINE {
+ return Err(ChannelError::TooLong);
+ }
+ if self.send_done {
+ return Err(ChannelError::Exhausted);
+ }
+ let counter = self.send_counter;
+ let frame = seal_with(self.send_key.as_bytes(), &self.room, self.send_dir, counter, line);
+ if counter == LAST_COUNTER {
+ self.send_done = true; // that was the last frame this session may send
+ } else {
+ self.send_counter += 1;
+ }
+ Ok(frame)
+ }
+
+ /// Decrypts a binary frame from the other side. The counter must be exactly the next one. Any error ends the session.
+ pub fn open(&mut self, frame: &[u8]) -> Result<Vec<u8>, ChannelError> {
+ if self.faulted {
+ return Err(ChannelError::Faulted);
+ }
+ let result = self.open_checked(frame);
+ if result.is_err() {
+ self.faulted = true;
+ }
+ result
+ }
+
+ fn open_checked(&mut self, frame: &[u8]) -> Result<Vec<u8>, ChannelError> {
+ if frame.len() > MAX_FRAME {
+ return Err(ChannelError::TooLong);
+ }
+ if frame.len() < HEADER + TAG || frame[0] != VER || frame[1] != T_DATA {
+ return Err(ChannelError::BadHeader);
+ }
+ let counter = u64::from_be_bytes(frame[2..HEADER].try_into().unwrap());
+ if counter != self.recv_next || counter > LAST_COUNTER {
+ return Err(ChannelError::BadCounter);
+ }
+ let line = open_with(self.recv_key.as_bytes(), &self.room, recv_dir(self.send_dir), frame)?;
+ self.recv_next = counter + 1; // past LAST_COUNTER the next frame fails the check above
+ Ok(line)
+ }
+
+
+ #[cfg(test)]
+ fn set_send_counter_for_test(&mut self, counter: u64) {
+ self.send_counter = counter;
+ }
+}
+
+/// 4-byte length, the line, then zeros up to a multiple of 128 bytes (at least 128).
+fn pad(line: &[u8]) -> Vec<u8> {
+ let raw = 4 + line.len();
+ let total = raw.div_ceil(BLOCK).max(1) * BLOCK;
+ let mut p = Vec::with_capacity(total);
+ p.extend_from_slice(&(line.len() as u32).to_be_bytes());
+ p.extend_from_slice(line);
+ p.resize(total, 0);
+ p
+}
+
+fn unpad(plain: &[u8]) -> Result<Vec<u8>, ChannelError> {
+ if plain.len() < BLOCK || plain.len() % BLOCK != 0 {
+ return Err(ChannelError::BadPadding);
+ }
+ let n = u32::from_be_bytes(plain[..4].try_into().unwrap()) as usize;
+ if n > MAX_LINE || 4 + n > plain.len() || plain[4 + n..].iter().any(|b| *b != 0) {
+ return Err(ChannelError::BadPadding);
+ }
+ Ok(plain[4..4 + n].to_vec())
+}
+
+fn key_for(bytes: &[u8; 32]) -> aead::LessSafeKey {
+ aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_256_GCM, bytes).expect("a 32-byte key"))
+}
+
+/// Encrypts at an explicit counter. The session guarantees the counter is never reused; tests use it for the vectors.
+fn seal_with(key: &[u8; 32], room: &str, dir: Dir, counter: u64, line: &[u8]) -> Vec<u8> {
+ let h = header(T_DATA, counter);
+ let mut body = pad(line);
+ key_for(key)
+ .seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce_for(dir, counter)), aead::Aad::from(aad(room, dir, &h)), &mut body)
+ .expect("AES-GCM sealing cannot fail for a valid key and nonce");
+ let mut f = h.to_vec();
+ f.extend_from_slice(&body);
+ f
+}
+
+/// Header already checked by the caller; verifies the tag under the direction's key and unpads.
+fn open_with(key: &[u8; 32], room: &str, dir: Dir, frame: &[u8]) -> Result<Vec<u8>, ChannelError> {
+ let h: [u8; HEADER] = frame[..HEADER].try_into().unwrap();
+ let counter = u64::from_be_bytes(h[2..].try_into().unwrap());
+ let mut body = frame[HEADER..].to_vec();
+ let plain = key_for(key)
+ .open_in_place(aead::Nonce::assume_unique_for_key(nonce_for(dir, counter)), aead::Aad::from(aad(room, dir, &h)), &mut body)
+ .map_err(|_| ChannelError::BadTag)?;
+ let line = unpad(plain);
+ wipe(&mut body);
+ line
+}
+
+// ── base64url (no padding) ──────────────────────────────────────────────────────
+
+const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+
+pub fn base64url_encode(bytes: &[u8]) -> String {
+ let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
+ for chunk in bytes.chunks(3) {
+ let n = (chunk[0] as u32) << 16 | (*chunk.get(1).unwrap_or(&0) as u32) << 8 | *chunk.get(2).unwrap_or(&0) as u32;
+ out.push(B64[(n >> 18) as usize & 63] as char);
+ out.push(B64[(n >> 12) as usize & 63] as char);
+ if chunk.len() > 1 {
+ out.push(B64[(n >> 6) as usize & 63] as char);
+ }
+ if chunk.len() > 2 {
+ out.push(B64[n as usize & 63] as char);
+ }
+ }
+ out
+}
+
+/// Strict: only the 64 URL-safe characters, no padding, and the unused trailing bits must be zero.
+pub fn base64url_decode(text: &str) -> Option<Vec<u8>> {
+ let val = |c: u8| B64.iter().position(|x| *x == c).map(|p| p as u32);
+ let bytes = text.as_bytes();
+ if bytes.len() % 4 == 1 {
+ return None;
+ }
+ let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
+ for chunk in bytes.chunks(4) {
+ let mut n = 0u32;
+ for (i, c) in chunk.iter().enumerate() {
+ n |= val(*c)? << (18 - 6 * i as u32);
+ }
+ let take = chunk.len() * 6 / 8;
+ let b = n.to_be_bytes();
+ out.extend_from_slice(&b[1..1 + take]);
+ let unused_bits = chunk.len() * 6 - take * 8;
+ if unused_bits > 0 && (n >> (24 - chunk.len() as u32 * 6)) & ((1 << unused_bits) - 1) != 0 {
+ return None;
+ }
+ }
+ Some(out)
+}
+
+// ── tests ───────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::Value;
+
+ const VECTORS: &str = include_str!("../../../../android/relay/test-vectors.json");
+
+ fn vectors() -> Value {
+ serde_json::from_str(VECTORS).unwrap()
+ }
+ fn unhex(s: &str) -> Vec<u8> {
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
+ }
+ fn text<'a>(v: &'a Value, path: &[&str]) -> &'a str {
+ let mut cur = v;
+ for p in path {
+ cur = &cur[*p];
+ }
+ cur.as_str().unwrap_or_else(|| panic!("{path:?}"))
+ }
+ fn hexs(b: &[u8]) -> String {
+ b.iter().map(|x| format!("{x:02x}")).collect()
+ }
+ fn n16(h: &str) -> [u8; 16] {
+ unhex(h).try_into().unwrap()
+ }
+ fn key(v: &Value) -> PairingKey {
+ PairingKey::from_bytes(unhex(text(v, &["inputs", "key"])).try_into().unwrap())
+ }
+ fn dir(s: &str) -> Dir {
+ if s == "p2h" { Dir::PhoneToHost } else { Dir::HostToPhone }
+ }
+ fn session_keys_of(v: &Value) -> (Secret32, Secret32) {
+ session_keys(&key(v), &n16(text(v, &["inputs", "nPhone"])), &n16(text(v, &["inputs", "nPc"])))
+ }
+
+ #[test]
+ fn hkdf_matches_rfc_5869_a1() {
+ let v = vectors();
+ let r = &v["rfc5869_a1"];
+ let mut out = vec![0u8; r["length"].as_u64().unwrap() as usize];
+ hkdf_sha256(&unhex(text(r, &["ikm"])), &unhex(text(r, &["salt"])), &unhex(text(r, &["info"])), &mut out);
+ assert_eq!(hexs(&out), text(r, &["okm"]));
+ }
+
+ #[test]
+ fn derived_keys_match_the_vectors() {
+ let v = vectors();
+ let k = key(&v);
+ assert_eq!(hexs(k_auth(&k).as_bytes()), text(&v, &["derived", "kAuth"]));
+ assert_eq!(hexs(k_join(&k).as_bytes()), text(&v, &["derived", "kJoin"]));
+ let (p2h, h2p) = session_keys_of(&v);
+ assert_eq!(hexs(p2h.as_bytes()), text(&v, &["derived", "kP2H"]));
+ assert_eq!(hexs(h2p.as_bytes()), text(&v, &["derived", "kH2P"]));
+ assert_eq!(join_proof(&k), base64url_encode(k_join(&k).as_bytes()));
+ assert_eq!(join_proof(&k).len(), 43);
+ }
+
+ #[test]
+ fn the_handshake_frames_match_the_vectors_and_the_two_sides_agree() {
+ let v = vectors();
+ let (k, room) = (key(&v), text(&v, &["inputs", "room"]));
+ let (n_phone, n_pc) = (n16(text(&v, &["inputs", "nPhone"])), n16(text(&v, &["inputs", "nPc"])));
+ let init = init_frame(&k, room, n_phone);
+ assert_eq!(hexs(&init), text(&v, &["init", "frame"]));
+ let (accept, mut host) = accept_init(&k, room, &init, n_pc).unwrap();
+ assert_eq!(hexs(&accept), text(&v, &["accept", "frame"]));
+ let mut phone = finish_handshake(&k, room, &n_phone, &accept).unwrap();
+ // They talk to each other, in order, both ways.
+ let a = phone.seal(b"{\"type\":\"hello\"}").unwrap();
+ assert_eq!(host.open(&a).unwrap(), b"{\"type\":\"hello\"}");
+ let b = host.seal(b"{\"type\":\"welcome\"}").unwrap();
+ assert_eq!(phone.open(&b).unwrap(), b"{\"type\":\"welcome\"}");
+ }
+
+ #[test]
+ fn a_wrong_key_room_or_stale_accept_is_refused() {
+ let v = vectors();
+ let (k, room) = (key(&v), text(&v, &["inputs", "room"]));
+ let (n_phone, n_pc) = (n16(text(&v, &["inputs", "nPhone"])), n16(text(&v, &["inputs", "nPc"])));
+ let init = init_frame(&k, room, n_phone);
+ let other = PairingKey::from_bytes([9; 32]);
+ assert_eq!(accept_init(&other, room, &init, n_pc).err(), Some(ChannelError::BadTag));
+ assert_eq!(accept_init(&k, "AAAAAAAAAAAAAAAAAAAAAA", &init, n_pc).err(), Some(ChannelError::BadTag));
+ let (accept, _) = accept_init(&k, room, &init, n_pc).unwrap();
+ // The phone has since started a new handshake with a different nonce: the old accept must not be taken.
+ assert_eq!(finish_handshake(&k, room, &[7; 16], &accept).err(), Some(ChannelError::BadTag));
+ // An init is not an accept, and nothing else is either.
+ assert_eq!(finish_handshake(&k, room, &n_phone, &init).err(), Some(ChannelError::BadHeader));
+ assert_eq!(accept_init(&k, room, &accept, n_pc).err(), Some(ChannelError::BadHeader));
+ assert_eq!(accept_init(&k, room, &init[..40], n_pc).err(), Some(ChannelError::BadHeader));
+ let mut flipped = init.clone();
+ flipped[12] ^= 1;
+ assert_eq!(accept_init(&k, room, &flipped, n_pc).err(), Some(ChannelError::BadTag));
+ }
+
+ #[test]
+ fn data_frames_reproduce_the_vectors_byte_for_byte_and_open_back() {
+ let v = vectors();
+ let room = text(&v, &["inputs", "room"]);
+ let (p2h, h2p) = session_keys_of(&v);
+ for c in v["data"].as_array().unwrap() {
+ let d = dir(text(c, &["dir"]));
+ let k = if d == Dir::PhoneToHost { &p2h } else { &h2p };
+ let counter = c["counter"].as_u64().unwrap();
+ let line = text(c, &["line"]);
+ assert_eq!(hexs(&nonce_for(d, counter)), text(c, &["nonce"]));
+ assert_eq!(hexs(&pad(line.as_bytes())), text(c, &["plaintext"]));
+ let sealed = seal_with(k.as_bytes(), room, d, counter, line.as_bytes());
+ assert_eq!(hexs(&sealed), text(c, &["frame"]), "{d:?} {counter}");
+ assert_eq!(open_with(k.as_bytes(), room, d, &sealed).unwrap(), line.as_bytes());
+ }
+ }
+
+ /// A session standing in for the receiving side of `d`, in its first-frame state.
+ fn receiver_of(v: &Value, d: Dir) -> Session {
+ let (k, room) = (key(v), text(v, &["inputs", "room"]));
+ let (n_phone, n_pc) = (n16(text(v, &["inputs", "nPhone"])), n16(text(v, &["inputs", "nPc"])));
+ let init = init_frame(&k, room, n_phone);
+ let (accept, host) = accept_init(&k, room, &init, n_pc).unwrap();
+ if d == Dir::PhoneToHost { host } else { finish_handshake(&k, room, &n_phone, &accept).unwrap() }
+ }
+
+ #[test]
+ fn frames_that_must_be_refused_are_refused_with_the_listed_reason() {
+ let v = vectors();
+ let room = text(&v, &["inputs", "room"]).to_string();
+ for n in v["mustRefuse"].as_array().unwrap() {
+ let d = dir(text(n, &["dir"]));
+ let frame = unhex(text(n, &["frame"]));
+ // Which session receives it: the one reading direction `d`.
+ let mut rx = receiver_of(&v, if d == Dir::PhoneToHost { Dir::PhoneToHost } else { Dir::HostToPhone });
+ // Another room or another key means a session built from different inputs.
+ if n.get("room").is_some() || n.get("key").is_some() {
+ let k = match n.get("key") {
+ Some(h) => PairingKey::from_bytes(unhex(h.as_str().unwrap()).try_into().unwrap()),
+ None => key(&v),
+ };
+ let r = n.get("room").and_then(|r| r.as_str()).unwrap_or(&room).to_string();
+ let (n_phone, n_pc) = (n16(text(&v, &["inputs", "nPhone"])), n16(text(&v, &["inputs", "nPc"])));
+ let (init, _) = (init_frame(&k, &r, n_phone), ());
+ rx = accept_init(&k, &r, &init, n_pc).unwrap().1;
+ }
+ let expect = match text(n, &["expect"]) {
+ "bad_tag" => ChannelError::BadTag,
+ "bad_header" => ChannelError::BadHeader,
+ other => panic!("{other}"),
+ };
+ let name = text(n, &["name"]);
+ let got = rx.open(&frame).err();
+ // A flipped counter byte is refused by the counter rule first; the vector calls it a bad tag (either way: refused).
+ if name == "the counter in the header changed" {
+ assert_eq!(got, Some(ChannelError::BadCounter), "{name}");
+ } else {
+ assert_eq!(got, Some(expect), "{name}");
+ }
+ // After a fault the session is dead.
+ assert_eq!(rx.open(&frame).err(), Some(ChannelError::Faulted), "{name}");
+ }
+ }
+
+ #[test]
+ fn counter_sequences_follow_the_rule() {
+ let v = vectors();
+ let (room, k) = (text(&v, &["inputs", "room"]), key(&v));
+ let (p2h, _) = session_keys_of(&v);
+ for s in v["mustRefuseInOrder"].as_array().unwrap() {
+ let mut rx = receiver_of(&v, Dir::PhoneToHost);
+ let counters: Vec<u64> = s["counters"].as_array().unwrap().iter().map(|c| c.as_u64().unwrap()).collect();
+ let want: Vec<bool> = s["accepted"].as_array().unwrap().iter().map(|c| c.as_bool().unwrap()).collect();
+ let mut got = Vec::new();
+ for c in counters {
+ let frame = seal_with(p2h.as_bytes(), room, Dir::PhoneToHost, c, b"{\"type\":\"ping\"}");
+ got.push(rx.open(&frame).is_ok());
+ }
+ assert_eq!(got, want, "{}", text(s, &["name"]));
+ }
+ let _ = k;
+ }
+
+ #[test]
+ fn no_key_and_nonce_pair_repeats_across_both_directions_and_two_sessions() {
+ let mut seen = std::collections::HashSet::new();
+ let k = PairingKey::from_bytes([3; 32]);
+ for (np, nh) in [([1u8; 16], [2u8; 16]), ([5u8; 16], [6u8; 16])] {
+ let (p2h, h2p) = session_keys(&k, &np, &nh);
+ assert_ne!(p2h.as_bytes(), h2p.as_bytes(), "the directions share a key");
+ for c in 0..3000u64 {
+ assert!(seen.insert((*p2h.as_bytes(), nonce_for(Dir::PhoneToHost, c))), "p2h {c}");
+ assert!(seen.insert((*h2p.as_bytes(), nonce_for(Dir::HostToPhone, c))), "h2p {c}");
+ }
+ }
+ assert_eq!(seen.len(), 2 * 2 * 3000, "four distinct keys, 3000 nonces each");
+ // Even a bug that made both directions share a key could not collide: the direction is in the nonce.
+ assert_ne!(nonce_for(Dir::PhoneToHost, 5), nonce_for(Dir::HostToPhone, 5));
+ }
+
+ #[test]
+ fn the_sessions_themselves_reproduce_the_vector_frames_in_each_direction() {
+ // Not just the helper functions: the keys a Session picks for sending and receiving are the vector's, per direction.
+ let v = vectors();
+ let mut phone = receiver_of(&v, Dir::HostToPhone); // the phone's session
+ let mut host = receiver_of(&v, Dir::PhoneToHost); // the computer's session
+ let mut checked = 0;
+ for c in v["data"].as_array().unwrap() {
+ let (d, counter) = (dir(text(c, &["dir"])), c["counter"].as_u64().unwrap());
+ if counter > 2 {
+ continue; // the last-counter vector is covered by its own test
+ }
+ let (sender, receiver) = if d == Dir::PhoneToHost { (&mut phone, &mut host) } else { (&mut host, &mut phone) };
+ let frame = sender.seal(text(c, &["line"]).as_bytes()).unwrap();
+ assert_eq!(hexs(&frame), text(c, &["frame"]), "{d:?} {counter}");
+ assert_eq!(receiver.open(&frame).unwrap(), text(c, &["line"]).as_bytes());
+ checked += 1;
+ }
+ assert_eq!(checked, 5);
+ assert_ne!(phone.send_key.as_bytes(), phone.recv_key.as_bytes(), "a session must not send and receive under one key");
+ assert_ne!(host.send_key.as_bytes(), host.recv_key.as_bytes());
+ assert_eq!(phone.send_key.as_bytes(), host.recv_key.as_bytes());
+ assert_eq!(host.send_key.as_bytes(), phone.recv_key.as_bytes());
+ }
+
+ #[test]
+ fn a_session_sends_counters_in_order_and_never_reuses_one() {
+ let v = vectors();
+ let mut host = receiver_of(&v, Dir::PhoneToHost);
+ let mut counters = Vec::new();
+ for _ in 0..500 {
+ let f = host.seal(b"{}").unwrap();
+ counters.push(u64::from_be_bytes(f[2..10].try_into().unwrap()));
+ }
+ assert_eq!(counters, (0..500).collect::<Vec<u64>>());
+ }
+
+ #[test]
+ fn a_sender_at_the_last_counter_sends_it_once_and_then_refuses() {
+ let v = vectors();
+ let mut host = receiver_of(&v, Dir::PhoneToHost);
+ host.set_send_counter_for_test(LAST_COUNTER - 1);
+ assert!(host.seal(b"{}").is_ok());
+ let last = host.seal(b"{}").unwrap();
+ assert_eq!(u64::from_be_bytes(last[2..10].try_into().unwrap()), LAST_COUNTER);
+ assert_eq!(host.seal(b"{}").err(), Some(ChannelError::Exhausted));
+ assert_eq!(host.seal(b"{}").err(), Some(ChannelError::Exhausted));
+ }
+
+ #[test]
+ fn a_receiver_refuses_a_counter_past_the_last_one() {
+ let v = vectors();
+ let (room, (p2h, _)) = (text(&v, &["inputs", "room"]), session_keys_of(&v));
+ let mut rx = receiver_of(&v, Dir::PhoneToHost);
+ let beyond = seal_with(p2h.as_bytes(), room, Dir::PhoneToHost, LAST_COUNTER + 1, b"{}");
+ assert_eq!(rx.open(&beyond).err(), Some(ChannelError::BadCounter));
+ }
+
+ #[test]
+ fn lines_pad_to_blocks_and_the_size_limit_holds() {
+ assert_eq!(pad(b"").len(), 128);
+ assert_eq!(pad(&[b'a'; 124]).len(), 128);
+ assert_eq!(pad(&[b'a'; 125]).len(), 256);
+ let v = vectors();
+ let mut tx = receiver_of(&v, Dir::PhoneToHost);
+ let mut rx = receiver_of(&v, Dir::HostToPhone);
+ let biggest = vec![b'x'; MAX_LINE];
+ let frame = tx.seal(&biggest).unwrap();
+ assert!(frame.len() <= MAX_FRAME, "{} bytes", frame.len());
+ assert_eq!(rx.open(&frame).unwrap(), biggest);
+ assert_eq!(tx.seal(&vec![b'x'; MAX_LINE + 1]).err(), Some(ChannelError::TooLong));
+ assert_eq!(rx.open(&vec![0u8; MAX_FRAME + 1]).err(), Some(ChannelError::TooLong));
+ }
+
+ #[test]
+ fn a_frame_with_bad_padding_is_refused_even_with_a_valid_tag() {
+ let v = vectors();
+ let (room, (p2h, _)) = (text(&v, &["inputs", "room"]), session_keys_of(&v));
+ for plain in [vec![0u8; 100], { let mut p = pad(b"{}"); p[100] = 1; p }, { let mut p = pad(b"{}"); p[..4].copy_from_slice(&200u32.to_be_bytes()); p }] {
+ let h = header(T_DATA, 0);
+ let mut body = plain.clone();
+ key_for(p2h.as_bytes())
+ .seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce_for(Dir::PhoneToHost, 0)), aead::Aad::from(aad(room, Dir::PhoneToHost, &h)), &mut body)
+ .unwrap();
+ let mut f = h.to_vec();
+ f.extend_from_slice(&body);
+ let mut rx = receiver_of(&v, Dir::PhoneToHost);
+ assert_eq!(rx.open(&f).err(), Some(ChannelError::BadPadding));
+ }
+ }
+
+ #[test]
+ fn base64url_round_trips_and_is_strict() {
+ for len in 0..40usize {
+ let bytes: Vec<u8> = (0..len as u8).map(|i| i.wrapping_mul(37)).collect();
+ assert_eq!(base64url_decode(&base64url_encode(&bytes)).unwrap(), bytes, "{len}");
+ }
+ let v = vectors();
+ assert_eq!(base64url_encode(&unhex(text(&v, &["inputs", "roomBytes"]))), text(&v, &["inputs", "room"]));
+ assert_eq!(base64url_encode(&[0xfb, 0xff]), "-_8");
+ for bad in ["A", "AAAAA", "AA=A", "A+AA", "A/AA", "AB", "AAB", "a b "] {
+ assert_eq!(base64url_decode(bad), None, "{bad}");
+ }
+ assert!(PairingKey::from_base64url(&base64url_encode(&[1u8; 32])).is_some());
+ assert!(PairingKey::from_base64url(&base64url_encode(&[1u8; 31])).is_none());
+ }
+
+ #[test]
+ fn secrets_never_print_and_the_module_never_logs() {
+ let k = PairingKey::from_bytes([0xab; 32]);
+ let text_of_key = format!("{k:?} {:?}", k_auth(&k));
+ assert!(!text_of_key.contains("ab") && !text_of_key.contains("171"), "{text_of_key}");
+ let v = vectors();
+ let s = receiver_of(&v, Dir::PhoneToHost);
+ let shown = format!("{s:?}");
+ assert_eq!(shown, "Session(..)");
+ let src = include_str!("relay_crypto.rs");
+ let code = src.split("// ── tests").next().unwrap();
+ for forbidden in ["println!", "eprintln!", "dbg!", "log::", "tracing::", "std::fs", "std::env", "File::"] {
+ assert!(!code.contains(forbidden), "relay_crypto.rs uses {forbidden}");
+ }
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/server.rs b/windows/src-tauri/src/phone_link/server.rs
new file mode 100644
index 00000000..3c42cbcb
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/server.rs
@@ -0,0 +1,449 @@
+// The phone link's TLS server (docs/ANDROID_LINK.md, protocol v1).
+//
+// One accepted connection is two tasks: a reader that checks the phone's lines
+// and a writer that sends what the hub queues. The reader owns the way in, so
+// when it ends (the phone left, a protocol error, the idle timeout) the writer
+// finishes what is queued, including a last `error`, and closes.
+//
+// What it refuses, on purpose:
+// * anyone who is not on the local network (private, loopback, link-local);
+// * a first message that is not a valid `hello` within a few seconds;
+// * a wrong token or protocol version (after a short pause, so guessing is slow);
+// * a line over 64 KiB, or silence for 20 minutes (the phone pings every 20 s while it is awake, and checks in every few minutes while it sleeps);
+// * more than a handful of connections at once, and more than two silent ones from one address: see
+// admission.rs (strangers share a small pool, a phone that authenticated before keeps its place, and the
+// TLS handshake and the hello get less time when the pool is filling up).
+// It never touches the agent: a decision goes through `Hub::decide`, which only
+// applies the request still pending.
+
+use std::net::IpAddr;
+use std::sync::atomic::Ordering;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use serde_json::json;
+use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
+use tokio::net::{TcpListener, TcpStream};
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
+use tokio_rustls::rustls::version::{TLS12, TLS13};
+use tokio_rustls::rustls::{crypto::ring as ring_provider, ServerConfig};
+use tokio_rustls::TlsAcceptor;
+
+use super::admission::{Admission, Ticket};
+use super::chat::ChatLink;
+use super::hub::{constant_eq, Hub, Out};
+use super::pairing::Identity;
+
+pub const PROTOCOL: u64 = 1;
+pub const MAX_LINE: usize = 64 * 1024;
+const HELLO_TIMEOUT: Duration = Duration::from_secs(10);
+/// An authenticated phone may be silent this long. A sleeping phone cannot ping every 20 s (its timers stop with the CPU), so a
+/// short limit here dropped it after 90 s and it only noticed on waking. Its alarm checks in every few minutes (Doze may stretch that
+/// to about 15), so the limit is well above that. A conversation whose phone vanished without a goodbye (its address changed)
+/// holds one of the 8 places until then.
+const IDLE_TIMEOUT: Duration = Duration::from_secs(20 * 60);
+
+#[cfg(test)]
+mod idle_tests {
+ #[test]
+ fn the_idle_limit_is_well_above_what_a_sleeping_phone_needs() {
+ // The phone's alarm asks for a check every 4 minutes and Doze can stretch that to about 15 (KeepAlivePolicy.kt).
+ assert!(super::IDLE_TIMEOUT >= std::time::Duration::from_secs(16 * 60));
+ // But not unbounded: a vanished phone must not hold a place for hours.
+ assert!(super::IDLE_TIMEOUT <= std::time::Duration::from_secs(30 * 60));
+ }
+}
+/// Pause before answering a wrong token.
+const AUTH_PENALTY: Duration = Duration::from_millis(400);
+
+/// Which optional features the user has switched on, read again for every connection.
+pub trait Features: Send + Sync {
+ /// Session details: the steps, the last line, the project's folder name and the colour.
+ fn details(&self) -> bool;
+ /// Answering the questions Claude Code asks, from the phone (the screen-lock check is the phone's).
+ fn answers(&self) -> bool {
+ false
+ }
+ /// File changes: the list of files of a session, and a file's diff on request.
+ fn diffs(&self) -> bool {
+ false
+ }
+ /// The plan usage (percentages and reset times of the Claude and Codex plans).
+ fn usage(&self) -> bool {
+ false
+ }
+ /// The relay is switched on (the phone then follows an access key rotation).
+ fn relay(&self) -> bool {
+ false
+ }
+ /// The services the user allowed for the phone (their ids); empty: none.
+ fn services(&self) -> Vec<String> {
+ Vec::new()
+ }
+}
+
+/// Nothing extra: how the link behaved before capabilities existed.
+#[cfg(test)]
+pub struct NoFeatures;
+#[cfg(test)]
+impl Features for NoFeatures {
+ fn details(&self) -> bool {
+ false
+ }
+}
+
+/// What a connection needs to know about the desktop.
+pub struct Shared {
+ pub hub: Arc<Hub>,
+ /// Replaced when the user pairs again; read for every `hello`.
+ pub token: Mutex<String>,
+ pub name: String,
+ /// Tests run on loopback and through a stand-in clock.
+ pub clock: fn() -> u64,
+ /// Chat from the phone; None where the feature is not wired in. Offered only to a phone that asks for it.
+ pub chat: Option<Arc<ChatLink>>,
+ pub features: Arc<dyn Features>,
+ admission: Arc<Admission>,
+}
+
+impl Shared {
+ pub fn with_features(hub: Arc<Hub>, token: String, name: String, chat: Option<Arc<ChatLink>>, features: Arc<dyn Features>) -> Arc<Shared> {
+ Arc::new(Shared { hub, token: Mutex::new(token), name, clock: now_ms, chat, features, admission: Admission::new() })
+ }
+}
+
+impl Shared {
+ /// A slot for the relay link, which reaches the server as one source: the relay's own forwarding is not a LAN
+ /// address, and the relay never shows who is behind it. One slot at a time, so a flood at the relay cannot
+ /// use more of the pool than a flood from one LAN address could.
+ #[cfg(test)]
+ pub(super) fn admission_counts(&self) -> (usize, usize) {
+ self.admission.counts()
+ }
+
+ pub(super) fn admit_relay(&self) -> Option<Ticket> {
+ self.admission.admit(RELAY_SOURCE)
+ }
+}
+
+/// The stand-in source address of everything that arrives through the relay (a documentation address, never routable).
+pub(super) const RELAY_SOURCE: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 255));
+
+pub fn now_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// A running server; dropping it does not stop it, `stop` does.
+pub struct Handle {
+ accept: JoinHandle<()>,
+ shared: Arc<Shared>,
+}
+
+impl Handle {
+ pub fn stop(self) {
+ self.accept.abort();
+ self.shared.hub.kick_all("closed", "the phone link was turned off");
+ if let Some(chat) = &self.shared.chat {
+ chat.shutdown();
+ }
+ }
+}
+
+/// TLS 1.2 and 1.3, the certificate made once. `ring` is named explicitly so
+/// nothing depends on a process-wide default provider.
+pub fn tls_acceptor(identity: &Identity) -> Result<TlsAcceptor, String> {
+ let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.key_der.clone()));
+ let config = ServerConfig::builder_with_provider(Arc::new(ring_provider::default_provider()))
+ .with_protocol_versions(&[&TLS13, &TLS12])
+ .map_err(|e| e.to_string())?
+ .with_no_client_auth()
+ .with_single_cert(vec![CertificateDer::from(identity.cert_der.clone())], key)
+ .map_err(|e| e.to_string())?;
+ Ok(TlsAcceptor::from(Arc::new(config)))
+}
+
+/// Accepts connections until stopped. Must be called inside the async runtime.
+pub fn serve(listener: TcpListener, acceptor: TlsAcceptor, shared: Arc<Shared>) -> Handle {
+ let for_handle = shared.clone();
+ let accept = tokio::spawn(async move {
+ loop {
+ let (tcp, peer) = match listener.accept().await {
+ Ok(x) => x,
+ Err(_) => {
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ continue;
+ }
+ };
+ if !is_local(peer.ip()) {
+ continue; // dropped before any byte is read
+ }
+ // The slot is held until the connection ends (the ticket drops), whatever way it ends.
+ let Some(ticket) = shared.admission.admit(peer.ip()) else { continue };
+ let (shared, acceptor) = (shared.clone(), acceptor.clone());
+ tokio::spawn(async move {
+ let _ = tcp.set_nodelay(true);
+ one_connection(tcp, acceptor, &shared, Arc::new(ticket)).await;
+ });
+ }
+ });
+ Handle { accept, shared: for_handle }
+}
+
+/// The local network only: private, loopback and link-local addresses.
+pub fn is_local(ip: IpAddr) -> bool {
+ match ip {
+ IpAddr::V4(v4) => v4.is_private() || v4.is_loopback() || v4.is_link_local(),
+ IpAddr::V6(v6) => {
+ if let Some(v4) = v6.to_ipv4_mapped() {
+ return is_local(IpAddr::V4(v4));
+ }
+ let first = v6.segments()[0];
+ v6.is_loopback() || (first & 0xfe00) == 0xfc00 /* fc00::/7 */ || (first & 0xffc0) == 0xfe80 /* fe80::/10 */
+ }
+ }
+}
+
+async fn one_connection(tcp: TcpStream, acceptor: TlsAcceptor, shared: &Arc<Shared>, ticket: Arc<Ticket>) {
+ let Ok(Ok(tls)) = tokio::time::timeout(ticket.wait(), acceptor.accept(tcp)).await else { return };
+ run_with(tls, shared, Some(ticket)).await;
+}
+
+/// The conversation over a byte stream (TLS in the app), holding its admission ticket until it ends.
+pub(super) async fn run_with<S>(stream: S, shared: &Arc<Shared>, ticket: Option<Arc<Ticket>>)
+where
+ S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
+{
+ let (read, mut write) = tokio::io::split(stream);
+ let (tx, mut rx) = mpsc::channel::<Out>(64);
+
+ let reader = tokio::spawn(read_loop(read, tx, shared.clone(), ticket));
+
+ while let Some(out) = rx.recv().await {
+ let (line, last) = match out {
+ Out::Line(l) => (l.to_string(), false),
+ Out::Close { code, message } => (json!({ "type": "error", "code": code, "message": message }).to_string(), true),
+ };
+ if write.write_all(line.as_bytes()).await.is_err() || write.write_all(b"\n").await.is_err() || write.flush().await.is_err() || last {
+ break;
+ }
+ }
+ reader.abort();
+ let _ = write.shutdown().await;
+}
+
+async fn read_loop<R>(read: R, tx: mpsc::Sender<Out>, shared: Arc<Shared>, ticket: Option<Arc<Ticket>>)
+where
+ R: AsyncRead + Unpin,
+{
+ let mut lines = LineReader::new(read);
+ let say = |v: serde_json::Value| tx.send(Out::Line(v.to_string().into()));
+
+ // 1. hello
+ let hello_wait = ticket.as_ref().map_or(HELLO_TIMEOUT, |t| t.wait());
+ let hello = match tokio::time::timeout(hello_wait, lines.next()).await {
+ Ok(Next::Line(l)) => l,
+ Ok(Next::TooLong) => {
+ let _ = tx.send(Out::Close { code: "protocol", message: "line too long" }).await;
+ return;
+ }
+ _ => return,
+ };
+ let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&hello) else { return };
+ if hello["type"] != "hello" {
+ return;
+ }
+ let sent_token = hello["token"].as_str().unwrap_or("").to_string();
+ let expected = shared.token.lock().unwrap().clone();
+ let good = hello["v"].as_u64() == Some(PROTOCOL) && constant_eq(sent_token.as_bytes(), expected.as_bytes());
+ if !good {
+ tokio::time::sleep(AUTH_PENALTY).await;
+ let _ = tx.send(Out::Close { code: "auth", message: "bad token or version" }).await;
+ return;
+ }
+ // A valid hello: from here on this connection no longer counts against the unauthenticated limits, and the
+ // address is remembered so a flood from elsewhere cannot keep this phone out.
+ if let Some(t) = &ticket {
+ t.authenticated();
+ }
+ // Capabilities: offered only if the phone asked and the user's switch is on right now. A phone
+ // that sends none (an older app) is never sent, and never answered, anything about chat.
+ let asked_chat = hello["caps"].as_array().is_some_and(|c| c.iter().any(|x| x == "chat"));
+ let chat = shared.chat.clone().filter(|c| asked_chat && c.enabled());
+ let asked = |cap: &str| hello["caps"].as_array().is_some_and(|c| c.iter().any(|x| x == cap));
+ let details = asked("details") && shared.features.details();
+ let answers = asked("answers") && shared.features.answers();
+ // The outfit is no secret and says nothing about the user's work: offered whenever the phone asks.
+ let prefs = asked("prefs");
+ let diffs = asked("diffs") && shared.features.diffs();
+ let usage = asked("usage") && shared.features.usage();
+ let relay = asked("relay") && shared.features.relay();
+ let services: Vec<String> = if asked("services") { shared.features.services() } else { Vec::new() };
+ let mut offered: Vec<&str> = Vec::new();
+ if chat.is_some() {
+ offered.push("chat");
+ }
+ if details {
+ offered.push("details");
+ }
+ if answers {
+ offered.push("answers");
+ }
+ if prefs {
+ offered.push("prefs");
+ }
+ if diffs {
+ offered.push("diffs");
+ }
+ if usage {
+ offered.push("usage");
+ }
+ if relay {
+ offered.push("relay");
+ }
+ if !services.is_empty() {
+ offered.push("services");
+ }
+ let mut welcome = json!({ "type": "welcome", "v": PROTOCOL, "desktop": shared.name, "os": std::env::consts::OS });
+ if !offered.is_empty() {
+ welcome["caps"] = json!(offered);
+ }
+ let _ = say(welcome).await;
+ let (id, evicted) = shared.hub.subscribe_with(tx.clone(), (shared.clock)(), crate::phone_link::hub::Caps { details, answers, prefs, diffs, usage, relay, services });
+
+ // 2. the conversation
+ loop {
+ let line = match tokio::time::timeout(IDLE_TIMEOUT, lines.next()).await {
+ Ok(Next::Line(l)) => l,
+ Ok(Next::TooLong) => {
+ let _ = tx.send(Out::Close { code: "protocol", message: "line too long" }).await;
+ break;
+ }
+ _ => break, // closed, failed or silent for too long
+ };
+ let Ok(msg) = serde_json::from_slice::<serde_json::Value>(&line) else { break };
+ // The hub stopped sending to this phone because it could not keep up:
+ // close, and the phone reconnects to a fresh picture (it pings every 20 s).
+ if evicted.load(Ordering::SeqCst) {
+ break;
+ }
+ match msg["type"].as_str() {
+ Some("ping") => {
+ let _ = say(json!({ "type": "pong" })).await;
+ }
+ Some("decision") => {
+ let fingerprint = msg["fingerprint"].as_str().unwrap_or("");
+ let decision = msg["decision"].as_str().unwrap_or("");
+ // The hub tells every phone when it applies one; an ignored
+ // decision changes nothing at all.
+ let _ = shared.hub.decide(fingerprint, decision, (shared.clock)());
+ }
+ Some("answer") if answers => {
+ // One list of labels per question. A malformed one, or one that does not match the pending question
+ // exactly, changes nothing (hub.rs).
+ let fingerprint = msg["fingerprint"].as_str().unwrap_or("");
+ if let Some(picks) = parse_picks(&msg["picks"]) {
+ let _ = shared.hub.answer(fingerprint, &picks, (shared.clock)());
+ }
+ }
+ Some("getDiff") if diffs => {
+ // Which file of which session; what it holds is the island's (hub.rs checks the rate and the limits).
+ let pill = msg["pillId"].as_str().unwrap_or("");
+ if let (false, true, Some(file)) = (pill.is_empty(), pill.len() <= 64, msg["fileId"].as_u64()) {
+ shared.hub.request_diff(id, pill, file, (shared.clock)());
+ }
+ }
+ Some("bye") => break,
+ Some(t) if t.starts_with("chat") => {
+ if let Some(chat) = &chat {
+ chat.handle(id, &tx, &msg, (shared.clock)());
+ }
+ }
+ _ => {} // unknown types are ignored
+ }
+ }
+ shared.hub.unsubscribe(id);
+ if let Some(chat) = &chat {
+ chat.cancel_conn(id);
+ }
+}
+
+/// `[["a"], ["b", "c"]]` as lists of strings, at most MAX_QUESTIONS lists of at most MAX_OPTIONS labels.
+fn parse_picks(v: &serde_json::Value) -> Option<Vec<Vec<String>>> {
+ let outer = v.as_array()?;
+ if outer.is_empty() || outer.len() > super::hub::MAX_QUESTIONS {
+ return None;
+ }
+ outer
+ .iter()
+ .map(|inner| {
+ let list = inner.as_array()?;
+ if list.len() > super::hub::MAX_OPTIONS {
+ return None;
+ }
+ list.iter().map(|x| x.as_str().map(str::to_string)).collect::<Option<Vec<String>>>()
+ })
+ .collect()
+}
+
+enum Next {
+ Line(Vec<u8>),
+ TooLong,
+ Closed,
+}
+
+/// Newline-delimited lines, none longer than MAX_LINE.
+struct LineReader<R> {
+ inner: BufReader<R>,
+}
+
+impl<R: AsyncRead + Unpin> LineReader<R> {
+ fn new(read: R) -> Self {
+ Self { inner: BufReader::new(read) }
+ }
+
+ async fn next(&mut self) -> Next {
+ loop {
+ let mut buf = Vec::new();
+ // Never reads more than one byte past the limit, however much is sent.
+ let mut limited = (&mut self.inner).take(MAX_LINE as u64 + 2);
+ match limited.read_until(b'\n', &mut buf).await {
+ Ok(0) | Err(_) => return Next::Closed,
+ Ok(_) => {}
+ }
+ if buf.last() != Some(&b'\n') {
+ // No newline within the limit: too long (or the phone vanished mid-line).
+ return if buf.len() > MAX_LINE { Next::TooLong } else { Next::Closed };
+ }
+ buf.pop();
+ if buf.last() == Some(&b'\r') {
+ buf.pop();
+ }
+ if buf.len() > MAX_LINE {
+ return Next::TooLong;
+ }
+ if !buf.is_empty() {
+ return Next::Line(buf);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_the_local_network_may_connect() {
+ for ok in ["192.168.1.20", "10.0.0.5", "172.16.3.4", "172.31.255.255", "127.0.0.1", "169.254.7.7", "::1", "fd12:3456::1", "fe80::1", "::ffff:192.168.0.9"] {
+ assert!(is_local(ok.parse().unwrap()), "{ok}");
+ }
+ for no in ["8.8.8.8", "172.32.0.1", "100.64.0.1", "2001:db8::1", "::ffff:8.8.8.8", "0.0.0.0"] {
+ assert!(!is_local(no.parse().unwrap()), "{no}");
+ }
+ }
+}
diff --git a/windows/src-tauri/src/phone_link/tests.rs b/windows/src-tauri/src/phone_link/tests.rs
new file mode 100644
index 00000000..53036aed
--- /dev/null
+++ b/windows/src-tauri/src/phone_link/tests.rs
@@ -0,0 +1,1821 @@
+// The phone link end to end: a real TLS server on loopback and a client that pins
+// the certificate the way the Android app does. The Kotlin client is tried
+// against this same server in android/.../RustDesktopInteropTest.kt.
+
+use std::future::Future;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use ring::digest;
+use serde_json::{json, Value};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
+use tokio::net::TcpStream;
+use tokio_rustls::client::TlsStream;
+use tokio_rustls::rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
+use tokio_rustls::rustls::crypto::ring as provider;
+use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName, UnixTime};
+use tokio_rustls::rustls::{ClientConfig, DigitallySignedStruct, Error, SignatureScheme};
+use tokio_rustls::TlsConnector;
+
+use super::hub::{hex, ApprovalIn, Host, Hub, SessionIn};
+use super::pairing::{self, tests::MemStore};
+use super::server::{self, MAX_LINE};
+
+const TOKEN: &str = "test-token-0123456789abcdef";
+
+fn block_on<F: Future>(f: F) -> F::Output {
+ tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
+}
+
+#[derive(Default)]
+struct Recorder(Mutex<Vec<(String, bool)>>, Mutex<Vec<(String, Value)>>, Mutex<Vec<(u64, String, u64)>>);
+impl Host for Recorder {
+ fn get_diff(&self, sub_id: u64, pill_id: &str, file_id: u64) {
+ self.2.lock().unwrap().push((sub_id, pill_id.to_string(), file_id));
+ }
+ fn decide(&self, request_id: &str, allow: bool) {
+ self.0.lock().unwrap().push((request_id.to_string(), allow));
+ }
+ fn answer(&self, request_id: &str, answers: &serde_json::Map<String, Value>) {
+ self.1.lock().unwrap().push((request_id.to_string(), Value::Object(answers.clone())));
+ }
+}
+
+struct Rig {
+ port: u16,
+ fingerprint: String,
+ hub: Arc<Hub>,
+ host: Arc<Recorder>,
+ shared: Arc<server::Shared>,
+ handle: Option<server::Handle>,
+}
+
+impl Rig {
+ async fn start() -> Rig {
+ Rig::start_with(None).await
+ }
+
+ async fn start_with(chat: Option<Arc<super::chat::ChatLink>>) -> Rig {
+ Rig::start_full(chat, Arc::new(server::NoFeatures)).await
+ }
+
+ async fn start_full(chat: Option<Arc<super::chat::ChatLink>>, features: Arc<dyn server::Features>) -> Rig {
+ let identity = pairing::load_or_create_identity(&MemStore::default()).unwrap();
+ let host = Arc::new(Recorder::default());
+ let hub = Hub::new(host.clone());
+ let shared = server::Shared::with_features(hub.clone(), TOKEN.to_string(), "Test PC".to_string(), chat, features);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let handle = server::serve(listener, server::tls_acceptor(&identity).unwrap(), shared.clone());
+ Rig { port, fingerprint: identity.fingerprint, hub, host, shared, handle: Some(handle) }
+ }
+
+ fn approval(&self, request: &str, command: &str, age_ms: u64) {
+ let now = server::now_ms() - age_ms;
+ self.hub.publish(
+ vec![],
+ Some(ApprovalIn {
+ request_id: request.into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ tool: "Bash".into(),
+ command: command.into(),
+ }),
+ now,
+ );
+ }
+
+ fn decisions(&self) -> Vec<(String, bool)> {
+ self.host.0.lock().unwrap().clone()
+ }
+}
+
+impl Drop for Rig {
+ fn drop(&mut self) {
+ if let Some(h) = self.handle.take() {
+ h.stop();
+ }
+ }
+}
+
+/// Accepts exactly one certificate, by its SHA-256 — the Android client's PinnedTrustManager.
+#[derive(Debug)]
+struct Pin(String);
+
+impl ServerCertVerifier for Pin {
+ fn verify_server_cert(
+ &self,
+ end_entity: &CertificateDer<'_>,
+ _intermediates: &[CertificateDer<'_>],
+ _name: &ServerName<'_>,
+ _ocsp: &[u8],
+ _now: UnixTime,
+ ) -> Result<ServerCertVerified, Error> {
+ if hex(digest::digest(&digest::SHA256, end_entity).as_ref()) == self.0 {
+ Ok(ServerCertVerified::assertion())
+ } else {
+ Err(Error::General("certificate does not match the pairing".into()))
+ }
+ }
+ fn verify_tls12_signature(&self, m: &[u8], c: &CertificateDer<'_>, d: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, Error> {
+ tokio_rustls::rustls::crypto::verify_tls12_signature(m, c, d, &provider::default_provider().signature_verification_algorithms)
+ }
+ fn verify_tls13_signature(&self, m: &[u8], c: &CertificateDer<'_>, d: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, Error> {
+ tokio_rustls::rustls::crypto::verify_tls13_signature(m, c, d, &provider::default_provider().signature_verification_algorithms)
+ }
+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+ provider::default_provider().signature_verification_algorithms.supported_schemes()
+ }
+}
+
+struct Client {
+ r: BufReader<ReadHalf<TlsStream<TcpStream>>>,
+ w: WriteHalf<TlsStream<TcpStream>>,
+}
+
+impl Client {
+ async fn connect(port: u16, pin: &str) -> Result<Client, String> {
+ Client::connect_from("127.0.0.1", port, pin).await
+ }
+
+ /// From a chosen loopback address (127.0.0.2 and so on), to stand in for another device on the network.
+ async fn connect_from(source: &str, port: u16, pin: &str) -> Result<Client, String> {
+ let config = ClientConfig::builder_with_provider(Arc::new(provider::default_provider()))
+ .with_safe_default_protocol_versions()
+ .unwrap()
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(Pin(pin.to_string())))
+ .with_no_client_auth();
+ let socket = tokio::net::TcpSocket::new_v4().map_err(|e| e.to_string())?;
+ socket.bind(format!("{source}:0").parse().unwrap()).map_err(|e| e.to_string())?;
+ let tcp = socket.connect(std::net::SocketAddr::from(([127, 0, 0, 1], port))).await.map_err(|e| e.to_string())?;
+ let tls = TlsConnector::from(Arc::new(config))
+ .connect(ServerName::try_from("coucou").unwrap(), tcp)
+ .await
+ .map_err(|e| e.to_string())?;
+ let (r, w) = tokio::io::split(tls);
+ Ok(Client { r: BufReader::new(r), w })
+ }
+
+ async fn paired(rig: &Rig) -> Client {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send(json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" })).await;
+ assert_eq!(c.recv().await.unwrap()["type"], "welcome");
+ c
+ }
+
+ async fn send(&mut self, v: Value) {
+ self.send_raw(v.to_string().as_bytes()).await;
+ }
+
+ async fn send_raw(&mut self, bytes: &[u8]) {
+ self.send_unterminated(bytes).await;
+ let _ = self.w.write_all(b"\n").await;
+ let _ = self.w.flush().await;
+ }
+
+ /// Bytes with no end of line, as a misbehaving peer would send them.
+ async fn send_unterminated(&mut self, bytes: &[u8]) {
+ let _ = self.w.write_all(bytes).await;
+ let _ = self.w.flush().await;
+ }
+
+ /// The next message, or None if the server closed (or said nothing for 3 s).
+ async fn recv(&mut self) -> Option<Value> {
+ let mut line = String::new();
+ match tokio::time::timeout(Duration::from_secs(3), self.r.read_line(&mut line)).await {
+ Ok(Ok(n)) if n > 0 => Some(serde_json::from_str(&line).unwrap()),
+ _ => None,
+ }
+ }
+
+ /// The next message of this type, skipping others.
+ async fn expect(&mut self, kind: &str) -> Value {
+ for _ in 0..10 {
+ let m = self.recv().await.unwrap_or_else(|| panic!("closed while waiting for {kind}"));
+ if m["type"] == kind {
+ return m;
+ }
+ }
+ panic!("no {kind} message");
+ }
+
+ /// True once the server has really closed this connection (an end of stream,
+ /// not just a quiet one).
+ async fn closed(&mut self) -> bool {
+ loop {
+ let mut line = String::new();
+ match tokio::time::timeout(Duration::from_secs(3), self.r.read_line(&mut line)).await {
+ Ok(Ok(0)) | Ok(Err(_)) => return true,
+ Ok(Ok(_)) => continue, // a last word before closing
+ Err(_) => return false,
+ }
+ }
+ }
+}
+
+#[test]
+fn a_paired_phone_gets_sessions_and_answers_the_request() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.hub.publish(
+ vec![SessionIn { pill_id: "integration_claude".into(), agent: "Claude Code".into(), state: "working".into(), status_text: "Editing".into(), step_index: 2, step_count: 6, ..Default::default() }],
+ None,
+ server::now_ms(),
+ );
+ let mut c = Client::paired(&rig).await;
+ let sessions = c.expect("sessions").await;
+ assert_eq!(sessions["sessions"][0]["agent"], "Claude Code");
+ assert_eq!(sessions["sessions"][0]["state"], "working");
+
+ rig.approval("req-1", "npm run build", 0);
+ let approval = c.expect("approval").await;
+ assert_eq!(approval["pillId"], "integration_claude");
+ assert_eq!(approval["tool"], "Bash");
+ assert_eq!(approval["command"], "npm run build");
+ let fp = approval["fingerprint"].as_str().unwrap().to_string();
+ assert_eq!(fp, super::hub::fingerprint("integration_claude", "s1", "Bash", "npm run build", "req-1"));
+
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ let resolved = c.expect("approvalResolved").await;
+ assert_eq!(resolved["fingerprint"], fp);
+ assert_eq!(rig.decisions(), vec![("req-1".to_string(), true)]);
+
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ c.send(json!({ "type": "bye" })).await;
+ assert!(c.closed().await);
+ });
+}
+
+#[test]
+fn a_wrong_token_is_refused_and_gets_nothing() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.approval("req-1", "rm -rf /", 0);
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send(json!({ "type": "hello", "v": 1, "token": "x".repeat(TOKEN.len()), "device": "Intruder" })).await;
+ let first = c.recv().await.unwrap();
+ assert_eq!(first["type"], "error");
+ assert_eq!(first["code"], "auth");
+ assert!(c.closed().await);
+ assert_eq!(rig.hub.clients(), 0);
+ assert!(rig.decisions().is_empty());
+ });
+}
+
+#[test]
+fn a_token_of_another_length_or_a_missing_one_is_refused_too() {
+ block_on(async {
+ let rig = Rig::start().await;
+ for hello in [
+ json!({ "type": "hello", "v": 1, "token": "short", "device": "x" }),
+ json!({ "type": "hello", "v": 1, "device": "x" }),
+ json!({ "type": "hello", "v": 1, "token": 12345, "device": "x" }),
+ json!({ "type": "hello", "v": 1, "token": format!("{TOKEN}extra"), "device": "x" }),
+ // Right token, other protocol version: the phone would refuse the desktop anyway.
+ json!({ "type": "hello", "v": 2, "token": TOKEN, "device": "x" }),
+ json!({ "type": "hello", "token": TOKEN, "device": "x" }),
+ ] {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send(hello.clone()).await;
+ assert_eq!(c.recv().await.unwrap()["code"], "auth", "{hello}");
+ }
+ assert_eq!(rig.hub.clients(), 0);
+ });
+}
+
+#[test]
+fn a_phone_that_does_not_say_hello_first_gets_nowhere() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.approval("req-1", "ls", 0);
+ let fp = super::hub::fingerprint("integration_claude", "s1", "Bash", "ls", "req-1");
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ assert!(c.closed().await);
+ assert!(rig.decisions().is_empty(), "a decision before hello must never be applied");
+
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send_raw(b"this is not json").await;
+ assert!(c.closed().await);
+ });
+}
+
+#[test]
+fn a_decision_for_another_request_changes_nothing() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.approval("req-2", "npm test", 0);
+ let mut c = Client::paired(&rig).await;
+ let real = c.expect("approval").await["fingerprint"].as_str().unwrap().to_string();
+
+ // The same command, but the fingerprint of an earlier request.
+ let stale = super::hub::fingerprint("integration_claude", "s1", "Bash", "npm test", "req-1");
+ for odd in [stale.as_str(), "", "not-a-fingerprint", &real.to_uppercase()] {
+ c.send(json!({ "type": "decision", "fingerprint": odd, "decision": "allow" })).await;
+ }
+ c.send(json!({ "type": "decision", "fingerprint": real, "decision": "always" })).await;
+ c.send(json!({ "type": "decision", "fingerprint": real })).await;
+ c.send(json!({ "type": "decision", "decision": "allow" })).await;
+ // A round trip proves the server has read all of the above.
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert!(rig.decisions().is_empty());
+
+ // And the real request is still waiting for the real answer.
+ c.send(json!({ "type": "decision", "fingerprint": real, "decision": "deny" })).await;
+ c.expect("approvalResolved").await;
+ assert_eq!(rig.decisions(), vec![("req-2".to_string(), false)]);
+ });
+}
+
+#[test]
+fn a_decision_that_comes_too_late_is_ignored() {
+ block_on(async {
+ let rig = Rig::start().await;
+ // The request has been waiting for two minutes: the desktop dismissed it long ago.
+ rig.approval("req-1", "npm test", 120_000);
+ let mut c = Client::paired(&rig).await;
+ // It is not even offered to a phone that connects now.
+ c.send(json!({ "type": "ping" })).await;
+ let mut offered = false;
+ loop {
+ let m = c.recv().await.unwrap();
+ offered |= m["type"] == "approval";
+ if m["type"] == "pong" {
+ break;
+ }
+ }
+ assert!(!offered, "an expired request must not be offered");
+
+ // A phone that still holds it from before answers anyway.
+ let fp = super::hub::fingerprint("integration_claude", "s1", "Bash", "npm test", "req-1");
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert!(rig.decisions().is_empty());
+ });
+}
+
+#[test]
+fn a_decision_after_the_desktop_answered_is_ignored() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.approval("req-1", "npm test", 0);
+ let mut c = Client::paired(&rig).await;
+ let fp = c.expect("approval").await["fingerprint"].as_str().unwrap().to_string();
+
+ // Allowed at the desk: the island publishes no pending request any more.
+ rig.hub.publish(vec![], None, server::now_ms());
+ assert_eq!(c.expect("approvalResolved").await["fingerprint"], fp);
+
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert!(rig.decisions().is_empty());
+ });
+}
+
+#[test]
+fn a_line_over_64_kib_closes_the_connection() {
+ block_on(async {
+ let rig = Rig::start().await;
+
+ // Before hello.
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ c.send_raw(&vec![b'a'; MAX_LINE + 10]).await;
+ assert!(c.closed().await);
+
+ // After hello.
+ let mut c = Client::paired(&rig).await;
+ c.send_raw(&vec![b'a'; MAX_LINE + 10]).await;
+ assert!(c.closed().await);
+
+ // A flood with no newline at all is cut at the limit, not buffered for ever.
+ let mut c = Client::paired(&rig).await;
+ for _ in 0..8 {
+ c.send_unterminated(&vec![b'b'; 32 * 1024]).await;
+ }
+ assert!(c.closed().await);
+ assert_eq!(rig.hub.clients(), 0);
+
+ // The server is fine afterwards.
+ let mut c = Client::paired(&rig).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ });
+}
+
+#[test]
+fn a_line_of_exactly_64_kib_is_accepted() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let mut c = Client::paired(&rig).await;
+ let head = r#"{"type":"ping","pad":""#;
+ let tail = r#""}"#;
+ let pad = "p".repeat(MAX_LINE - head.len() - tail.len());
+ let line = format!("{head}{pad}{tail}");
+ assert_eq!(line.len(), MAX_LINE);
+ c.send_raw(line.as_bytes()).await;
+ c.expect("pong").await;
+ });
+}
+
+#[test]
+fn a_phone_with_another_certificate_in_mind_does_not_connect() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let err = Client::connect(rig.port, &"0".repeat(64)).await.err().expect("the pin must fail");
+ assert!(err.contains("does not match"), "{err}");
+ assert_eq!(rig.hub.clients(), 0);
+ });
+}
+
+#[test]
+fn plain_text_is_not_spoken_here() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let mut tcp = TcpStream::connect(("127.0.0.1", rig.port)).await.unwrap();
+ tcp.write_all(b"{\"type\":\"hello\",\"v\":1,\"token\":\"test-token-0123456789abcdef\"}\n").await.unwrap();
+ let mut buf = Vec::new();
+ let mut r = BufReader::new(tcp);
+ let _ = tokio::time::timeout(Duration::from_secs(3), r.read_until(b'\n', &mut buf)).await;
+ assert!(!String::from_utf8_lossy(&buf).contains("welcome"));
+ assert_eq!(rig.hub.clients(), 0);
+ });
+}
+
+#[test]
+fn pairing_again_locks_the_old_phone_out() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let mut old = Client::paired(&rig).await;
+
+ // What phone_link_new_pairing does.
+ *rig.shared.token.lock().unwrap() = "a-brand-new-token-0123456789".to_string();
+ rig.hub.kick_all("auth", "unpaired");
+ let word = old.expect("error").await;
+ assert_eq!(word["code"], "auth");
+ assert!(old.closed().await);
+
+ let mut again = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ again.send(json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "old" })).await;
+ assert_eq!(again.recv().await.unwrap()["code"], "auth");
+ let mut fresh = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ fresh.send(json!({ "type": "hello", "v": 1, "token": "a-brand-new-token-0123456789", "device": "new" })).await;
+ assert_eq!(fresh.recv().await.unwrap()["type"], "welcome");
+ });
+}
+
+#[test]
+fn turning_it_off_closes_the_phones_and_stops_listening() {
+ block_on(async {
+ let mut rig = Rig::start().await;
+ let mut c = Client::paired(&rig).await;
+ let port = rig.port;
+ rig.handle.take().unwrap().stop();
+ assert!(c.closed().await);
+ // Nobody answers any more (the listener was dropped with the task).
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert!(Client::connect(port, &rig.fingerprint).await.is_err());
+ });
+}
+
+/// True when this machine lets us use 127.0.0.2 and 127.0.0.3 as other devices (Linux and Windows do; some systems do not).
+fn loopback_aliases() -> bool {
+ ["127.0.0.2", "127.0.0.3"].iter().all(|a| std::net::TcpListener::bind((*a, 0)).is_ok())
+}
+
+/// Whether a connection that was admitted answers a hello (a dropped one is closed unserved or never completes TLS).
+async fn served(c: Result<Client, String>) -> bool {
+ match c {
+ Err(_) => false,
+ Ok(mut c) => {
+ c.send(json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "probe" })).await;
+ c.recv().await.is_some()
+ }
+ }
+}
+
+#[test]
+fn the_total_number_of_connections_is_limited() {
+ block_on(async {
+ let rig = Rig::start().await;
+ // Eight phones that said a valid hello fill the pool; the ninth is dropped.
+ let mut phones = Vec::new();
+ for _ in 0..8 {
+ phones.push(Client::paired(&rig).await);
+ }
+ assert!(!served(Client::connect(rig.port, &rig.fingerprint).await).await, "the ninth connection");
+ drop(phones);
+ });
+}
+
+#[test]
+fn one_address_cannot_hold_more_than_two_silent_connections() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let a = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let b = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ // A third that never says hello is refused before it can wait.
+ assert!(!served(Client::connect(rig.port, &rig.fingerprint).await).await, "the third from one address");
+ // Closing one frees its place.
+ drop(a);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ assert!(served(Client::connect(rig.port, &rig.fingerprint).await).await);
+ drop(b);
+ });
+}
+
+#[test]
+fn a_flood_from_one_address_cannot_lock_out_the_paired_phone() {
+ if !loopback_aliases() {
+ eprintln!("skipped: this machine has no 127.0.0.2/127.0.0.3");
+ return;
+ }
+ block_on(async {
+ let rig = Rig::start().await;
+ // The phone (127.0.0.1) pairs once, so the computer knows its address.
+ drop(Client::paired(&rig).await);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ // Another device floods with silent connections: only two are kept.
+ let mut flood = Vec::new();
+ for _ in 0..10 {
+ if let Ok(c) = Client::connect_from("127.0.0.2", rig.port, &rig.fingerprint).await {
+ flood.push(c);
+ }
+ }
+ assert!(flood.len() <= 2, "the flood is capped at two, got {}", flood.len());
+ // The paired phone connects and is served, again and again, while the flood goes on.
+ for _ in 0..3 {
+ let mut phone = Client::paired(&rig).await;
+ phone.send(json!({ "type": "ping" })).await;
+ phone.expect("pong").await;
+ }
+ drop(flood);
+ });
+}
+
+#[test]
+fn a_flood_from_several_addresses_still_leaves_room_for_the_known_phone() {
+ if !loopback_aliases() {
+ eprintln!("skipped: this machine has no 127.0.0.2/127.0.0.3");
+ return;
+ }
+ block_on(async {
+ let rig = Rig::start().await;
+ drop(Client::paired(&rig).await);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ // Two other devices fill the whole stranger pool (2 + 2).
+ let mut flood = Vec::new();
+ for source in ["127.0.0.2", "127.0.0.3"] {
+ for _ in 0..4 {
+ if let Ok(c) = Client::connect_from(source, rig.port, &rig.fingerprint).await {
+ flood.push(c);
+ }
+ }
+ }
+ assert_eq!(flood.len(), 4, "strangers share four places");
+ let mut phone = Client::paired(&rig).await;
+ phone.send(json!({ "type": "ping" })).await;
+ phone.expect("pong").await;
+ drop(flood);
+ });
+}
+
+
+// ── Chat from the phone: the rules, with a fake provider ──────────────────
+
+mod chat_tests {
+ use super::*;
+ use crate::phone_link::chat::{
+ reason, BoxFuture, ChatBackend, ChatConfig, ChatFail, ChatLink, ModelOption, DONE_TEXT_MAX, MAX_SENDS, MAX_TEXT_CHARS,
+ };
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ use tokio::sync::mpsc::UnboundedSender;
+
+ #[derive(Clone)]
+ enum Script {
+ /// Streams these parts one after the other (the answer so far each time).
+ Words(Vec<String>),
+ /// Streams `streamed`, then returns `full` (which is not an extension of it).
+ Rewrite { streamed: String, full: String },
+ Fail(ChatFail),
+ /// Never answers (a slow provider).
+ Hang,
+ }
+
+ struct Fake {
+ config: Mutex<ChatConfig>,
+ script: Mutex<Script>,
+ calls: Mutex<Vec<(String, String)>>,
+ resets: AtomicUsize,
+ dropped: Arc<AtomicBool>,
+ }
+
+ impl Fake {
+ fn new(enabled: bool) -> Arc<Fake> {
+ let models = vec![
+ ModelOption { id: "anthropic/claude-x".into(), provider: "anthropic".into(), label: "Claude X".into() },
+ ModelOption { id: "openai/gpt-y".into(), provider: "openai".into(), label: "GPT Y".into() },
+ ];
+ Arc::new(Fake {
+ config: Mutex::new(ChatConfig { enabled, allowed: models }),
+ script: Mutex::new(Script::Words(vec!["Hel".into(), "lo".into(), " world".into()])),
+ calls: Mutex::new(Vec::new()),
+ resets: AtomicUsize::new(0),
+ dropped: Arc::new(AtomicBool::new(false)),
+ })
+ }
+ fn script(&self, s: Script) {
+ *self.script.lock().unwrap() = s;
+ }
+ fn enable(&self, on: bool) {
+ self.config.lock().unwrap().enabled = on;
+ }
+ }
+
+ impl ChatBackend for Fake {
+ fn config(&self) -> ChatConfig {
+ self.config.lock().unwrap().clone()
+ }
+ fn send(&self, model_id: &str, text: String, deltas: UnboundedSender<String>) -> BoxFuture<Result<String, ChatFail>> {
+ self.calls.lock().unwrap().push((model_id.to_string(), text));
+ let script = self.script.lock().unwrap().clone();
+ let dropped = self.dropped.clone();
+ self.dropped.store(false, Ordering::SeqCst);
+ Box::pin(async move {
+ struct Mark(Arc<AtomicBool>);
+ impl Drop for Mark {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+ }
+ let _mark = Mark(dropped);
+ match script {
+ Script::Words(parts) => {
+ let mut so_far = String::new();
+ for p in parts {
+ so_far.push_str(&p);
+ let _ = deltas.send(so_far.clone());
+ tokio::task::yield_now().await;
+ }
+ Ok(so_far)
+ }
+ Script::Rewrite { streamed, full } => {
+ let _ = deltas.send(streamed);
+ tokio::task::yield_now().await;
+ Ok(full)
+ }
+ Script::Fail(f) => Err(f),
+ Script::Hang => std::future::pending().await,
+ }
+ })
+ }
+ fn reset(&self) {
+ self.resets.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ async fn rig(fake: &Arc<Fake>) -> Rig {
+ Rig::start_with(Some(ChatLink::new(fake.clone()))).await
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ fn send(id: &str, model: &str, text: &str) -> Value {
+ json!({ "type": "chatSend", "id": id, "model": model, "text": text })
+ }
+
+ /// Everything of one answer until chatDone or chatError.
+ async fn answer(c: &mut Client, id: &str) -> (String, Value) {
+ let mut text = String::new();
+ for _ in 0..200 {
+ let m = c.recv().await.expect("the connection closed or went quiet");
+ match m["type"].as_str() {
+ Some("chatDelta") if m["id"] == id => text.push_str(m["text"].as_str().unwrap()),
+ Some("chatDone") | Some("chatError") if m["id"] == id => return (text, m),
+ _ => {}
+ }
+ }
+ panic!("no end of answer");
+ }
+
+ #[test]
+ fn a_phone_that_asks_is_offered_chat_and_gets_only_the_allowed_models() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, welcome) = phone(&rig, Some(json!(["chat"]))).await;
+ assert_eq!(welcome["caps"], json!(["chat"]));
+ c.send(json!({ "type": "chatModels" })).await;
+ let m = c.expect("chatModels").await;
+ assert_eq!(m["models"][0], json!({ "id": "anthropic/claude-x", "provider": "anthropic", "label": "Claude X" }));
+ assert_eq!(m["models"].as_array().unwrap().len(), 2);
+ // only ids, providers and labels: nothing else is in the message
+ assert_eq!(m["models"][0].as_object().unwrap().len(), 3);
+ });
+ }
+
+ #[test]
+ fn an_older_phone_is_never_offered_nor_answered_anything_about_chat() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, welcome) = phone(&rig, None).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ c.send(send("a1", "anthropic/claude-x", "hi")).await;
+ c.send(json!({ "type": "chatModels" })).await;
+ c.send(json!({ "type": "ping" })).await;
+ // the first thing back is the pong: nothing was said about chat in between
+ loop {
+ let m = c.recv().await.unwrap();
+ assert!(!m["type"].as_str().unwrap().starts_with("chat"), "{m}");
+ if m["type"] == "pong" {
+ break;
+ }
+ }
+ assert!(fake.calls.lock().unwrap().is_empty());
+ });
+ }
+
+ #[test]
+ fn an_older_computer_is_the_same_as_chat_being_off_no_caps_in_welcome() {
+ block_on(async {
+ // No chat wired in at all (as before this feature): the welcome has no caps even if the phone asks.
+ let rig = Rig::start().await;
+ let (_c, welcome) = phone(&rig, Some(json!(["chat", "details"]))).await;
+ assert!(welcome.get("caps").is_none());
+ assert_eq!(welcome["v"], 1);
+ });
+ }
+
+ #[test]
+ fn with_the_switch_off_nothing_is_offered_and_a_send_is_ignored() {
+ block_on(async {
+ let fake = Fake::new(false);
+ let rig = rig(&fake).await;
+ let (mut c, welcome) = phone(&rig, Some(json!(["chat"]))).await;
+ assert!(welcome.get("caps").is_none());
+ c.send(send("a1", "anthropic/claude-x", "hi")).await;
+ c.send(json!({ "type": "ping" })).await;
+ loop {
+ let m = c.recv().await.unwrap();
+ assert!(!m["type"].as_str().unwrap().starts_with("chat"), "{m}");
+ if m["type"] == "pong" {
+ break;
+ }
+ }
+ assert!(fake.calls.lock().unwrap().is_empty());
+ });
+ }
+
+ #[test]
+ fn an_answer_arrives_in_pieces_that_add_up_and_the_model_gets_the_text() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "Say hello")).await;
+ let (text, end) = answer(&mut c, "a1").await;
+ assert_eq!(text, "Hello world");
+ assert_eq!(end["type"], "chatDone");
+ assert!(end.get("text").is_none(), "no correction needed");
+ assert_eq!(*fake.calls.lock().unwrap(), vec![("openai/gpt-y".to_string(), "Say hello".to_string())]);
+ });
+ }
+
+ #[test]
+ fn a_rewritten_answer_is_corrected_in_done() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Rewrite { streamed: "<think>hmm".into(), full: "Answer".into() });
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "q")).await;
+ let (_, end) = answer(&mut c, "a1").await;
+ assert_eq!(end["type"], "chatDone");
+ assert_eq!(end["text"], "Answer");
+ });
+ }
+
+ #[test]
+ fn a_huge_answer_is_cut_into_lines_under_64_kib() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let big = "é".repeat(60_000); // 120 KB in one go
+ fake.script(Script::Words(vec![big.clone()]));
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "q")).await;
+ let (text, end) = answer(&mut c, "a1").await;
+ assert_eq!(end["type"], "chatDone");
+ assert_eq!(text, big);
+ });
+ }
+
+ #[test]
+ fn failures_carry_a_fixed_code_and_message_only() {
+ block_on(async {
+ for (fail, code) in [
+ (ChatFail::NoKey, "no_key"),
+ (ChatFail::Unreachable, "unreachable"),
+ (ChatFail::Auth, "auth"),
+ (ChatFail::Provider, "provider"),
+ (ChatFail::Internal, "internal"),
+ ] {
+ let fake = Fake::new(true);
+ fake.script(Script::Fail(fail));
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "q")).await;
+ let (_, end) = answer(&mut c, "a1").await;
+ assert_eq!(end["type"], "chatError");
+ assert_eq!(end["reason"], code);
+ assert_eq!(end["message"], reason(code));
+ assert_eq!(end.as_object().unwrap().len(), 4, "type, id, reason, message and nothing else: {end}");
+ }
+ });
+ }
+
+ #[test]
+ fn the_text_the_model_and_the_id_are_checked() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("e1", "openai/gpt-y", &"x".repeat(MAX_TEXT_CHARS + 1))).await;
+ assert_eq!(answer(&mut c, "e1").await.1["reason"], "too_long");
+ c.send(send("e2", "openai/gpt-y", " ")).await;
+ assert_eq!(answer(&mut c, "e2").await.1["reason"], "empty");
+ c.send(send("e3", "openai/not-allowed", "hi")).await;
+ assert_eq!(answer(&mut c, "e3").await.1["reason"], "not_allowed");
+ c.send(send("e4", "", "hi")).await;
+ assert_eq!(answer(&mut c, "e4").await.1["reason"], "not_allowed");
+ // exactly the limit is fine
+ c.send(send("ok", "openai/gpt-y", &"é".repeat(MAX_TEXT_CHARS))).await;
+ assert_eq!(answer(&mut c, "ok").await.1["type"], "chatDone");
+ // an id that is empty, too long or odd is not answered at all
+ for bad in ["", &"a".repeat(65), "a b", "a\u{0}b"] {
+ c.send(send(bad, "openai/gpt-y", "hi")).await;
+ }
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert_eq!(fake.calls.lock().unwrap().len(), 1, "only the valid send reached the provider");
+ });
+ }
+
+ #[test]
+ fn only_one_answer_runs_at_a_time_and_cancel_frees_the_slot() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Hang);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "slow")).await;
+ // wait until the provider call has started
+ for _ in 0..100 {
+ if !fake.calls.lock().unwrap().is_empty() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ c.send(send("a2", "openai/gpt-y", "second")).await;
+ assert_eq!(answer(&mut c, "a2").await.1["reason"], "busy");
+ c.send(json!({ "type": "chatCancel", "id": "a1" })).await;
+ assert_eq!(answer(&mut c, "a1").await.1["reason"], "canceled");
+ assert!(wait_for(|| fake.dropped.load(Ordering::SeqCst)).await, "the provider call was dropped");
+ fake.script(Script::Words(vec!["ok".into()]));
+ c.send(send("a3", "openai/gpt-y", "third")).await;
+ assert_eq!(answer(&mut c, "a3").await.0, "ok");
+ });
+ }
+
+ #[test]
+ fn a_cancel_for_another_id_changes_nothing() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Hang);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "slow")).await;
+ c.send(json!({ "type": "chatCancel", "id": "other" })).await;
+ c.send(send("a2", "openai/gpt-y", "x")).await;
+ assert_eq!(answer(&mut c, "a2").await.1["reason"], "busy", "a1 is still running");
+ });
+ }
+
+ #[test]
+ fn the_rate_limit_stops_the_thirteenth_send() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ for i in 0..MAX_SENDS {
+ let id = format!("m{i}");
+ c.send(send(&id, "openai/gpt-y", "hi")).await;
+ assert_eq!(answer(&mut c, &id).await.1["type"], "chatDone", "send {i}");
+ }
+ c.send(send("over", "openai/gpt-y", "hi")).await;
+ assert_eq!(answer(&mut c, "over").await.1["reason"], "rate");
+ assert_eq!(fake.calls.lock().unwrap().len(), MAX_SENDS);
+ });
+ }
+
+ #[test]
+ fn leaving_stops_the_answer_and_frees_the_slot_for_the_next_phone() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Hang);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "slow")).await;
+ assert!(wait_for(|| !fake.calls.lock().unwrap().is_empty()).await);
+ c.send(json!({ "type": "bye" })).await;
+ assert!(c.closed().await);
+ assert!(wait_for(|| fake.dropped.load(Ordering::SeqCst)).await, "no answer keeps running for a phone that left");
+ fake.script(Script::Words(vec!["fine".into()]));
+ let (mut d, _) = phone(&rig, Some(json!(["chat"]))).await;
+ d.send(send("b1", "openai/gpt-y", "hi")).await;
+ assert_eq!(answer(&mut d, "b1").await.0, "fine");
+ });
+ }
+
+ #[test]
+ fn switching_chat_off_while_connected_refuses_further_sends() {
+ block_on(async {
+ let fake = Fake::new(true);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ fake.enable(false);
+ c.send(send("a1", "openai/gpt-y", "hi")).await;
+ let (_, end) = answer(&mut c, "a1").await;
+ assert_eq!(end["reason"], "off");
+ assert!(fake.calls.lock().unwrap().is_empty());
+ c.send(json!({ "type": "chatModels" })).await;
+ assert_eq!(c.expect("chatModels").await["models"], json!([]));
+ });
+ }
+
+ #[test]
+ fn turning_the_link_off_cancels_the_answer_and_forgets_the_conversation() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Hang);
+ let mut rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "slow")).await;
+ assert!(wait_for(|| !fake.calls.lock().unwrap().is_empty()).await);
+ rig.handle.take().unwrap().stop();
+ assert!(wait_for(|| fake.dropped.load(Ordering::SeqCst)).await);
+ assert_eq!(fake.resets.load(Ordering::SeqCst), 1);
+ });
+ }
+
+ #[test]
+ fn new_chat_forgets_the_computers_side_and_stops_a_running_answer() {
+ block_on(async {
+ let fake = Fake::new(true);
+ fake.script(Script::Hang);
+ let rig = rig(&fake).await;
+ let (mut c, _) = phone(&rig, Some(json!(["chat"]))).await;
+ c.send(send("a1", "openai/gpt-y", "slow")).await;
+ assert!(wait_for(|| !fake.calls.lock().unwrap().is_empty()).await);
+ c.send(json!({ "type": "chatReset" })).await;
+ assert_eq!(answer(&mut c, "a1").await.1["reason"], "canceled");
+ assert_eq!(fake.resets.load(Ordering::SeqCst), 1);
+ });
+ }
+
+ #[test]
+ fn nothing_that_leaves_the_computer_can_contain_a_key_or_a_provider_message() {
+ block_on(async {
+ // The backend has no way to hand text to the link besides the answer itself, so
+ // a failure cannot carry any; this pins the messages that exist.
+ for code in ["off", "not_allowed", "busy", "rate", "too_long", "empty", "no_key", "unreachable", "auth", "provider", "canceled", "internal"] {
+ let m = reason(code);
+ assert!(!m.contains("sk-") && !m.to_lowercase().contains("bearer") && !m.contains("key:"), "{m}");
+ }
+ assert!(DONE_TEXT_MAX < 64 * 1024);
+ });
+ }
+
+ async fn wait_for(cond: impl Fn() -> bool) -> bool {
+ for _ in 0..200 {
+ if cond() {
+ return true;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ false
+ }
+}
+
+
+// ── Session details (cap `details`) end to end ───────────────────────────────────────────────
+
+mod details_tests {
+ use super::*;
+ use crate::phone_link::server::Features;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct Switch(AtomicBool);
+ impl Features for Switch {
+ fn details(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+ }
+
+ fn rich() -> SessionIn {
+ SessionIn {
+ pill_id: "integration_claude".into(),
+ agent: "Claude Code".into(),
+ state: "finished".into(),
+ status_text: "Done".into(),
+ step_index: 2,
+ step_count: 3,
+ steps: vec!["Read · a.rs".into(), "Edit · a.rs".into()],
+ final_line: Some("Fixed the bug".into()),
+ project: Some("/home/me/secret-folder/coucou".into()),
+ color: Some("#2DD4BF".into()),
+ ..Default::default()
+ }
+ }
+
+ async fn rig(on: bool) -> Rig {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(on)))).await;
+ rig.hub.publish(vec![rich()], None, server::now_ms());
+ rig
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ let sessions = c.expect("sessions").await;
+ (c, welcome, sessions)
+ }
+
+ #[test]
+ fn a_phone_that_asks_gets_the_details_when_the_switch_is_on() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (_c, welcome, sessions) = phone(&rig, Some(json!(["details"]))).await;
+ assert_eq!(welcome["caps"], json!(["details"]));
+ let s = &sessions["sessions"][0];
+ assert_eq!(s["steps"], json!(["Read · a.rs", "Edit · a.rs"]));
+ assert_eq!(s["finalLine"], "Fixed the bug");
+ assert_eq!(s["project"], "coucou", "the folder name, never the path");
+ assert_eq!(s["color"], "#2DD4BF");
+ assert!(!sessions.to_string().contains("secret-folder"));
+ });
+ }
+
+ #[test]
+ fn an_older_phone_gets_the_v1_sessions_and_no_caps() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (_c, welcome, sessions) = phone(&rig, None).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ let s = sessions["sessions"][0].as_object().unwrap();
+ let mut keys: Vec<&str> = s.keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ assert_eq!(keys, ["agent", "pillId", "state", "statusText", "stepCount", "stepIndex", "updatedAt"]);
+ assert!(!sessions.to_string().contains("coucou") && !sessions.to_string().contains("Fixed the bug"));
+ });
+ }
+
+ #[test]
+ fn with_the_switch_off_nothing_extra_is_offered_even_to_a_phone_that_asks() {
+ block_on(async {
+ let rig = rig(false).await;
+ let (_c, welcome, sessions) = phone(&rig, Some(json!(["details", "chat"]))).await;
+ assert!(welcome.get("caps").is_none());
+ assert!(sessions["sessions"][0].get("steps").is_none());
+ assert!(sessions["sessions"][0].get("project").is_none());
+ });
+ }
+
+ #[test]
+ fn a_phone_gets_a_live_update_with_details_and_another_phone_without() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut with, _, _) = phone(&rig, Some(json!(["details"]))).await;
+ let (mut without, _, _) = phone(&rig, None).await;
+ let mut next = rich();
+ next.final_line = Some("A second line".into());
+ rig.hub.publish(vec![next], None, server::now_ms());
+ let a = with.expect("sessions").await;
+ let b = without.expect("sessions").await;
+ assert_eq!(a["sessions"][0]["finalLine"], "A second line");
+ assert!(b["sessions"][0].get("finalLine").is_none());
+ });
+ }
+
+ #[test]
+ fn a_full_load_of_details_still_arrives_under_the_line_limit() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let sessions: Vec<SessionIn> = (0..16)
+ .map(|i| SessionIn { pill_id: format!("agent_{i}"), steps: (0..20).map(|n| format!("{n} {}", "x".repeat(250))).collect(), ..rich() })
+ .collect();
+ rig.hub.publish(sessions, None, server::now_ms());
+ let (_c, _, line) = phone(&rig, Some(json!(["details"]))).await;
+ assert_eq!(line["sessions"].as_array().unwrap().len(), 16);
+ });
+ }
+}
+
+
+// ── Answering questions (cap `answers`) end to end ───────────────────────────────────────────
+
+mod answers_tests {
+ use super::*;
+ use crate::phone_link::hub::{OptionIn, QuestionIn, QuestionItemIn};
+ use crate::phone_link::server::Features;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct Switch(AtomicBool);
+ impl Features for Switch {
+ fn details(&self) -> bool {
+ false
+ }
+ fn answers(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+ }
+
+ fn opt(l: &str) -> OptionIn {
+ OptionIn { label: l.into(), description: format!("about {l}") }
+ }
+
+ fn question(request: &str) -> QuestionIn {
+ QuestionIn {
+ request_id: request.into(),
+ session_id: "s1".into(),
+ pill_id: "integration_claude".into(),
+ questions: vec![
+ QuestionItemIn { question: "Which engine?".into(), options: vec![opt("Postgres"), opt("Meilisearch")], multi_select: false },
+ QuestionItemIn { question: "Which extras?".into(), options: vec![opt("Typos"), opt("Facets"), opt("Synonyms")], multi_select: true },
+ ],
+ }
+ }
+
+ async fn rig(on: bool) -> Rig {
+ Rig::start_full(None, Arc::new(Switch(AtomicBool::new(on)))).await
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ /// Everything the phone is sent up to the answer to a ping: proves what it was and was not told.
+ async fn types_until_pong(c: &mut Client) -> Vec<String> {
+ c.send(json!({ "type": "ping" })).await;
+ let mut seen = Vec::new();
+ for _ in 0..10 {
+ let m = c.recv().await.expect("closed");
+ let t = m["type"].as_str().unwrap_or("").to_string();
+ if t == "pong" {
+ return seen;
+ }
+ seen.push(t);
+ }
+ panic!("no pong");
+ }
+
+ fn answers_of(rig: &Rig) -> Vec<(String, Value)> {
+ rig.host.1.lock().unwrap().clone()
+ }
+
+ #[test]
+ fn a_phone_that_asks_is_offered_answers_only_while_the_switch_is_on() {
+ block_on(async {
+ let on = rig(true).await;
+ let (_c, welcome) = phone(&on, Some(json!(["answers"]))).await;
+ assert_eq!(welcome["caps"], json!(["answers"]));
+ let off = rig(false).await;
+ let (_c, welcome) = phone(&off, Some(json!(["answers"]))).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ });
+ }
+
+ #[test]
+ fn the_question_reaches_a_phone_with_the_capability_and_no_other() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut with, _) = phone(&rig, Some(json!(["answers"]))).await;
+ let (mut old, _) = phone(&rig, None).await;
+ rig.hub.publish_question(Some(question("r1")), server::now_ms());
+ let q = with.expect("question").await;
+ assert_eq!(q["questions"][0]["question"], "Which engine?");
+ assert_eq!(q["questions"][1]["multiSelect"], true);
+ assert_eq!(q["questions"][0]["options"][1]["label"], "Meilisearch");
+ assert!(q["fingerprint"].as_str().unwrap().len() == 64);
+ assert!(q.get("requestId").is_none() && !q.to_string().contains("r1"), "the island's request id stays on the computer");
+ // the older phone is told nothing, not even that something was resolved
+ rig.hub.publish_question(None, server::now_ms());
+ assert_eq!(with.expect("approvalResolved").await["fingerprint"], q["fingerprint"]);
+ let told = types_until_pong(&mut old).await;
+ assert!(!told.iter().any(|t| t == "question" || t == "approvalResolved"), "{told:?}");
+ });
+ }
+
+ #[test]
+ fn a_phone_that_connects_late_still_gets_the_question_that_waits() {
+ block_on(async {
+ let rig = rig(true).await;
+ rig.hub.publish_question(Some(question("r1")), server::now_ms());
+ let (mut c, _) = phone(&rig, Some(json!(["answers"]))).await;
+ assert_eq!(c.expect("question").await["questions"].as_array().unwrap().len(), 2);
+ });
+ }
+
+ #[test]
+ fn a_valid_answer_goes_back_to_the_agent_in_the_shape_of_the_island() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut c, _) = phone(&rig, Some(json!(["answers"]))).await;
+ rig.hub.publish_question(Some(question("r1")), server::now_ms());
+ let q = c.expect("question").await;
+ c.send(json!({ "type": "answer", "fingerprint": q["fingerprint"], "picks": [["Meilisearch"], ["Typos", "Synonyms"]] })).await;
+ c.expect("approvalResolved").await;
+ let got = answers_of(&rig);
+ assert_eq!(got.len(), 1);
+ assert_eq!(got[0].0, "r1");
+ assert_eq!(got[0].1, json!({ "Which engine?": "Meilisearch", "Which extras?": ["Typos", "Synonyms"] }));
+ // once only
+ c.send(json!({ "type": "answer", "fingerprint": q["fingerprint"], "picks": [["Postgres"], ["Facets"]] })).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert_eq!(answers_of(&rig).len(), 1);
+ });
+ }
+
+ #[test]
+ fn a_wrong_answer_changes_nothing_and_the_question_stays_open() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut c, _) = phone(&rig, Some(json!(["answers"]))).await;
+ rig.hub.publish_question(Some(question("r1")), server::now_ms());
+ let fp = c.expect("question").await["fingerprint"].clone();
+ let bad = [
+ json!([["Postgres"]]), // one pick too few
+ json!([["Mongo"], ["Typos"]]), // not an option
+ json!([["postgres"], ["Typos"]]), // not the exact label
+ json!([["Postgres", "Meilisearch"], ["Typos"]]), // two for a single choice
+ json!([["Postgres"], []]), // nothing for a multiple choice
+ json!([["Postgres"], ["Typos", "Typos"]]), // the same twice
+ json!([["Postgres"], "Typos"]), // wrong shape
+ json!("Postgres"),
+ json!([[1], [2]]),
+ ];
+ for picks in bad {
+ c.send(json!({ "type": "answer", "fingerprint": fp, "picks": picks })).await;
+ }
+ c.send(json!({ "type": "answer", "fingerprint": "0".repeat(64), "picks": [["Postgres"], ["Typos"]] })).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await;
+ assert!(answers_of(&rig).is_empty());
+ // and the right one still works afterwards
+ c.send(json!({ "type": "answer", "fingerprint": fp, "picks": [["Postgres"], ["Facets"]] })).await;
+ c.expect("approvalResolved").await;
+ assert_eq!(answers_of(&rig).len(), 1);
+ });
+ }
+
+ #[test]
+ fn a_phone_without_the_capability_cannot_answer_even_with_the_right_fingerprint() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut with, _) = phone(&rig, Some(json!(["answers"]))).await;
+ let (mut old, _) = phone(&rig, None).await;
+ rig.hub.publish_question(Some(question("r1")), server::now_ms());
+ let fp = with.expect("question").await["fingerprint"].clone();
+ old.send(json!({ "type": "answer", "fingerprint": fp, "picks": [["Postgres"], ["Typos"]] })).await;
+ old.send(json!({ "type": "ping" })).await;
+ old.expect("pong").await;
+ assert!(answers_of(&rig).is_empty());
+ });
+ }
+
+ #[test]
+ fn a_question_that_does_not_fit_the_limits_stays_on_the_island() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut c, _) = phone(&rig, Some(json!(["answers"]))).await;
+ let mut long = question("r1");
+ long.questions[0].options[0].label = "x".repeat(200);
+ rig.hub.publish_question(Some(long), server::now_ms());
+ let mut twins = question("r2");
+ twins.questions[0].options = vec![opt("Same"), opt("Same")];
+ rig.hub.publish_question(Some(twins), server::now_ms());
+ let told = types_until_pong(&mut c).await;
+ assert!(!told.iter().any(|t| t == "question"), "nothing was offered: {told:?}");
+ });
+ }
+
+ #[test]
+ fn a_permission_request_still_reaches_every_phone_as_before() {
+ block_on(async {
+ let rig = rig(true).await;
+ let (mut with, _) = phone(&rig, Some(json!(["answers"]))).await;
+ let (mut old, _) = phone(&rig, None).await;
+ rig.approval("r9", "ls", 0);
+ assert_eq!(with.expect("approval").await["tool"], "Bash");
+ assert_eq!(old.expect("approval").await["tool"], "Bash");
+ });
+ }
+}
+
+mod prefs_tests {
+ use super::*;
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ #[test]
+ fn prefs_is_offered_to_a_phone_that_asks_and_the_outfit_follows() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.hub.publish_outfit("witchHat");
+ let (mut c, welcome) = phone(&rig, Some(json!(["prefs"]))).await;
+ assert_eq!(welcome["caps"], json!(["prefs"]));
+ assert_eq!(c.expect("sessions").await["type"], "sessions");
+ let prefs = c.expect("prefs").await;
+ assert_eq!(prefs["outfit"], "witchHat");
+ rig.hub.publish_outfit("auto");
+ assert_eq!(c.expect("prefs").await["outfit"], "auto");
+ });
+ }
+
+ #[test]
+ fn an_older_phone_is_offered_nothing_and_hears_nothing() {
+ block_on(async {
+ let rig = Rig::start().await;
+ rig.hub.publish_outfit("bow");
+ let (mut c, welcome) = phone(&rig, None).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ rig.hub.publish_outfit("scarf");
+ c.send(json!({ "type": "ping" })).await;
+ let mut seen = Vec::new();
+ loop {
+ let m = c.recv().await.expect("closed");
+ let t = m["type"].as_str().unwrap_or("").to_string();
+ if t == "pong" {
+ break;
+ }
+ seen.push(t);
+ }
+ assert_eq!(seen, vec!["sessions".to_string()]);
+ });
+ }
+}
+
+mod diffs_tests {
+ use super::*;
+ use crate::phone_link::hub::{DiffIn, FileIn, SessionIn};
+ use crate::phone_link::server::Features;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct Switch(AtomicBool);
+ impl Features for Switch {
+ fn details(&self) -> bool {
+ false
+ }
+ fn diffs(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ fn working() -> SessionIn {
+ SessionIn {
+ pill_id: "integration_claude".into(),
+ state: "working".into(),
+ files: vec![FileIn { id: 7, name: "/home/me/secret/app.ts".into(), added: 3, removed: 1, ..FileIn::default() }],
+ ..SessionIn::default()
+ }
+ }
+
+ #[test]
+ fn diffs_are_offered_only_while_the_switch_is_on_and_the_phone_asked() {
+ block_on(async {
+ let on = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (_c, welcome) = phone(&on, Some(json!(["diffs"]))).await;
+ assert_eq!(welcome["caps"], json!(["diffs"]));
+ let (_c, welcome) = phone(&on, None).await;
+ assert!(welcome.get("caps").is_none());
+ let off = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(false)))).await;
+ let (_c, welcome) = phone(&off, Some(json!(["diffs"]))).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ });
+ }
+
+ #[test]
+ fn a_phone_asks_for_a_file_and_gets_it_and_nobody_else_does() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (mut c, _) = phone(&rig, Some(json!(["diffs"]))).await;
+ let (mut other, _) = phone(&rig, Some(json!(["diffs"]))).await;
+ c.expect("sessions").await;
+ other.expect("sessions").await;
+ rig.hub.publish(vec![working()], None, server::now_ms());
+ let list = c.expect("sessions").await;
+ assert_eq!(list["sessions"][0]["files"][0]["name"], "app.ts");
+ c.send(json!({ "type": "getDiff", "pillId": "integration_claude", "fileId": 7 })).await;
+ let conn = loop {
+ if let Some(first) = rig.host.2.lock().unwrap().first().cloned() {
+ break first;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ };
+ assert_eq!((conn.1.as_str(), conn.2), ("integration_claude", 7));
+ rig.hub.send_diff(conn.0, DiffIn { pill_id: conn.1.clone(), file_id: 7, name: "app.ts".into(), added: 3, removed: 1, lines: vec![("+".into(), "let x = 1;".into())], ..DiffIn::default() });
+ let diff = c.expect("diff").await;
+ assert_eq!(diff["lines"][0], json!(["+", "let x = 1;"]));
+ // the other phone hears nothing of it
+ other.send(json!({ "type": "ping" })).await;
+ assert_eq!(other.recv().await.unwrap()["type"], "sessions");
+ assert_eq!(other.recv().await.unwrap()["type"], "pong");
+ });
+ }
+
+ #[test]
+ fn a_malformed_request_or_one_without_the_capability_never_reaches_the_island() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (mut c, _) = phone(&rig, Some(json!(["diffs"]))).await;
+ let (mut plain, _) = phone(&rig, None).await;
+ for bad in [
+ json!({ "type": "getDiff" }),
+ json!({ "type": "getDiff", "pillId": "", "fileId": 1 }),
+ json!({ "type": "getDiff", "pillId": "x", "fileId": "1" }),
+ json!({ "type": "getDiff", "pillId": "x", "fileId": -1 }),
+ json!({ "type": "getDiff", "pillId": "x".repeat(65), "fileId": 1 }),
+ ] {
+ c.send(bad).await;
+ }
+ plain.send(json!({ "type": "getDiff", "pillId": "integration_claude", "fileId": 7 })).await;
+ c.send(json!({ "type": "ping" })).await;
+ loop {
+ if c.recv().await.unwrap()["type"] == "pong" {
+ break;
+ }
+ }
+ plain.send(json!({ "type": "ping" })).await;
+ loop {
+ if plain.recv().await.unwrap()["type"] == "pong" {
+ break;
+ }
+ }
+ assert!(rig.host.2.lock().unwrap().is_empty());
+ });
+ }
+}
+
+mod usage_tests {
+ use super::*;
+ use crate::phone_link::hub::{PlanIn, UsageIn, WindowIn};
+ use crate::phone_link::server::Features;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct Switch(AtomicBool);
+ impl Features for Switch {
+ fn details(&self) -> bool {
+ false
+ }
+ fn usage(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ fn usage() -> UsageIn {
+ UsageIn { claude: Some(PlanIn { five_hour: Some(WindowIn { used_pct: 61.0, resets_at: 1_900_000_000_000 }), ..PlanIn::default() }), codex: None }
+ }
+
+ #[test]
+ fn usage_is_offered_only_while_the_switch_is_on_and_the_phone_asked() {
+ block_on(async {
+ let on = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (_c, welcome) = phone(&on, Some(json!(["usage"]))).await;
+ assert_eq!(welcome["caps"], json!(["usage"]));
+ let (_c, welcome) = phone(&on, None).await;
+ assert!(welcome.get("caps").is_none());
+ let off = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(false)))).await;
+ let (_c, welcome) = phone(&off, Some(json!(["usage"]))).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ });
+ }
+
+ #[test]
+ fn the_phone_hears_the_usage_and_its_changes() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ rig.hub.publish_usage(usage());
+ let (mut c, _) = phone(&rig, Some(json!(["usage"]))).await;
+ c.expect("sessions").await;
+ assert_eq!(c.expect("usage").await["claude"]["fiveHour"]["pct"], 61);
+ rig.hub.publish_usage(UsageIn { claude: Some(PlanIn { five_hour: Some(WindowIn { used_pct: 80.0, resets_at: 1_900_000_000_000 }), ..PlanIn::default() }), codex: None });
+ assert_eq!(c.expect("usage").await["claude"]["fiveHour"]["pct"], 80);
+ });
+ }
+}
+
+mod services_tests {
+ use super::*;
+ use crate::phone_link::hub::{ServiceIn, ServiceItemIn};
+ use crate::phone_link::server::Features;
+ use std::sync::Mutex as StdMutex;
+
+ struct Ticks(StdMutex<Vec<String>>);
+ impl Features for Ticks {
+ fn details(&self) -> bool {
+ false
+ }
+ fn services(&self) -> Vec<String> {
+ self.0.lock().unwrap().clone()
+ }
+ }
+
+ async fn phone(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ fn cards() -> Vec<ServiceIn> {
+ vec![
+ ServiceIn { id: "integration_stripe".into(), title: "Stripe".into(), headline: "12.50 EUR".into(), reason: None, items: vec![ServiceItemIn { label: "Payment".into(), detail: "+9.00".into() }] },
+ ServiceIn { id: "integration_notion".into(), title: "Notion".into(), headline: "2".into(), reason: None, items: vec![ServiceItemIn { label: "Private page".into(), detail: "1m".into() }] },
+ ]
+ }
+
+ #[test]
+ fn services_are_offered_only_when_the_phone_asked_and_something_is_ticked() {
+ block_on(async {
+ let ticked = Rig::start_full(None, Arc::new(Ticks(StdMutex::new(vec!["integration_stripe".into()])))).await;
+ let (_c, welcome) = phone(&ticked, Some(json!(["services"]))).await;
+ assert_eq!(welcome["caps"], json!(["services"]));
+ let (_c, welcome) = phone(&ticked, None).await;
+ assert!(welcome.get("caps").is_none());
+ let none = Rig::start_full(None, Arc::new(Ticks(StdMutex::new(vec![])))).await;
+ let (_c, welcome) = phone(&none, Some(json!(["services"]))).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ });
+ }
+
+ #[test]
+ fn the_phone_gets_the_ticked_services_only() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Ticks(StdMutex::new(vec!["integration_stripe".into()])))).await;
+ rig.hub.publish_services(cards());
+ let (mut c, _) = phone(&rig, Some(json!(["services"]))).await;
+ c.expect("sessions").await;
+ let m = c.expect("services").await;
+ assert_eq!(m["services"].as_array().unwrap().len(), 1);
+ assert_eq!(m["services"][0]["id"], "integration_stripe");
+ assert!(!m.to_string().contains("Private page"));
+ });
+ }
+}
+
+mod relay_cap_tests {
+ use super::*;
+ use crate::phone_link::server::Features;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct Switch(AtomicBool);
+ impl Features for Switch {
+ fn details(&self) -> bool {
+ false
+ }
+ fn relay(&self) -> bool {
+ self.0.load(Ordering::SeqCst)
+ }
+ }
+
+ async fn welcome_for(rig: &Rig, caps: Option<Value>) -> (Client, Value) {
+ let mut c = Client::connect(rig.port, &rig.fingerprint).await.unwrap();
+ let mut hello = json!({ "type": "hello", "v": 1, "token": TOKEN, "device": "Test phone" });
+ if let Some(caps) = caps {
+ hello["caps"] = caps;
+ }
+ c.send(hello).await;
+ let welcome = c.expect("welcome").await;
+ (c, welcome)
+ }
+
+ #[test]
+ fn relay_is_offered_only_while_the_switch_is_on_and_the_phone_asked() {
+ block_on(async {
+ let on = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (_c, welcome) = welcome_for(&on, Some(json!(["relay"]))).await;
+ assert_eq!(welcome["caps"], json!(["relay"]));
+ let (_c, welcome) = welcome_for(&on, None).await;
+ assert!(welcome.get("caps").is_none(), "an older phone is never offered it");
+ let off = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(false)))).await;
+ let (_c, welcome) = welcome_for(&off, Some(json!(["relay"]))).await;
+ assert!(welcome.get("caps").is_none(), "{welcome}");
+ });
+ }
+
+ #[test]
+ fn a_rotated_access_key_reaches_a_phone_that_negotiated_relay() {
+ block_on(async {
+ let rig = Rig::start_full(None, Arc::new(Switch(AtomicBool::new(true)))).await;
+ let (mut c, _) = welcome_for(&rig, Some(json!(["relay"]))).await;
+ let (mut other, _) = welcome_for(&rig, None).await;
+ let access = "D".repeat(43);
+ assert_eq!(rig.hub.send_relay_access(&access), 1);
+ let m = c.expect("relayAccess").await;
+ assert_eq!(m["access"], access);
+ other.send(json!({ "type": "ping" })).await;
+ other.expect("pong").await; // it only ever sees ordinary traffic
+ });
+ }
+}
+
+// ── The keystore's key list (secrets::INTERNAL_KEYS) ──
+
+/// Every key the phone link stores must be in the real keystore's list: the keystore refuses the others with "unknown key".
+/// MemStore accepts anything, which is how a missing key once went unnoticed.
+#[test]
+fn every_secret_the_phone_link_stores_is_in_the_keystores_key_list() {
+ for key in [
+ pairing::CERT_KEY,
+ pairing::PRIVATE_KEY,
+ pairing::TOKEN_KEY,
+ super::relay_client::ROOM_KEY,
+ super::relay_client::PAIRING_KEY,
+ super::relay_client::ACCESS_KEY,
+ ] {
+ assert!(crate::secrets::INTERNAL_KEYS.contains(&key), "{key} is not in secrets::INTERNAL_KEYS");
+ }
+ // And nothing in the list is a stray: each one is used by the phone link.
+ assert_eq!(crate::secrets::INTERNAL_KEYS.len(), 6);
+}
+
+#[test]
+fn the_whole_pairing_life_works_through_the_real_key_list() {
+ use pairing::tests::StrictStore;
+ use super::relay_client as relay;
+ let store = StrictStore::default();
+ pairing::load_or_create_identity(&store).unwrap();
+ let t1 = pairing::token(&store).unwrap();
+ let (room1, _) = relay::pairing(&store).unwrap();
+ relay::set_access_key(&store, &super::relay_crypto::base64url_encode(&[7u8; 32])).unwrap();
+ assert!(relay::access_key(&store).is_some());
+ // "Pair again"
+ let hub = Hub::new(Arc::new(Recorder::default()));
+ let token = Mutex::new(t1.clone());
+ super::renew_pairing(&hub, &token, &store).unwrap();
+ assert_ne!(*token.lock().unwrap(), t1);
+ assert_ne!(relay::pairing(&store).unwrap().0, room1);
+ // Clearing the access key goes through too.
+ relay::set_access_key(&store, "").unwrap();
+}
+
+#[test]
+fn a_key_outside_the_list_is_refused_by_the_strict_store() {
+ use pairing::tests::StrictStore;
+ use pairing::SecretStore;
+ assert!(StrictStore::default().set("phone-something-new", "x").is_err());
+}
+
+#[test]
+fn pairing_again_disconnects_the_phones_even_when_the_keystore_refuses_to_save() {
+ use pairing::tests::StrictStore;
+ use std::sync::atomic::Ordering;
+ block_on(async {
+ let rig = Rig::start().await;
+ let mut phone = Client::paired(&rig).await;
+ let store = StrictStore::default();
+ store.refuse_writes.store(true, Ordering::SeqCst);
+ let token = Mutex::new(TOKEN.to_string());
+ assert!(super::renew_pairing(&rig.hub, &token, &store).is_err());
+ // The error is reported, and the phone was cut off all the same.
+ assert_eq!(phone.expect("error").await["code"], "auth");
+ assert!(phone.closed().await);
+ });
+}
+
+#[test]
+fn over_the_wire_a_10000_character_command_is_flagged_and_allow_does_nothing() {
+ block_on(async {
+ let rig = Rig::start().await;
+ let mut c = Client::paired(&rig).await;
+ c.expect("sessions").await;
+ let command = format!("echo {}", "x".repeat(10_000));
+ rig.approval("req-long", &command, 0);
+ let approval = c.expect("approval").await;
+ assert_eq!(approval["truncated"], true);
+ assert_eq!(approval["command"].as_str().unwrap().chars().count(), 500);
+ let fp = approval["fingerprint"].as_str().unwrap().to_string();
+
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "allow" })).await;
+ c.send(json!({ "type": "ping" })).await;
+ c.expect("pong").await; // the decision before it was read, and ignored
+ assert!(rig.decisions().is_empty(), "Allow from the phone must not reach the agent");
+
+ // Deny still works.
+ c.send(json!({ "type": "decision", "fingerprint": fp, "decision": "deny" })).await;
+ c.expect("approvalResolved").await;
+ assert_eq!(rig.decisions(), vec![("req-long".to_string(), false)]);
+ });
+}
+
+// ── Which window may call which command ──
+
+#[test]
+fn only_the_right_window_may_call_a_command_that_changes_something() {
+ use super::{caller_allowed, Caller};
+ assert!(caller_allowed("settings", Caller::Settings));
+ assert!(caller_allowed("island", Caller::Island));
+ for other in ["island", "mochi", "", "Settings", "settings ", "main", "settings2"] {
+ assert!(!caller_allowed(other, Caller::Settings), "{other:?} must not act as the settings window");
+ }
+ for other in ["settings", "mochi", "", "Island", "island ", "main"] {
+ assert!(!caller_allowed(other, Caller::Island), "{other:?} must not act as the island");
+ }
+}
+
+/// Reads mod.rs: every `#[tauri::command]` that is not a plain read of a status must check the calling window. A command added later
+/// without the check fails here, which is how phone_link_set_enabled (it starts a network server) was found.
+#[test]
+fn every_command_that_changes_something_checks_the_calling_window() {
+ // The Windows runner checks files out with CRLF line endings.
+ let source = include_str!("mod.rs").replace("\r\n", "\n");
+ let mut seen = 0;
+ for chunk in source.split("#[tauri::command]\n").skip(1) {
+ let name = chunk.split("pub fn ").nth(1).and_then(|r| r.split('(').next()).expect("a command has a name");
+ let end = chunk.find("\n}\n").expect("a command ends");
+ let body = &chunk[..end];
+ seen += 1;
+ if name.ends_with("_status") {
+ // Reads only. None of them returns a secret: the relay's access key is reported as a yes/no.
+ assert!(!body.contains("settings::save") && !body.contains(".start()") && !body.contains(".stop()"), "{name} changes something");
+ continue;
+ }
+ assert!(
+ body.contains("window: WebviewWindow") && (body.contains("only_settings(&window)") || body.contains("only_island(&window)")),
+ "{name} changes something but does not check the calling window"
+ );
+ }
+ assert!(seen >= 25, "the test must see the commands (saw {seen})");
+}
diff --git a/windows/src-tauri/src/secrets.rs b/windows/src-tauri/src/secrets.rs
index 7b7a7671..e81ef527 100644
--- a/windows/src-tauri/src/secrets.rs
+++ b/windows/src-tauri/src/secrets.rs
@@ -53,3 +53,82 @@ pub fn clear(key: &str) -> Result<(), String> {
pub fn present(key: &str) -> bool {
get(key).is_some()
}
+
+// ── Entries only Rust reads and writes ───────────────────────────────────────
+//
+// The phone link's certificate, key and pairing token, and the relay's room, end-to-end key and access key.
+// They are not in KNOWN_KEYS
+// on purpose: the island has `secret_present` / `secret_set` / `secret_clear`
+// for those, and none of the three may be reachable from a webview.
+
+/// Every entry of that kind. Anything outside this list is refused.
+pub const INTERNAL_KEYS: &[&str] = &[
+ "phone-link-cert",
+ "phone-link-key",
+ "phone-link-token",
+ "phone-relay-room",
+ "phone-relay-key",
+ "phone-relay-access",
+];
+
+/// Whether the keystore would accept this key through `get_internal` / `set_internal`.
+pub fn is_internal(key: &str) -> bool {
+ INTERNAL_KEYS.contains(&key)
+}
+
+fn internal_entry(key: &str) -> Result<Entry, String> {
+ if !is_internal(key) {
+ return Err(format!("unknown key {key}"));
+ }
+ Entry::new(SERVICE, key).map_err(|e| e.to_string())
+}
+
+pub fn get_internal(key: &str) -> Option<String> {
+ internal_entry(key).ok()?.get_password().ok().filter(|v| !v.is_empty())
+}
+
+pub fn set_internal(key: &str, value: &str) -> Result<(), String> {
+ let entry = internal_entry(key)?;
+ if value.is_empty() {
+ // An empty value means "forget it" (the relay's access key); some keystores refuse an empty password.
+ return match entry.delete_credential() {
+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
+ Err(e) => Err(e.to_string()),
+ };
+ }
+ entry.set_password(value).map_err(|e| e.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_phone_links_secrets_cannot_be_reached_from_the_island() {
+ // The island's commands go through `get`/`set`/`clear`/`present`, which
+ // only know KNOWN_KEYS.
+ for key in INTERNAL_KEYS {
+ assert!(!KNOWN_KEYS.contains(key), "{key}");
+ assert!(entry(key).is_none(), "{key}");
+ assert!(set(key, "x").is_err(), "{key}");
+ assert!(clear(key).is_err(), "{key}");
+ assert!(!present(key), "{key}");
+ }
+ // And the other way round: a key of the island is not an internal one.
+ assert!(set_internal("github-token", "x").is_err());
+ }
+
+ /// Windows Credential Manager caps a secret's size. The phone link stores its certificate (about
+ /// 600 hex characters) and key there, so prove that a secret of that size round-trips through the
+ /// real store. A separate service name: this can never touch a user's real entries.
+ #[cfg(windows)]
+ #[test]
+ fn a_certificate_sized_secret_round_trips_through_credential_manager() {
+ let entry = keyring::Entry::new("fr.louisraille.coucou.test", "phone-link-size-check").unwrap();
+ let big: String = (0..1_200).map(|i| char::from(b"0123456789abcdef"[i % 16])).collect();
+ entry.set_password(&big).expect("Credential Manager refused a certificate-sized secret");
+ let back = entry.get_password().expect("could not read it back");
+ let _ = entry.delete_credential();
+ assert_eq!(back, big);
+ }
+}
diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rs
index 26590ef8..400d5ed5 100644
--- a/windows/src-tauri/src/settings.rs
+++ b/windows/src-tauri/src/settings.rs
@@ -69,6 +69,34 @@ pub struct Settings {
/// Mochi on the desktop: whether he lives there, and his spot. Owned by
/// the Rust side (desktop.rs) — what a webview sends back is ignored.
pub desktop_mochi: DesktopMochiPref,
+ /// The phone link (phone_link/) is on: a TLS server for the Android app on
+ /// the local network. Off until the user turns it on in Settings → Phone;
+ /// owned by the Rust side, so what a webview sends back is ignored.
+ pub phone_link: bool,
+ /// The phone may chat through this computer's API keys (phone_link/chat.rs).
+ /// Off until the user turns it on in Settings → Android phone; owned by the
+ /// Rust side like `phone_link`, so what a webview sends back is ignored.
+ pub phone_chat: bool,
+ /// Which models the phone may use, as "provider/model". Empty allows none.
+ /// Also owned by the Rust side (phone_link::set_chat_models cleans it).
+ pub phone_chat_models: Vec<String>,
+ /// The phone may see session details (steps, last line, project folder name, colour). Off until the
+ /// user turns it on in Settings → Android phone; owned by the Rust side like `phone_link`.
+ pub phone_details: bool,
+ /// Let the phone answer the questions Claude Code asks (cap `answers`). Off by default; owned by Rust like the other phone switches.
+ pub phone_answers: bool,
+ /// Show the files an agent changed on the phone, and their diffs on request (cap `diffs`). Off by default; owned by Rust like the other phone switches.
+ pub phone_diffs: bool,
+ /// Show the Claude and Codex plan usage on the phone (cap `usage`). Off by default; owned by Rust like the other phone switches.
+ pub phone_usage: bool,
+ /// The service pills whose cards the phone may see, by pill id (cap `services`). None by default; owned by Rust like the other phone switches.
+ pub phone_services: Vec<String>,
+ /// Reach the phone through the user's own relay when it is not on this network (phone_link/relay_client.rs).
+ /// Off by default; owned by Rust like the other phone switches. The access key, the room and the pairing key live
+ /// in the OS keystore, never here.
+ pub phone_relay: bool,
+ /// The relay's address (`wss://…`), empty until the user enters it. Not a secret. Owned by Rust.
+ pub phone_relay_url: String,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
@@ -124,6 +152,16 @@ impl Default for Settings {
pill_colors: BTreeMap::new(),
language: String::new(),
desktop_mochi: DesktopMochiPref::default(),
+ phone_link: false,
+ phone_chat: false,
+ phone_chat_models: Vec::new(),
+ phone_details: false,
+ phone_answers: false,
+ phone_diffs: false,
+ phone_usage: false,
+ phone_services: Vec::new(),
+ phone_relay: false,
+ phone_relay_url: String::new(),
}
}
}
@@ -400,7 +438,17 @@ mod tests {
"mochiOutfit": "witchHat",
"pillColors": { "integration_claude": "#2DD4BF" },
"language": "pt-BR",
- "desktopMochi": { "onDesktop": true, "spot": { "x": 1500.5, "y": -300.0, "space": "screen" } }
+ "desktopMochi": { "onDesktop": true, "spot": { "x": 1500.5, "y": -300.0, "space": "screen" } },
+ "phoneLink": true,
+ "phoneChat": true,
+ "phoneChatModels": ["openai/gpt-x"],
+ "phoneDetails": true,
+ "phoneAnswers": true,
+ "phoneDiffs": true,
+ "phoneUsage": true,
+ "phoneServices": ["integration_stripe"],
+ "phoneRelay": true,
+ "phoneRelayUrl": "wss://relay.example.workers.dev"
}"##;
fn custom() -> Value {
@@ -506,6 +554,100 @@ mod tests {
assert_eq!(loaded.mochi_outfit, "witchHat");
}
+ #[test]
+ fn a_file_from_before_the_phone_link_keeps_it_off() {
+ // The link opens a port on the local network: it is never on by default,
+ // and an older file must not be read as consent.
+ assert!(!Settings::default().phone_link);
+ let loaded = parse(&custom_with("phoneLink", None)).unwrap();
+ assert!(!loaded.phone_link);
+ assert_eq!(loaded.mochi_outfit, "witchHat");
+ assert!(parse(&custom_with("phoneLink", Some(serde_json::json!(true)))).unwrap().phone_link);
+
+ // A value of the wrong type does not switch it on either, and costs nothing else.
+ let (dir, file) = scratch("phone-link");
+ std::fs::write(&file, custom_with("phoneLink", Some(serde_json::json!("yes")))).unwrap();
+ let odd = load_from(&file);
+ assert!(!odd.phone_link);
+ assert_eq!(odd.mochi_outfit, "witchHat");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_file_from_before_phone_chat_keeps_it_off_and_empty() {
+ // Chat spends the user's API credit: never on by default, and an older file is not consent.
+ let d = Settings::default();
+ assert!(!d.phone_chat);
+ assert!(d.phone_chat_models.is_empty());
+ let loaded = parse(&custom_with("phoneChat", None)).unwrap();
+ assert!(!loaded.phone_chat);
+ assert!(parse(&custom_with("phoneChat", Some(serde_json::json!(true)))).unwrap().phone_chat);
+ let odd = parse(&custom_with("phoneChat", Some(serde_json::json!("yes")))).unwrap();
+ assert!(!odd.phone_chat, "a wrong type does not switch it on");
+ assert_eq!(odd.mochi_outfit, "witchHat");
+ let models = parse(&custom_with("phoneChatModels", Some(serde_json::json!(["openai/gpt-x"])))).unwrap();
+ assert_eq!(models.phone_chat_models, vec!["openai/gpt-x".to_string()]);
+ let bad = parse(&custom_with("phoneChatModels", Some(serde_json::json!("openai/gpt-x")))).unwrap();
+ assert!(bad.phone_chat_models.is_empty());
+ }
+
+ #[test]
+ fn a_file_from_before_phone_answers_keeps_it_off() {
+ // Answering for the agent from the phone is never on by default; an older file is not consent.
+ assert!(!Settings::default().phone_answers);
+ assert!(!parse(&custom_with("phoneAnswers", None)).unwrap().phone_answers);
+ assert!(parse(&custom_with("phoneAnswers", Some(serde_json::json!(true)))).unwrap().phone_answers);
+ assert!(!parse(&custom_with("phoneAnswers", Some(serde_json::json!("yes")))).unwrap().phone_answers, "a wrong type does not switch it on");
+ }
+
+ #[test]
+ fn a_file_from_before_phone_diffs_keeps_it_off() {
+ // Showing what an agent changed on the phone is never on by default; an older file is not consent.
+ assert!(!Settings::default().phone_diffs);
+ assert!(!parse(&custom_with("phoneDiffs", None)).unwrap().phone_diffs);
+ assert!(parse(&custom_with("phoneDiffs", Some(serde_json::json!(true)))).unwrap().phone_diffs);
+ assert!(!parse(&custom_with("phoneDiffs", Some(serde_json::json!("yes")))).unwrap().phone_diffs, "a wrong type does not switch it on");
+ }
+
+ #[test]
+ fn a_file_from_before_phone_usage_keeps_it_off() {
+ assert!(!Settings::default().phone_usage);
+ assert!(!parse(&custom_with("phoneUsage", None)).unwrap().phone_usage);
+ assert!(parse(&custom_with("phoneUsage", Some(serde_json::json!(true)))).unwrap().phone_usage);
+ assert!(!parse(&custom_with("phoneUsage", Some(serde_json::json!("yes")))).unwrap().phone_usage, "a wrong type does not switch it on");
+ }
+
+ #[test]
+ fn a_file_from_before_the_relay_keeps_it_off_and_empty() {
+ assert!(!Settings::default().phone_relay);
+ assert!(Settings::default().phone_relay_url.is_empty());
+ let old = parse(&custom_with("phoneRelay", None)).unwrap();
+ assert!(!old.phone_relay);
+ assert!(parse(&custom_with("phoneRelay", Some(serde_json::json!(true)))).unwrap().phone_relay);
+ assert!(!parse(&custom_with("phoneRelay", Some(serde_json::json!("yes")))).unwrap().phone_relay, "a wrong type does not switch it on");
+ assert!(parse(&custom_with("phoneRelayUrl", Some(serde_json::json!(5)))).unwrap().phone_relay_url.is_empty());
+ }
+
+ #[test]
+ fn a_file_from_before_phone_services_shows_none() {
+ // Showing a service on the phone is never on by default; an older file is not consent.
+ assert!(Settings::default().phone_services.is_empty());
+ assert!(parse(&custom_with("phoneServices", None)).unwrap().phone_services.is_empty());
+ assert_eq!(parse(&custom_with("phoneServices", Some(serde_json::json!(["integration_stripe"])))).unwrap().phone_services, vec!["integration_stripe".to_string()]);
+ assert!(parse(&custom_with("phoneServices", Some(serde_json::json!("integration_stripe")))).unwrap().phone_services.is_empty(), "a wrong type shows none");
+ }
+
+ #[test]
+ fn a_file_from_before_phone_details_keeps_them_off() {
+ // Details can include commands and folder names: never on by default, an older file is not consent.
+ assert!(!Settings::default().phone_details);
+ assert!(!parse(&custom_with("phoneDetails", None)).unwrap().phone_details);
+ assert!(parse(&custom_with("phoneDetails", Some(serde_json::json!(true)))).unwrap().phone_details);
+ let odd = parse(&custom_with("phoneDetails", Some(serde_json::json!("yes")))).unwrap();
+ assert!(!odd.phone_details, "a wrong type does not switch it on");
+ assert_eq!(odd.mochi_outfit, "witchHat");
+ }
+
#[test]
fn a_half_written_desktop_spot_costs_only_the_spot() {
let loaded = parse(&custom_with(
@@ -804,6 +946,16 @@ mod tests {
"pillColors",
"language",
"desktopMochi",
+ "phoneLink",
+ "phoneChat",
+ "phoneChatModels",
+ "phoneDetails",
+ "phoneAnswers",
+ "phoneDiffs",
+ "phoneUsage",
+ "phoneServices",
+ "phoneRelay",
+ "phoneRelayUrl",
]
);
let _ = std::fs::remove_dir_all(&dir);
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index e40b3935..848daecf 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -32,6 +32,152 @@ export interface BootInfo {
cursorPoll: boolean;
}
+/** The phone link (src-tauri/src/phone_link): how it is, never its secrets. */
+export interface PhoneLinkStatus {
+ enabled: boolean;
+ running: boolean;
+ port: number;
+ host: string;
+ name: string;
+ clients: number;
+ error: string | null;
+ /** The relay connection ("Away from home Wi-Fi"). */
+ relayState: PhoneRelayState;
+}
+
+export type PhoneRelayState = "off" | "connecting" | "waiting" | "linked" | "accessRefused" | "unreachable" | "roomTaken" | "tooMany";
+
+/** The relay switch and address. The access key is write-only: only whether one is stored comes back. */
+export interface PhoneRelayStatus {
+ enabled: boolean;
+ url: string;
+ hasAccess: boolean;
+ state: PhoneRelayState;
+}
+
+/** Session details for the phone: the switch (off by default). */
+export interface PhoneDetailsStatus {
+ enabled: boolean;
+}
+
+/** Chat from the phone: the switch and the models the phone may use ("provider/model"). */
+export interface PhoneChatStatus {
+ enabled: boolean;
+ models: string[];
+}
+
+/** What the settings window shows to pair a phone. Only the settings window may ask. */
+export interface PhoneLinkPairing {
+ link: string;
+ qrSvg: string;
+ host: string;
+ port: number;
+ name: string;
+ /** The relay's host when this link also carries the relay fields. */
+ relay: string | null;
+}
+
+/** One session as the phone sees it; Rust stamps `updatedAt`. */
+export interface PhoneLinkSession {
+ pillId: string;
+ agent: string;
+ state: string;
+ statusText: string;
+ stepIndex: number;
+ stepCount: number;
+ /** Details, for a phone that has the capability (the user's switch). */
+ steps?: string[];
+ finalLine?: string;
+ /** A folder name, never a path. */
+ project?: string;
+ color?: string;
+ /** The files this session changed, for a phone that has `diffs` (Rust cuts them to a name and a count). */
+ files?: PhoneLinkFile[];
+}
+
+export interface PhoneLinkFile {
+ id: number;
+ /** A file name; Rust keeps only its last segment. */
+ name: string;
+ added: number;
+ removed: number;
+ tooLarge?: boolean;
+ isNew?: boolean;
+}
+
+/** One file's diff for the phone that asked: lines as [kind, text], kind "+", "-", " " or "@" (a hunk's first line). */
+export interface PhoneLinkDiff {
+ pillId: string;
+ fileId: number;
+ name: string;
+ added: number;
+ removed: number;
+ tooLarge: boolean;
+ gone: boolean;
+ lines: [string, string][];
+}
+
+/** One plan window for the phone: used percentage (as the island has it) and when it resets (epoch ms). */
+export interface PhoneLinkWindow {
+ usedPct: number;
+ resetsAt: number;
+}
+
+export interface PhoneLinkPlan {
+ fiveHour?: PhoneLinkWindow;
+ sevenDay?: PhoneLinkWindow;
+ resetCredits?: number;
+ planType?: string;
+ updatedAt: number;
+}
+
+export interface PhoneLinkUsage {
+ claude: PhoneLinkPlan | null;
+ codex: PhoneLinkPlan | null;
+}
+
+/** What one service pill says, for a phone whose user allowed it (Rust cuts every text to size). */
+export interface PhoneLinkService {
+ id: string;
+ title: string;
+ headline: string;
+ reason?: string;
+ items: { label: string; detail: string }[];
+}
+
+export interface PhoneServicesStatus {
+ /** The services allowed for the phone. */
+ services: string[];
+}
+
+export interface PhoneUsageStatus {
+ enabled: boolean;
+}
+
+export interface PhoneDiffsStatus {
+ enabled: boolean;
+}
+
+export interface PhoneLinkApproval {
+ requestId: string;
+ sessionId: string;
+ pillId: string;
+ tool: string;
+ command: string;
+}
+
+/** The question Claude Code is waiting on, for a phone that may answer it (phone_link/hub.rs). */
+export interface PhoneLinkQuestion {
+ requestId: string;
+ sessionId: string;
+ pillId: string;
+ questions: { question: string; options: { label: string; description: string }[]; multiSelect: boolean }[];
+}
+
+export interface PhoneAnswersStatus {
+ enabled: boolean;
+}
+
export const Bridge = {
boot: () => call<BootInfo>("boot"),
/** The system's languages as the webview sees them, for Rust's own texts (i18n.rs). */
@@ -138,6 +284,47 @@ export const Bridge = {
/** "Nobody can act on this" — Claude Code asks in the terminal right away. */
approvalDecline: (requestId: string) => call<void>("approval_decline", { requestId }),
+ // ── Phone link (Coucou for Android) ───────────────────────────────────────
+ phoneLinkStatus: () => call<PhoneLinkStatus>("phone_link_status"),
+ /** Only ever from the switch in Settings. Throws with the reason if it cannot start. */
+ phoneLinkSetEnabled: (enabled: boolean) => callOrThrow<PhoneLinkStatus>("phone_link_set_enabled", { enabled }),
+ phoneLinkPairing: () => callOrThrow<PhoneLinkPairing>("phone_link_pairing"),
+ /** A new code: the phone that had the old one is disconnected. */
+ phoneLinkNewPairing: () => callOrThrow<PhoneLinkPairing>("phone_link_new_pairing"),
+ phoneDetailsStatus: () => call<PhoneDetailsStatus>("phone_details_status"),
+ /** Off by default; only from the switch in Settings. Phones are reconnected so they learn about it. */
+ phoneDetailsSetEnabled: (enabled: boolean) => callOrThrow<PhoneDetailsStatus>("phone_details_set_enabled", { enabled }),
+ phoneAnswersStatus: () => call<PhoneAnswersStatus>("phone_answers_status"),
+ /** Off by default; only from the switch in Settings. Phones are reconnected so they learn about it. */
+ phoneAnswersSetEnabled: (enabled: boolean) => callOrThrow<PhoneAnswersStatus>("phone_answers_set_enabled", { enabled }),
+ phoneDiffsStatus: () => call<PhoneDiffsStatus>("phone_diffs_status"),
+ /** Off by default; only from the switch in Settings. Phones are reconnected so they learn about it. */
+ phoneDiffsSetEnabled: (enabled: boolean) => callOrThrow<PhoneDiffsStatus>("phone_diffs_set_enabled", { enabled }),
+ /** The answer to a phone's request for a file's diff (the "phone-link-getdiff" event); `conn` says which phone. */
+ phoneLinkSendDiff: (conn: number, diff: PhoneLinkDiff) => call<void>("phone_link_send_diff", { conn, diff }),
+ phoneServicesStatus: () => call<PhoneServicesStatus>("phone_services_status"),
+ /** None by default; only from the ticks in Settings. Phones are reconnected so they learn about it. */
+ phoneServicesSet: (services: string[]) => callOrThrow<PhoneServicesStatus>("phone_services_set", { services }),
+ phoneLinkPublishServices: (services: PhoneLinkService[]) => call<void>("phone_link_publish_services", { services }),
+ phoneRelayStatus: () => call<PhoneRelayStatus>("phone_relay_status"),
+ /** Off by default; needs a valid wss:// address and a stored access key. */
+ phoneRelaySet: (enabled: boolean, url: string) => callOrThrow<PhoneRelayStatus>("phone_relay_set", { enabled, url }),
+ /** Write-only: stored in the OS keystore, never sent back. An empty value clears it. */
+ phoneRelaySetAccess: (access: string) => callOrThrow<PhoneRelayStatus>("phone_relay_set_access", { access }),
+ phoneUsageStatus: () => call<PhoneUsageStatus>("phone_usage_status"),
+ /** Off by default; only from the switch in Settings. Phones are reconnected so they learn about it. */
+ phoneUsageSetEnabled: (enabled: boolean) => callOrThrow<PhoneUsageStatus>("phone_usage_set_enabled", { enabled }),
+ phoneLinkPublishUsage: (usage: PhoneLinkUsage) => call<void>("phone_link_publish_usage", { usage }),
+ phoneChatStatus: () => call<PhoneChatStatus>("phone_chat_status"),
+ /** Off by default; only from the switch in Settings. Phones are reconnected so they learn about it. */
+ phoneChatSetEnabled: (enabled: boolean) => callOrThrow<PhoneChatStatus>("phone_chat_set_enabled", { enabled }),
+ phoneChatSetModels: (models: string[]) => callOrThrow<PhoneChatStatus>("phone_chat_set_models", { models }),
+ phoneLinkPublish: (sessions: PhoneLinkSession[], approval: PhoneLinkApproval | null) =>
+ call<void>("phone_link_publish", { sessions, approval }),
+ phoneLinkPublishQuestion: (question: PhoneLinkQuestion | null) => call<void>("phone_link_publish_question", { question }),
+ /** What Mochi wears ("auto" or an outfit), for phones that asked for it. */
+ phoneLinkPublishPrefs: (outfit: string) => call<void>("phone_link_publish_prefs", { outfit }),
+
// ── Chat, files, secrets ──────────────────────────────────────────────────
/** One chat turn. The API key and any file bytes never leave Rust. */
chatSend: (query: string, context: ChatContext | null) =>
diff --git a/windows/src/core/phone-chat.ts b/windows/src/core/phone-chat.ts
new file mode 100644
index 00000000..2cc10104
--- /dev/null
+++ b/windows/src/core/phone-chat.ts
@@ -0,0 +1,40 @@
+// Settings → Android phone → chat: which models the phone may use. Pure helpers, so the
+// rules can be tested without a webview. Rust cleans the list again (phone_link/chat_backend.rs);
+// this only builds it. The ids are "provider/model", as the phone is told them.
+
+import { PROVIDERS, type ProviderDef } from "./providers";
+import type { Settings } from "./state";
+
+/** Most models the user can allow; Rust caps the list at the same number. */
+export const MAX_ALLOWED = 50;
+
+export function modelId(provider: string, model: string): string {
+ return `${provider}/${model}`;
+}
+
+/** The provider part of an id, or null when it is not one this app knows. */
+export function providerOf(id: string): string | null {
+ const at = id.indexOf("/");
+ const provider = at > 0 ? id.slice(0, at) : "";
+ return PROVIDERS.some((p) => p.id === provider) && id.length > at + 1 ? provider : null;
+}
+
+/** `allowed` with `id` ticked or unticked: no duplicates, order kept, capped. */
+export function toggleModel(allowed: readonly string[], id: string, on: boolean): string[] {
+ const rest = allowed.filter((x) => x !== id);
+ if (!on) return rest;
+ return [...rest, id].slice(0, MAX_ALLOWED);
+}
+
+/**
+ * The providers worth offering: a cloud provider that has a key, a model server whose address is
+ * set. `hasKey` maps a provider id to "its key is saved".
+ */
+export function usableProviders(settings: Settings, hasKey: Readonly<Record<string, boolean>>): ProviderDef[] {
+ return PROVIDERS.filter((p) => (p.key ? hasKey[p.id] === true : p.urlField !== null && settings[p.urlField] !== ""));
+}
+
+/** The ids of `allowed` that belong to `provider`, without the provider part. */
+export function modelsOf(allowed: readonly string[], provider: string): string[] {
+ return allowed.filter((id) => providerOf(id) === provider).map((id) => id.slice(provider.length + 1));
+}
diff --git a/windows/src/core/state.ts b/windows/src/core/state.ts
index 6b78452c..3c9c8aa5 100644
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@ -146,6 +146,17 @@ export interface Settings {
* else English), or one of src/i18n's ten codes ("fr", "pt-BR", "zh-Hans"…).
*/
language: string;
+ /**
+ * The phone link for Coucou for Android is on. Rust owns it (only the switch in
+ * Settings → Android phone turns it on): whatever the page sends back is ignored.
+ */
+ phoneLink?: boolean;
+ /** The phone may chat through this computer's API keys. Rust owns it too. */
+ phoneChat?: boolean;
+ /** The phone may see session details (steps, last line, folder name, colour). Rust owns it too. */
+ phoneDetails?: boolean;
+ /** Which models the phone may use, "provider/model". Rust owns it too. */
+ phoneChatModels?: string[];
/** Mochi on the desktop. Rust owns it: whatever the page sends back is ignored. */
desktopMochi?: {
onDesktop: boolean;
diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.json
index 7de4fe35..89f7ecb8 100644
--- a/windows/src/i18n/extra.json
+++ b/windows/src/i18n/extra.json
@@ -1629,17 +1629,6 @@
"ru": "Платёж",
"id": "Pembayaran"
},
- "Permissions": {
- "zh-Hans": "权限",
- "hi": "अनुमतियाँ",
- "es": "Permisos",
- "ar": "الأذونات",
- "fr": "Permissions",
- "bn": "অনুমতি",
- "pt-BR": "Permissões",
- "ru": "Разрешения",
- "id": "Izin"
- },
"Pick a model above the chat box first.": {
"zh-Hans": "请先在聊天框上方选择一个模型。",
"hi": "पहले चैट बॉक्स के ऊपर एक मॉडल चुनें।",
@@ -3360,6 +3349,545 @@
"pt-BR": "Só um arquivo solto na ilha pode ser enviado com uma pergunta.",
"ru": "С вопросом можно отправить только файл, перетащенный на остров.",
"id": "Hanya file yang dijatuhkan ke pulau yang bisa dikirim bersama pertanyaan."
+ },
+ "Your phone finds this computer again by itself when the network changes. It is announced on your local network only while this switch is on. Some hotspots and guest networks block this.": {
+ "zh-Hans": "网络变化后,你的手机会自动重新找到这台电脑。只有在此开关打开时,才会在本地网络中公布。某些热点和访客网络会阻止这一功能。",
+ "hi": "नेटवर्क बदलने पर आपका फ़ोन इस कंप्यूटर को अपने-आप फिर से ढूँढ लेता है। यह स्विच चालू रहने पर ही इसे आपके लोकल नेटवर्क पर घोषित किया जाता है। कुछ हॉटस्पॉट और गेस्ट नेटवर्क इसे रोक देते हैं।",
+ "es": "Tu teléfono vuelve a encontrar este ordenador por sí solo cuando cambia la red. Solo se anuncia en tu red local mientras este interruptor esté activado. Algunos puntos de acceso y redes de invitados lo bloquean.",
+ "ar": "يعثر هاتفك على هذا الكمبيوتر من جديد تلقائيًا عند تغيّر الشبكة. ولا يُعلَن عنه في شبكتك المحلية إلا أثناء تشغيل هذا المفتاح. بعض نقاط الاتصال وشبكات الضيوف تحجب ذلك.",
+ "fr": "Ton téléphone retrouve tout seul cet ordinateur quand le réseau change. Il n'est annoncé sur ton réseau local que tant que cet interrupteur est activé. Certains points d'accès et réseaux invités bloquent cette fonction.",
+ "bn": "নেটওয়ার্ক বদলালে আপনার ফোন নিজে থেকেই এই কম্পিউটারটি আবার খুঁজে নেয়। এই সুইচ চালু থাকলে তবেই এটি আপনার লোকাল নেটওয়ার্কে জানানো হয়। কিছু হটস্পট ও গেস্ট নেটওয়ার্ক এটি আটকে দেয়।",
+ "pt-BR": "Seu celular encontra este computador de novo sozinho quando a rede muda. Ele só é anunciado na sua rede local enquanto esta chave estiver ligada. Alguns hotspots e redes de convidados bloqueiam isso.",
+ "ru": "Телефон сам находит этот компьютер снова, когда сеть меняется. Компьютер объявляется в вашей локальной сети только пока этот переключатель включён. Некоторые точки доступа и гостевые сети это блокируют.",
+ "id": "Ponsel Anda menemukan komputer ini lagi secara otomatis saat jaringan berubah. Komputer ini hanya diumumkan di jaringan lokal Anda selama sakelar ini aktif. Beberapa hotspot dan jaringan tamu memblokirnya."
+ },
+ "Let the phone answer Claude Code's questions": {
+ "zh-Hans": "允许手机回答 Claude Code 的提问",
+ "hi": "फ़ोन को Claude Code के सवालों के जवाब देने दें",
+ "es": "Dejar que el teléfono responda a las preguntas de Claude Code",
+ "ar": "السماح للهاتف بالإجابة عن أسئلة Claude Code",
+ "fr": "Laisser le téléphone répondre aux questions de Claude Code",
+ "bn": "ফোনকে Claude Code-এর প্রশ্নের উত্তর দিতে দিন",
+ "pt-BR": "Deixar o celular responder às perguntas do Claude Code",
+ "ru": "Разрешить телефону отвечать на вопросы Claude Code",
+ "id": "Izinkan ponsel menjawab pertanyaan Claude Code"
+ },
+ "The phone shows each question with its options. Every answer is confirmed with the phone's fingerprint or screen lock.": {
+ "zh-Hans": "手机会显示每个问题及其选项。每个回答都需要用手机的指纹或锁屏来确认。",
+ "hi": "फ़ोन हर सवाल को उसके विकल्पों के साथ दिखाता है। हर जवाब की पुष्टि फ़ोन के फ़िंगरप्रिंट या स्क्रीन लॉक से होती है।",
+ "es": "El teléfono muestra cada pregunta con sus opciones. Cada respuesta se confirma con la huella o el bloqueo de pantalla del teléfono.",
+ "ar": "يعرض الهاتف كل سؤال مع خياراته. يتم تأكيد كل إجابة ببصمة الهاتف أو قفل الشاشة.",
+ "fr": "Le téléphone affiche chaque question avec ses options. Chaque réponse est confirmée avec l'empreinte ou le verrouillage d'écran du téléphone.",
+ "bn": "ফোন প্রতিটি প্রশ্ন তার বিকল্পসহ দেখায়। প্রতিটি উত্তর ফোনের ফিঙ্গারপ্রিন্ট বা স্ক্রিন লক দিয়ে নিশ্চিত করা হয়।",
+ "pt-BR": "O celular mostra cada pergunta com suas opções. Cada resposta é confirmada com a digital ou o bloqueio de tela do celular.",
+ "ru": "Телефон показывает каждый вопрос с вариантами. Каждый ответ подтверждается отпечатком пальца или блокировкой экрана телефона.",
+ "id": "Ponsel menampilkan setiap pertanyaan beserta pilihannya. Setiap jawaban dikonfirmasi dengan sidik jari atau kunci layar ponsel."
+ },
+ "Android phone": {
+ "zh-Hans": "Android 手机",
+ "hi": "Android फ़ोन",
+ "es": "Teléfono Android",
+ "ar": "هاتف Android",
+ "fr": "Téléphone Android",
+ "bn": "Android ফোন",
+ "pt-BR": "Celular Android",
+ "ru": "Телефон Android",
+ "id": "Ponsel Android"
+ },
+ "Send your agents' sessions to Coucou for Android and answer permission requests from the phone. Off by default; it only listens on your local network.": {
+ "zh-Hans": "把你的智能体会话发送到 Coucou for Android,并在手机上回应权限请求。默认关闭;仅在本地网络中监听。",
+ "hi": "अपने एजेंट के सत्र Coucou for Android को भेजें और फ़ोन से अनुमति के अनुरोधों का जवाब दें। डिफ़ॉल्ट रूप से बंद; यह केवल आपके स्थानीय नेटवर्क पर सुनता है।",
+ "es": "Envía las sesiones de tus agentes a Coucou for Android y responde a las solicitudes de permiso desde el teléfono. Desactivado por defecto; solo escucha en tu red local.",
+ "ar": "أرسل جلسات وكلائك إلى Coucou for Android وردّ على طلبات الإذن من الهاتف. معطّل افتراضيًا؛ ويستمع فقط على شبكتك المحلية.",
+ "fr": "Envoie les sessions de tes agents à Coucou for Android et réponds aux demandes d'autorisation depuis le téléphone. Désactivé par défaut ; il n'écoute que sur ton réseau local.",
+ "bn": "আপনার এজেন্টদের সেশন Coucou for Android-এ পাঠান এবং ফোন থেকে অনুমতির অনুরোধের উত্তর দিন। ডিফল্টে বন্ধ; এটি শুধু আপনার লোকাল নেটওয়ার্কে শোনে।",
+ "pt-BR": "Envie as sessões dos seus agentes ao Coucou for Android e responda a pedidos de permissão pelo celular. Desativado por padrão; só escuta na sua rede local.",
+ "ru": "Отправляйте сессии ваших агентов в Coucou for Android и отвечайте на запросы разрешений с телефона. По умолчанию выключено; слушает только в вашей локальной сети.",
+ "id": "Kirim sesi agen Anda ke Coucou for Android dan jawab permintaan izin dari ponsel. Nonaktif secara default; hanya mendengarkan di jaringan lokal Anda."
+ },
+ "Allow on the phone asks for the fingerprint or the screen lock. Deny does not.": {
+ "zh-Hans": "在手机上点“允许”需要指纹或锁屏验证;“拒绝”则不需要。",
+ "hi": "फ़ोन पर अनुमति देने के लिए फ़िंगरप्रिंट या स्क्रीन लॉक माँगा जाता है। अस्वीकार के लिए नहीं।",
+ "es": "Permitir en el teléfono pide la huella o el bloqueo de pantalla. Denegar no.",
+ "ar": "السماح على الهاتف يتطلب بصمة الإصبع أو قفل الشاشة. أما الرفض فلا يتطلبها.",
+ "fr": "Autoriser sur le téléphone demande l'empreinte ou le verrouillage d'écran. Refuser, non.",
+ "bn": "ফোনে অনুমতি দিতে ফিঙ্গারপ্রিন্ট বা স্ক্রিন লক লাগে। প্রত্যাখ্যানে লাগে না।",
+ "pt-BR": "Permitir no celular pede a digital ou o bloqueio de tela. Negar não pede.",
+ "ru": "Чтобы разрешить на телефоне, нужен отпечаток пальца или блокировка экрана. Для отказа — не нужен.",
+ "id": "Mengizinkan di ponsel meminta sidik jari atau kunci layar. Menolak tidak."
+ },
+ "Phone link": {
+ "zh-Hans": "手机连接",
+ "hi": "फ़ोन लिंक",
+ "es": "Enlace con el teléfono",
+ "ar": "ربط الهاتف",
+ "fr": "Lien avec le téléphone",
+ "bn": "ফোন লিংক",
+ "pt-BR": "Link com o celular",
+ "ru": "Связь с телефоном",
+ "id": "Tautan ponsel"
+ },
+ "Could not turn it on: {error}": {
+ "zh-Hans": "无法开启:{error}",
+ "hi": "चालू नहीं हो सका: {error}",
+ "es": "No se pudo activar: {error}",
+ "ar": "تعذّر التفعيل: {error}",
+ "fr": "Impossible de l'activer : {error}",
+ "bn": "চালু করা যায়নি: {error}",
+ "pt-BR": "Não foi possível ativar: {error}",
+ "ru": "Не удалось включить: {error}",
+ "id": "Tidak dapat mengaktifkan: {error}"
+ },
+ "Show pairing code": {
+ "zh-Hans": "显示配对码",
+ "hi": "पेयरिंग कोड दिखाएँ",
+ "es": "Mostrar código de emparejamiento",
+ "ar": "إظهار رمز الاقتران",
+ "fr": "Afficher le code d'association",
+ "bn": "পেয়ারিং কোড দেখান",
+ "pt-BR": "Mostrar código de pareamento",
+ "ru": "Показать код сопряжения",
+ "id": "Tampilkan kode penyandingan"
+ },
+ "Phones connected: {count}": {
+ "zh-Hans": "已连接的手机:{count}",
+ "hi": "जुड़े फ़ोन: {count}",
+ "es": "Teléfonos conectados: {count}",
+ "ar": "الهواتف المتصلة: {count}",
+ "fr": "Téléphones connectés : {count}",
+ "bn": "সংযুক্ত ফোন: {count}",
+ "pt-BR": "Celulares conectados: {count}",
+ "ru": "Подключённые телефоны: {count}",
+ "id": "Ponsel terhubung: {count}"
+ },
+ "In Coucou for Android, scan this code with the camera or paste the link.": {
+ "zh-Hans": "在 Coucou for Android 中,用相机扫描此码,或粘贴链接。",
+ "hi": "Coucou for Android में कैमरे से यह कोड स्कैन करें या लिंक पेस्ट करें।",
+ "es": "En Coucou for Android, escanea este código con la cámara o pega el enlace.",
+ "ar": "في Coucou for Android، امسح هذا الرمز بالكاميرا أو الصق الرابط.",
+ "fr": "Dans Coucou for Android, scanne ce code avec l'appareil photo ou colle le lien.",
+ "bn": "Coucou for Android-এ ক্যামেরা দিয়ে এই কোড স্ক্যান করুন বা লিংক পেস্ট করুন।",
+ "pt-BR": "No Coucou for Android, escaneie este código com a câmera ou cole o link.",
+ "ru": "В Coucou for Android отсканируйте этот код камерой или вставьте ссылку.",
+ "id": "Di Coucou for Android, pindai kode ini dengan kamera atau tempel tautannya."
+ },
+ "Copy link": {
+ "zh-Hans": "复制链接",
+ "hi": "लिंक कॉपी करें",
+ "es": "Copiar enlace",
+ "ar": "نسخ الرابط",
+ "fr": "Copier le lien",
+ "bn": "লিংক কপি করুন",
+ "pt-BR": "Copiar link",
+ "ru": "Скопировать ссылку",
+ "id": "Salin tautan"
+ },
+ "Pair again": {
+ "zh-Hans": "重新配对",
+ "hi": "फिर से पेयर करें",
+ "es": "Emparejar de nuevo",
+ "ar": "إعادة الاقتران",
+ "fr": "Associer à nouveau",
+ "bn": "আবার পেয়ার করুন",
+ "pt-BR": "Parear de novo",
+ "ru": "Сопрячь заново",
+ "id": "Sandingkan ulang"
+ },
+ "The phone that was paired is disconnected and needs the new code.": {
+ "zh-Hans": "已配对的手机会断开连接,并需要新的配对码。",
+ "hi": "जो फ़ोन पेयर था वह डिस्कनेक्ट हो जाएगा और उसे नया कोड चाहिए।",
+ "es": "El teléfono emparejado se desconecta y necesita el código nuevo.",
+ "ar": "سيُفصل الهاتف المقترن ويحتاج إلى الرمز الجديد.",
+ "fr": "Le téléphone associé est déconnecté et a besoin du nouveau code.",
+ "bn": "যে ফোনটি পেয়ার করা ছিল সেটি বিচ্ছিন্ন হবে এবং নতুন কোড লাগবে।",
+ "pt-BR": "O celular pareado é desconectado e precisa do novo código.",
+ "ru": "Сопряжённый телефон отключится, и ему понадобится новый код.",
+ "id": "Ponsel yang tersandingkan akan terputus dan memerlukan kode baru."
+ },
+ "If Windows asks about the firewall, allow Coucou on private networks. The phone and this computer must be on the same Wi-Fi.": {
+ "zh-Hans": "如果 Windows 询问防火墙,请允许 Coucou 在专用网络上通信。手机和这台电脑必须连接同一个 Wi-Fi。",
+ "hi": "अगर Windows फ़ायरवॉल के बारे में पूछे, तो Coucou को निजी नेटवर्क पर अनुमति दें। फ़ोन और यह कंप्यूटर एक ही Wi-Fi पर होने चाहिए।",
+ "es": "Si Windows pregunta por el firewall, permite Coucou en redes privadas. El teléfono y este equipo deben estar en la misma Wi-Fi.",
+ "ar": "إذا سأل Windows عن جدار الحماية، فاسمح لـ Coucou على الشبكات الخاصة. يجب أن يكون الهاتف وهذا الكمبيوتر على شبكة Wi-Fi نفسها.",
+ "fr": "Si Windows te interroge sur le pare-feu, autorise Coucou sur les réseaux privés. Le téléphone et cet ordinateur doivent être sur le même Wi-Fi.",
+ "bn": "Windows ফায়ারওয়াল নিয়ে জিজ্ঞেস করলে Coucou-কে প্রাইভেট নেটওয়ার্কে অনুমতি দিন। ফোন ও এই কম্পিউটার একই Wi-Fi-তে থাকতে হবে।",
+ "pt-BR": "Se o Windows perguntar sobre o firewall, permita o Coucou em redes privadas. O celular e este computador precisam estar no mesmo Wi-Fi.",
+ "ru": "Если Windows спросит про брандмауэр, разрешите Coucou в частных сетях. Телефон и этот компьютер должны быть в одной сети Wi-Fi.",
+ "id": "Jika Windows menanyakan firewall, izinkan Coucou di jaringan pribadi. Ponsel dan komputer ini harus berada di Wi-Fi yang sama."
+ },
+ "The phone connects to {address}": {
+ "zh-Hans": "手机连接的地址:{address}",
+ "hi": "फ़ोन इस पते से जुड़ता है: {address}",
+ "es": "El teléfono se conecta a {address}",
+ "ar": "يتصل الهاتف بالعنوان {address}",
+ "fr": "Le téléphone se connecte à {address}",
+ "bn": "ফোন যে ঠিকানায় সংযুক্ত হয়: {address}",
+ "pt-BR": "O celular se conecta a {address}",
+ "ru": "Телефон подключается к {address}",
+ "id": "Ponsel terhubung ke {address}"
+ },
+ "Let the phone chat with my AI providers": {
+ "zh-Hans": "允许手机使用我的 AI 提供商聊天",
+ "hi": "फ़ोन को मेरे AI प्रदाताओं से चैट करने दें",
+ "es": "Permitir que el teléfono chatee con mis proveedores de IA",
+ "ar": "السماح للهاتف بالدردشة مع مزوّدي الذكاء الاصطناعي لديّ",
+ "fr": "Laisser le téléphone discuter avec mes fournisseurs d'IA",
+ "bn": "ফোনকে আমার AI প্রদানকারীদের সঙ্গে চ্যাট করতে দিন",
+ "pt-BR": "Permitir que o celular converse com meus provedores de IA",
+ "ru": "Разрешить телефону общаться с моими ИИ-провайдерами",
+ "id": "Izinkan ponsel mengobrol dengan penyedia AI saya"
+ },
+ "Chat uses the API keys saved on this computer. The phone never sees them, and each message may cost money.": {
+ "zh-Hans": "聊天使用保存在这台电脑上的 API 密钥。手机永远看不到密钥,每条消息都可能产生费用。",
+ "hi": "चैट इस कंप्यूटर पर सहेजी गई API कुंजियों का उपयोग करती है। फ़ोन उन्हें कभी नहीं देखता, और हर संदेश पर शुल्क लग सकता है।",
+ "es": "El chat usa las claves de API guardadas en este ordenador. El teléfono nunca las ve y cada mensaje puede costar dinero.",
+ "ar": "تستخدم الدردشة مفاتيح API المحفوظة على هذا الكمبيوتر. لا يراها الهاتف أبدًا، وقد تترتب تكلفة على كل رسالة.",
+ "fr": "Le chat utilise les clés d'API enregistrées sur cet ordinateur. Le téléphone ne les voit jamais, et chaque message peut coûter de l'argent.",
+ "bn": "চ্যাট এই কম্পিউটারে সংরক্ষিত API কী ব্যবহার করে। ফোন কখনও সেগুলো দেখে না, এবং প্রতিটি বার্তায় খরচ হতে পারে।",
+ "pt-BR": "O chat usa as chaves de API salvas neste computador. O celular nunca as vê, e cada mensagem pode custar dinheiro.",
+ "ru": "Чат использует ключи API, сохранённые на этом компьютере. Телефон их никогда не видит, а каждое сообщение может стоить денег.",
+ "id": "Obrolan memakai kunci API yang tersimpan di komputer ini. Ponsel tidak pernah melihatnya, dan setiap pesan dapat memakan biaya."
+ },
+ "Models the phone may use": {
+ "zh-Hans": "手机可使用的模型",
+ "hi": "फ़ोन जिन मॉडलों का उपयोग कर सकता है",
+ "es": "Modelos que puede usar el teléfono",
+ "ar": "النماذج التي يمكن للهاتف استخدامها",
+ "fr": "Modèles que le téléphone peut utiliser",
+ "bn": "ফোন যেসব মডেল ব্যবহার করতে পারে",
+ "pt-BR": "Modelos que o celular pode usar",
+ "ru": "Модели, доступные телефону",
+ "id": "Model yang boleh dipakai ponsel"
+ },
+ "Choose models": {
+ "zh-Hans": "选择模型",
+ "hi": "मॉडल चुनें",
+ "es": "Elegir modelos",
+ "ar": "اختيار النماذج",
+ "fr": "Choisir les modèles",
+ "bn": "মডেল বেছে নিন",
+ "pt-BR": "Escolher modelos",
+ "ru": "Выбрать модели",
+ "id": "Pilih model"
+ },
+ "Nothing is allowed yet: the phone cannot chat until you tick a model.": {
+ "zh-Hans": "尚未允许任何模型:勾选一个模型后,手机才能聊天。",
+ "hi": "अभी कुछ भी अनुमत नहीं है: जब तक आप कोई मॉडल नहीं चुनते, फ़ोन चैट नहीं कर सकता।",
+ "es": "Aún no hay nada permitido: el teléfono no podrá chatear hasta que marques un modelo.",
+ "ar": "لا يوجد شيء مسموح به بعد: لا يمكن للهاتف الدردشة حتى تحدّد نموذجًا.",
+ "fr": "Rien n'est autorisé pour l'instant : le téléphone ne peut pas discuter tant que vous n'avez pas coché un modèle.",
+ "bn": "এখনও কিছু অনুমোদিত নয়: আপনি একটি মডেল না বাছা পর্যন্ত ফোন চ্যাট করতে পারবে না।",
+ "pt-BR": "Nada foi permitido ainda: o celular não poderá conversar até você marcar um modelo.",
+ "ru": "Пока ничего не разрешено: телефон не сможет общаться, пока вы не отметите модель.",
+ "id": "Belum ada yang diizinkan: ponsel tidak bisa mengobrol sampai Anda mencentang sebuah model."
+ },
+ "No provider is ready: add an API key or connect a local model first.": {
+ "zh-Hans": "没有可用的提供商:请先添加 API 密钥或连接本地模型。",
+ "hi": "कोई प्रदाता तैयार नहीं है: पहले API कुंजी जोड़ें या स्थानीय मॉडल कनेक्ट करें।",
+ "es": "Ningún proveedor está listo: añade primero una clave de API o conecta un modelo local.",
+ "ar": "لا يوجد مزوّد جاهز: أضف مفتاح API أو اتصل بنموذج محلي أولاً.",
+ "fr": "Aucun fournisseur n'est prêt : ajoutez d'abord une clé d'API ou connectez un modèle local.",
+ "bn": "কোনো প্রদানকারী প্রস্তুত নয়: আগে একটি API কী যোগ করুন বা স্থানীয় মডেল সংযুক্ত করুন।",
+ "pt-BR": "Nenhum provedor está pronto: adicione primeiro uma chave de API ou conecte um modelo local.",
+ "ru": "Нет готовых провайдеров: сначала добавьте ключ API или подключите локальную модель.",
+ "id": "Belum ada penyedia yang siap: tambahkan kunci API atau hubungkan model lokal terlebih dahulu."
+ },
+ "Show session details on the phone": {
+ "zh-Hans": "在手机上显示会话详情",
+ "hi": "फ़ोन पर सत्र का विवरण दिखाएँ",
+ "es": "Mostrar los detalles de la sesión en el teléfono",
+ "ar": "إظهار تفاصيل الجلسة على الهاتف",
+ "fr": "Afficher les détails de la session sur le téléphone",
+ "bn": "ফোনে সেশনের বিবরণ দেখান",
+ "pt-BR": "Mostrar os detalhes da sessão no celular",
+ "ru": "Показывать детали сессии на телефоне",
+ "id": "Tampilkan detail sesi di ponsel"
+ },
+ "Sends the last steps (as shown on the island, so they can include commands), the final line, the project's folder name and the colour. Never a path.": {
+ "zh-Hans": "发送最近的步骤(与灵动岛上显示的一致,可能包含命令)、最后一行、项目文件夹名称和颜色。绝不发送路径。",
+ "hi": "आख़िरी चरण (जैसे आइलैंड पर दिखते हैं, इसलिए उनमें कमांड हो सकते हैं), आख़िरी पंक्ति, प्रोजेक्ट के फ़ोल्डर का नाम और रंग भेजता है। कभी कोई पाथ नहीं।",
+ "es": "Envía los últimos pasos (tal como se ven en la isla, por lo que pueden incluir comandos), la línea final, el nombre de la carpeta del proyecto y el color. Nunca una ruta.",
+ "ar": "يرسل الخطوات الأخيرة (كما تظهر في الجزيرة، فقد تتضمن أوامر) والسطر الأخير واسم مجلد المشروع واللون. لا يرسل مسارًا أبدًا.",
+ "fr": "Envoie les dernières étapes (telles qu'elles apparaissent sur l'île, donc elles peuvent contenir des commandes), la dernière ligne, le nom du dossier du projet et la couleur. Jamais un chemin.",
+ "bn": "শেষ ধাপগুলো (আইল্যান্ডে যেমন দেখায়, তাই তাতে কমান্ড থাকতে পারে), শেষ লাইন, প্রকল্পের ফোল্ডারের নাম ও রং পাঠায়। কখনও কোনো পাথ নয়।",
+ "pt-BR": "Envia as últimas etapas (como aparecem na ilha, então podem incluir comandos), a linha final, o nome da pasta do projeto e a cor. Nunca um caminho.",
+ "ru": "Отправляет последние шаги (как на острове, поэтому в них могут быть команды), последнюю строку, имя папки проекта и цвет. Никогда не путь.",
+ "id": "Mengirim langkah terakhir (seperti tampil di pulau, jadi bisa berisi perintah), baris akhir, nama folder proyek, dan warna. Tidak pernah jalur."
+ },
+ "Show the files an agent changed on the phone": {
+ "zh-Hans": "在手机上显示智能体修改过的文件",
+ "hi": "फ़ोन पर वे फ़ाइलें दिखाएँ जिन्हें एजेंट ने बदला",
+ "es": "Mostrar en el teléfono los archivos que un agente ha cambiado",
+ "ar": "عرض الملفات التي غيّرها الوكيل على الهاتف",
+ "fr": "Afficher sur le téléphone les fichiers qu'un agent a modifiés",
+ "bn": "এজেন্ট যে ফাইলগুলো বদলেছে সেগুলো ফোনে দেখান",
+ "pt-BR": "Mostrar no celular os arquivos que um agente alterou",
+ "ru": "Показывать на телефоне файлы, изменённые агентом",
+ "id": "Tampilkan file yang diubah agen di ponsel"
+ },
+ "The phone lists the files each agent changed and, when you tap one, shows what changed in it (200 lines at most, long lines cut). File names and lines go only to your paired phone, over the pinned encrypted link, and only when it asks.": {
+ "zh-Hans": "手机会列出每个智能体修改过的文件,点按某个文件即可查看其中的改动(最多 200 行,过长的行会被截断)。文件名和内容只会在手机请求时,通过已固定证书的加密连接发送给已配对的手机。",
+ "hi": "फ़ोन हर एजेंट की बदली हुई फ़ाइलों की सूची दिखाता है और किसी फ़ाइल पर टैप करने पर उसमें हुए बदलाव दिखाता है (अधिकतम 200 पंक्तियाँ, लंबी पंक्तियाँ कटी हुई)। फ़ाइल के नाम और पंक्तियाँ केवल आपके जोड़े गए फ़ोन को, पिन किए गए एन्क्रिप्टेड लिंक से, और केवल उसके माँगने पर जाती हैं।",
+ "es": "El teléfono muestra la lista de archivos que cambió cada agente y, al tocar uno, lo que cambió en él (200 líneas como máximo, las líneas largas se recortan). Los nombres y las líneas solo llegan a tu teléfono emparejado, por el enlace cifrado y fijado, y solo cuando los pide.",
+ "ar": "يعرض الهاتف قائمة بالملفات التي غيّرها كل وكيل، وعند الضغط على ملف يعرض ما تغيّر فيه (200 سطر كحد أقصى، وتُقتطع الأسطر الطويلة). تُرسل أسماء الملفات والأسطر إلى هاتفك المقترن فقط، عبر الرابط المشفّر المثبّت، وعندما يطلبها فقط.",
+ "fr": "Le téléphone liste les fichiers modifiés par chaque agent et, si vous en touchez un, montre ce qui y a changé (200 lignes au plus, les longues lignes sont coupées). Les noms et les lignes ne vont qu'à votre téléphone associé, par le lien chiffré et épinglé, et seulement quand il les demande.",
+ "bn": "ফোন প্রতিটি এজেন্টের বদলানো ফাইলের তালিকা দেখায় এবং কোনো ফাইলে ট্যাপ করলে তাতে কী বদলেছে তা দেখায় (সর্বোচ্চ ২০০ লাইন, লম্বা লাইন কেটে দেওয়া হয়)। ফাইলের নাম ও লাইন শুধু আপনার যুক্ত করা ফোনে, পিন করা এনক্রিপ্টেড লিঙ্কে এবং ফোন চাইলেই যায়।",
+ "pt-BR": "O celular lista os arquivos que cada agente alterou e, ao tocar em um, mostra o que mudou nele (200 linhas no máximo, linhas longas são cortadas). Os nomes e as linhas vão só para o seu celular pareado, pelo link criptografado e fixado, e só quando ele pede.",
+ "ru": "Телефон показывает список файлов, изменённых каждым агентом, а при нажатии на файл — что в нём изменилось (не более 200 строк, длинные строки обрезаются). Имена файлов и строки отправляются только на ваш подключённый телефон, по защищённому зашифрованному каналу и только по его запросу.",
+ "id": "Ponsel menampilkan daftar file yang diubah tiap agen dan, saat Anda mengetuk salah satu, apa yang berubah di dalamnya (maksimal 200 baris, baris panjang dipotong). Nama file dan baris hanya dikirim ke ponsel Anda yang terhubung, lewat tautan terenkripsi yang disematkan, dan hanya saat ponsel memintanya."
+ },
+ "Show my plan usage on the phone": {
+ "zh-Hans": "在手机上显示我的套餐用量",
+ "hi": "फ़ोन पर मेरे प्लान का उपयोग दिखाएँ",
+ "es": "Mostrar en el teléfono el uso de mi plan",
+ "ar": "عرض استهلاك خطتي على الهاتف",
+ "fr": "Afficher sur le téléphone l'utilisation de mon forfait",
+ "bn": "ফোনে আমার প্ল্যানের ব্যবহার দেখান",
+ "pt-BR": "Mostrar no celular o uso do meu plano",
+ "ru": "Показывать на телефоне использование моего тарифа",
+ "id": "Tampilkan penggunaan paket saya di ponsel"
+ },
+ "The phone shows how much of your Claude and Codex plans is used and when they reset: the same percentages as the pills here, nothing else.": {
+ "zh-Hans": "手机会显示您的 Claude 和 Codex 套餐已用多少以及何时重置:与这里的药丸显示的百分比相同,不包含其他内容。",
+ "hi": "फ़ोन दिखाता है कि आपके Claude और Codex प्लान का कितना उपयोग हुआ और वे कब रीसेट होंगे: वही प्रतिशत जो यहाँ की पिल में दिखते हैं, और कुछ नहीं।",
+ "es": "El teléfono muestra cuánto se ha usado de tus planes de Claude y Codex y cuándo se restablecen: los mismos porcentajes que las píldoras de aquí, nada más.",
+ "ar": "يعرض الهاتف مقدار ما استُهلك من خطتي Claude وCodex ومتى تُعاد تهيئتهما: النسب نفسها المعروضة في الأقراص هنا، ولا شيء غيرها.",
+ "fr": "Le téléphone montre la part utilisée de vos forfaits Claude et Codex et leur réinitialisation : les mêmes pourcentages que les pastilles ici, rien d'autre.",
+ "bn": "ফোন দেখায় আপনার Claude ও Codex প্ল্যানের কতটা ব্যবহার হয়েছে এবং কখন রিসেট হবে: এখানকার পিলের মতো একই শতাংশ, আর কিছু নয়।",
+ "pt-BR": "O celular mostra quanto dos seus planos do Claude e do Codex foi usado e quando eles reiniciam: as mesmas porcentagens das pílulas aqui, nada mais.",
+ "ru": "Телефон показывает, какая часть ваших тарифов Claude и Codex использована и когда они сбросятся: те же проценты, что и на плашках здесь, и ничего больше.",
+ "id": "Ponsel menampilkan seberapa banyak paket Claude dan Codex Anda terpakai dan kapan direset: persentase yang sama dengan pil di sini, tidak ada yang lain."
+ },
+ "Payment failed": {
+ "zh-Hans": "付款失败",
+ "hi": "भुगतान विफल",
+ "es": "Pago fallido",
+ "ar": "فشل الدفع",
+ "fr": "Paiement échoué",
+ "bn": "পেমেন্ট ব্যর্থ",
+ "pt-BR": "Pagamento falhou",
+ "ru": "Платёж не прошёл",
+ "id": "Pembayaran gagal"
+ },
+ "Delivered": {
+ "zh-Hans": "已送达",
+ "hi": "पहुँचाया गया",
+ "es": "Entregado",
+ "ar": "تم التسليم",
+ "fr": "Remis",
+ "bn": "পৌঁছেছে",
+ "pt-BR": "Entregue",
+ "ru": "Доставлено",
+ "id": "Terkirim"
+ },
+ "Not delivered": {
+ "zh-Hans": "未送达",
+ "hi": "नहीं पहुँचा",
+ "es": "No entregado",
+ "ar": "لم يتم التسليم",
+ "fr": "Non remis",
+ "bn": "পৌঁছায়নি",
+ "pt-BR": "Não entregue",
+ "ru": "Не доставлено",
+ "id": "Tidak terkirim"
+ },
+ "Show these services on the phone": {
+ "zh-Hans": "在手机上显示这些服务",
+ "hi": "इन सेवाओं को फ़ोन पर दिखाएँ",
+ "es": "Mostrar estos servicios en el teléfono",
+ "ar": "عرض هذه الخدمات على الهاتف",
+ "fr": "Afficher ces services sur le téléphone",
+ "bn": "এই সার্ভিসগুলো ফোনে দেখান",
+ "pt-BR": "Mostrar estes serviços no celular",
+ "ru": "Показывать эти сервисы на телефоне",
+ "id": "Tampilkan layanan ini di ponsel"
+ },
+ "Each tick lets your paired phone see that service's card: a headline and up to three short lines, read-only. Nothing is shown until you tick it. No addresses, subjects, links or keys are ever sent.": {
+ "zh-Hans": "勾选后,已配对的手机即可查看该服务的卡片:一个标题和最多三行简短内容,只读。未勾选前不会显示任何内容。绝不会发送地址、主题、链接或密钥。",
+ "hi": "टिक करने पर आपका जोड़ा गया फ़ोन उस सेवा का कार्ड देख सकता है: एक शीर्षक और अधिकतम तीन छोटी पंक्तियाँ, केवल पढ़ने के लिए। टिक करने तक कुछ नहीं दिखता। पते, विषय, लिंक या कुंजियाँ कभी नहीं भेजी जातीं।",
+ "es": "Cada marca permite que tu teléfono emparejado vea la tarjeta de ese servicio: un titular y hasta tres líneas breves, solo lectura. No se muestra nada hasta que lo marques. Nunca se envían direcciones, asuntos, enlaces ni claves.",
+ "ar": "كل علامة تتيح لهاتفك المقترن رؤية بطاقة تلك الخدمة: عنوان وحتى ثلاثة أسطر قصيرة للقراءة فقط. لا يُعرض شيء حتى تضع العلامة. لا تُرسل أبدًا العناوين أو الموضوعات أو الروابط أو المفاتيح.",
+ "fr": "Chaque case permet à votre téléphone associé de voir la carte de ce service : un titre et jusqu'à trois courtes lignes, en lecture seule. Rien n'est montré tant que vous ne cochez pas. Aucune adresse, aucun objet, aucun lien ni aucune clé n'est jamais envoyé.",
+ "bn": "প্রতিটি টিকে আপনার যুক্ত করা ফোন ওই সার্ভিসের কার্ড দেখতে পারে: একটি শিরোনাম ও সর্বোচ্চ তিনটি ছোট লাইন, শুধু পড়ার জন্য। টিক না দেওয়া পর্যন্ত কিছুই দেখানো হয় না। ঠিকানা, বিষয়, লিঙ্ক বা কী কখনও পাঠানো হয় না।",
+ "pt-BR": "Cada marcação permite que seu celular pareado veja o cartão desse serviço: um título e até três linhas curtas, somente leitura. Nada aparece até você marcar. Endereços, assuntos, links ou chaves nunca são enviados.",
+ "ru": "Каждая отметка позволяет подключённому телефону видеть карточку сервиса: заголовок и до трёх коротких строк, только для чтения. Пока вы не отметите, ничего не показывается. Адреса, темы писем, ссылки и ключи не отправляются никогда.",
+ "id": "Setiap centang memungkinkan ponsel Anda yang terhubung melihat kartu layanan itu: satu judul dan hingga tiga baris pendek, hanya-baca. Tidak ada yang ditampilkan sebelum Anda mencentangnya. Alamat, subjek, tautan, atau kunci tidak pernah dikirim."
+ },
+ "The link you copied contains the pairing code: anyone who gets it can pair a phone with this computer. If it ends up somewhere it should not, press Pair again to make a new code; the old one stops working.": {
+ "zh-Hans": "您复制的链接包含配对码:任何拿到它的人都可以将手机与这台电脑配对。如果它出现在不该出现的地方,请点击“重新配对”生成新的配对码;旧的配对码将失效。",
+ "hi": "आपने जो लिंक कॉपी किया है उसमें पेयरिंग कोड है: जिसे भी यह मिले वह किसी फ़ोन को इस कंप्यूटर से पेयर कर सकता है। अगर यह कहीं ग़लत जगह पहुँच जाए तो “दोबारा पेयर करें” दबाकर नया कोड बनाएँ; पुराना कोड काम करना बंद कर देगा।",
+ "es": "El enlace que copiaste contiene el código de emparejamiento: quien lo consiga puede emparejar un teléfono con este ordenador. Si acaba donde no debe, pulsa Emparejar de nuevo para crear un código nuevo; el anterior deja de funcionar.",
+ "ar": "الرابط الذي نسخته يحتوي على رمز الإقران: يمكن لأي شخص يحصل عليه إقران هاتف بهذا الكمبيوتر. إذا وصل إلى مكان غير مناسب، فاضغط «إقران مجددًا» لإنشاء رمز جديد؛ وسيتوقف الرمز القديم عن العمل.",
+ "fr": "Le lien que vous avez copié contient le code de jumelage : quiconque l'obtient peut jumeler un téléphone avec cet ordinateur. S'il se retrouve où il ne devrait pas, appuyez sur Jumeler à nouveau pour créer un nouveau code ; l'ancien cessera de fonctionner.",
+ "bn": "আপনি যে লিঙ্কটি কপি করেছেন তাতে পেয়ারিং কোড আছে: যে কেউ এটি পেলে এই কম্পিউটারের সাথে একটি ফোন পেয়ার করতে পারবে। এটি অনুপযুক্ত জায়গায় চলে গেলে “আবার পেয়ার করুন” চাপুন নতুন কোড তৈরি করতে; পুরনো কোড আর কাজ করবে না।",
+ "pt-BR": "O link que você copiou contém o código de pareamento: quem o obtiver pode parear um celular com este computador. Se ele for parar onde não deveria, toque em Parear de novo para gerar um código novo; o antigo deixa de funcionar.",
+ "ru": "Скопированная ссылка содержит код сопряжения: любой, кто её получит, сможет связать телефон с этим компьютером. Если ссылка попала не туда, нажмите «Связать заново», чтобы создать новый код; старый перестанет работать.",
+ "id": "Tautan yang Anda salin berisi kode pemasangan: siapa pun yang mendapatkannya dapat memasangkan ponsel ke komputer ini. Jika tautan itu sampai ke tempat yang tidak semestinya, tekan Pasangkan lagi untuk membuat kode baru; kode lama berhenti berfungsi."
+ },
+ "Reaching the relay…": {
+ "zh-Hans": "正在连接中继…",
+ "hi": "रिले से जुड़ रहा है…",
+ "es": "Conectando con el relé…",
+ "ar": "جارٍ الاتصال بالمرحّل…",
+ "fr": "Connexion au relais…",
+ "bn": "রিলেতে সংযোগ হচ্ছে…",
+ "pt-BR": "Conectando ao relay…",
+ "ru": "Подключение к ретранслятору…",
+ "id": "Menghubungi relay…"
+ },
+ "Connected to the relay, waiting for the phone.": {
+ "zh-Hans": "已连接到中继,正在等待手机。",
+ "hi": "रिले से जुड़ गया, फ़ोन की प्रतीक्षा है।",
+ "es": "Conectado al relé, esperando al teléfono.",
+ "ar": "تم الاتصال بالمرحّل، في انتظار الهاتف.",
+ "fr": "Connecté au relais, en attente du téléphone.",
+ "bn": "রিলেতে সংযুক্ত, ফোনের অপেক্ষায়।",
+ "pt-BR": "Conectado ao relay, aguardando o celular.",
+ "ru": "Подключено к ретранслятору, ожидание телефона.",
+ "id": "Terhubung ke relay, menunggu ponsel."
+ },
+ "The phone is connected through the relay.": {
+ "zh-Hans": "手机已通过中继连接。",
+ "hi": "फ़ोन रिले के ज़रिए जुड़ा है।",
+ "es": "El teléfono está conectado a través del relé.",
+ "ar": "الهاتف متصل عبر المرحّل.",
+ "fr": "Le téléphone est connecté via le relais.",
+ "bn": "ফোন রিলের মাধ্যমে সংযুক্ত।",
+ "pt-BR": "O celular está conectado pelo relay.",
+ "ru": "Телефон подключён через ретранслятор.",
+ "id": "Ponsel terhubung melalui relay."
+ },
+ "The relay refused the access key.": {
+ "zh-Hans": "中继拒绝了该访问密钥。",
+ "hi": "रिले ने एक्सेस की अस्वीकार कर दी।",
+ "es": "El relé rechazó la clave de acceso.",
+ "ar": "رفض المرحّل مفتاح الوصول.",
+ "fr": "Le relais a refusé la clé d'accès.",
+ "bn": "রিলে অ্যাক্সেস কী প্রত্যাখ্যান করেছে।",
+ "pt-BR": "O relay recusou a chave de acesso.",
+ "ru": "Ретранслятор отклонил ключ доступа.",
+ "id": "Relay menolak kunci akses."
+ },
+ "The relay cannot be reached. Trying again.": {
+ "zh-Hans": "无法连接到中继,正在重试。",
+ "hi": "रिले तक नहीं पहुँचा जा सकता। फिर कोशिश की जा रही है।",
+ "es": "No se puede contactar con el relé. Reintentando.",
+ "ar": "يتعذّر الوصول إلى المرحّل. تتم إعادة المحاولة.",
+ "fr": "Le relais est injoignable. Nouvelle tentative.",
+ "bn": "রিলেতে পৌঁছানো যাচ্ছে না। আবার চেষ্টা করা হচ্ছে।",
+ "pt-BR": "Não foi possível alcançar o relay. Tentando novamente.",
+ "ru": "Ретранслятор недоступен. Повторная попытка.",
+ "id": "Relay tidak dapat dijangkau. Mencoba lagi."
+ },
+ "This pairing is in use somewhere else. Press Pair again.": {
+ "zh-Hans": "此配对正在别处使用。请点击“重新配对”。",
+ "hi": "यह पेयरिंग कहीं और उपयोग में है। “फिर से पेयर करें” दबाएँ।",
+ "es": "Este emparejamiento se está usando en otro sitio. Pulsa «Emparejar de nuevo».",
+ "ar": "هذا الاقتران مستخدم في مكان آخر. اضغط «إعادة الاقتران».",
+ "fr": "Cet appairage est utilisé ailleurs. Appuyez sur « Associer à nouveau ».",
+ "bn": "এই পেয়ারিং অন্য কোথাও ব্যবহৃত হচ্ছে। “আবার পেয়ার করুন” চাপুন।",
+ "pt-BR": "Este pareamento está em uso em outro lugar. Toque em «Parear de novo».",
+ "ru": "Это сопряжение используется где-то ещё. Нажмите «Сопрячь заново».",
+ "id": "Penyandingan ini dipakai di tempat lain. Tekan «Sandingkan ulang»."
+ },
+ "The relay is limiting connections from here. Trying again later.": {
+ "zh-Hans": "中继正在限制来自此处的连接,稍后重试。",
+ "hi": "रिले यहाँ से कनेक्शन सीमित कर रहा है। बाद में फिर कोशिश की जाएगी।",
+ "es": "El relé está limitando las conexiones desde aquí. Se reintentará más tarde.",
+ "ar": "يحدّ المرحّل من الاتصالات الواردة من هنا. ستتم إعادة المحاولة لاحقًا.",
+ "fr": "Le relais limite les connexions depuis ici. Nouvelle tentative plus tard.",
+ "bn": "রিলে এখান থেকে সংযোগ সীমিত করছে। পরে আবার চেষ্টা করা হবে।",
+ "pt-BR": "O relay está limitando as conexões daqui. Tentando de novo mais tarde.",
+ "ru": "Ретранслятор ограничивает подключения отсюда. Повтор позже.",
+ "id": "Relay membatasi koneksi dari sini. Mencoba lagi nanti."
+ },
+ "Off": {
+ "zh-Hans": "关",
+ "hi": "बंद",
+ "es": "Desactivado",
+ "ar": "متوقف",
+ "fr": "Désactivé",
+ "bn": "বন্ধ",
+ "pt-BR": "Desligado",
+ "ru": "Выключено",
+ "id": "Mati"
+ },
+ "Save address": {
+ "zh-Hans": "保存地址",
+ "hi": "पता सहेजें",
+ "es": "Guardar dirección",
+ "ar": "حفظ العنوان",
+ "fr": "Enregistrer l'adresse",
+ "bn": "ঠিকানা সংরক্ষণ করুন",
+ "pt-BR": "Salvar endereço",
+ "ru": "Сохранить адрес",
+ "id": "Simpan alamat"
+ },
+ "Away from home Wi-Fi": {
+ "zh-Hans": "不在家中 Wi-Fi 时",
+ "hi": "घर के Wi-Fi से दूर",
+ "es": "Fuera del Wi-Fi de casa",
+ "ar": "بعيدًا عن شبكة Wi-Fi المنزلية",
+ "fr": "Hors du Wi-Fi de la maison",
+ "bn": "বাড়ির Wi-Fi-এর বাইরে",
+ "pt-BR": "Fora do Wi-Fi de casa",
+ "ru": "Вне домашнего Wi-Fi",
+ "id": "Di luar Wi-Fi rumah"
+ },
+ "Reach this computer from your phone on mobile data or another network, through a relay you deployed yourself. Everything is encrypted end to end: the relay only forwards data it cannot read. Off by default.": {
+ "zh-Hans": "通过你自己部署的中继,让手机在移动数据或其他网络下也能连接此电脑。所有内容均为端到端加密:中继只转发它无法读取的数据。默认关闭。",
+ "hi": "अपने खुद के तैनात किए रिले के ज़रिए, मोबाइल डेटा या किसी दूसरे नेटवर्क पर अपने फ़ोन से इस कंप्यूटर तक पहुँचें। सब कुछ एंड-टू-एंड एन्क्रिप्टेड है: रिले केवल वह डेटा आगे भेजता है जिसे वह पढ़ नहीं सकता। डिफ़ॉल्ट रूप से बंद।",
+ "es": "Conecta tu teléfono con este ordenador con datos móviles u otra red, mediante un relé que has desplegado tú mismo. Todo va cifrado de extremo a extremo: el relé solo reenvía datos que no puede leer. Desactivado por defecto.",
+ "ar": "يمكنك الوصول إلى هذا الكمبيوتر من هاتفك عبر بيانات الجوال أو شبكة أخرى، من خلال مرحّل نشرتَه بنفسك. كل شيء مشفّر من طرف إلى طرف: المرحّل لا يمرّر سوى بيانات لا يستطيع قراءتها. متوقف افتراضيًا.",
+ "fr": "Joignez cet ordinateur depuis votre téléphone en données mobiles ou sur un autre réseau, via un relais que vous avez déployé vous-même. Tout est chiffré de bout en bout : le relais ne fait que transmettre des données qu'il ne peut pas lire. Désactivé par défaut.",
+ "bn": "আপনার নিজের স্থাপন করা রিলের মাধ্যমে মোবাইল ডেটা বা অন্য নেটওয়ার্কে থাকা ফোন থেকে এই কম্পিউটারে পৌঁছান। সবকিছু এন্ড-টু-এন্ড এনক্রিপ্টেড: রিলে শুধু এমন ডেটা এগিয়ে দেয় যা সে পড়তে পারে না। ডিফল্টভাবে বন্ধ।",
+ "pt-BR": "Acesse este computador pelo celular com dados móveis ou outra rede, usando um relay que você mesmo publicou. Tudo é criptografado de ponta a ponta: o relay só repassa dados que não consegue ler. Desligado por padrão.",
+ "ru": "Подключайтесь к этому компьютеру с телефона через мобильный интернет или другую сеть с помощью ретранслятора, который вы развернули сами. Всё шифруется сквозным шифрованием: ретранслятор лишь пересылает данные, которые не может прочитать. По умолчанию выключено.",
+ "id": "Jangkau komputer ini dari ponsel lewat data seluler atau jaringan lain, melalui relay yang Anda pasang sendiri. Semuanya terenkripsi ujung ke ujung: relay hanya meneruskan data yang tidak bisa dibacanya. Nonaktif secara bawaan."
+ },
+ "Relay address": {
+ "zh-Hans": "中继地址",
+ "hi": "रिले का पता",
+ "es": "Dirección del relé",
+ "ar": "عنوان المرحّل",
+ "fr": "Adresse du relais",
+ "bn": "রিলের ঠিকানা",
+ "pt-BR": "Endereço do relay",
+ "ru": "Адрес ретранслятора",
+ "id": "Alamat relay"
+ },
+ "Relay access key": {
+ "zh-Hans": "中继访问密钥",
+ "hi": "रिले एक्सेस की",
+ "es": "Clave de acceso del relé",
+ "ar": "مفتاح وصول المرحّل",
+ "fr": "Clé d'accès du relais",
+ "bn": "রিলের অ্যাক্সেস কী",
+ "pt-BR": "Chave de acesso do relay",
+ "ru": "Ключ доступа к ретранслятору",
+ "id": "Kunci akses relay"
+ },
+ "Paste the access key you set when you deployed the relay. It is kept in the system keystore and never shown again.": {
+ "zh-Hans": "粘贴部署中继时设置的访问密钥。它保存在系统密钥库中,之后不会再显示。",
+ "hi": "रिले तैनात करते समय आपने जो एक्सेस की सेट की थी उसे चिपकाएँ। यह सिस्टम कीस्टोर में रखी जाती है और दोबारा नहीं दिखाई जाती।",
+ "es": "Pega la clave de acceso que definiste al desplegar el relé. Se guarda en el almacén de claves del sistema y no se vuelve a mostrar.",
+ "ar": "الصق مفتاح الوصول الذي عيّنتَه عند نشر المرحّل. يُحفظ في مخزن مفاتيح النظام ولا يُعرض مرة أخرى.",
+ "fr": "Collez la clé d'accès définie lors du déploiement du relais. Elle est conservée dans le trousseau du système et n'est plus jamais affichée.",
+ "bn": "রিলে স্থাপনের সময় যে অ্যাক্সেস কী সেট করেছিলেন তা পেস্ট করুন। এটি সিস্টেম কীস্টোরে থাকে এবং আর দেখানো হয় না।",
+ "pt-BR": "Cole a chave de acesso definida ao publicar o relay. Ela fica no cofre de chaves do sistema e nunca é mostrada novamente.",
+ "ru": "Вставьте ключ доступа, заданный при развёртывании ретранслятора. Он хранится в системном хранилище ключей и больше не показывается.",
+ "id": "Tempel kunci akses yang Anda atur saat memasang relay. Kunci disimpan di penyimpanan kunci sistem dan tidak ditampilkan lagi."
+ },
+ "This code also carries the access key and the end-to-end key for the relay {host}. Pair again makes a new key and a new room.": {
+ "zh-Hans": "此代码还包含中继 {host} 的访问密钥和端到端密钥。“重新配对”会生成新的密钥和新的房间。",
+ "hi": "इस कोड में रिले {host} की एक्सेस की और एंड-टू-एंड कुंजी भी है। “फिर से पेयर करें” नई कुंजी और नया रूम बनाता है।",
+ "es": "Este código también incluye la clave de acceso y la clave de extremo a extremo del relé {host}. «Emparejar de nuevo» crea una clave y una sala nuevas.",
+ "ar": "يتضمن هذا الرمز أيضًا مفتاح الوصول والمفتاح الطرفي للمرحّل {host}. «إعادة الاقتران» تنشئ مفتاحًا وغرفة جديدين.",
+ "fr": "Ce code contient aussi la clé d'accès et la clé de bout en bout du relais {host}. « Associer à nouveau » crée une nouvelle clé et une nouvelle salle.",
+ "bn": "এই কোডে রিলে {host}-এর অ্যাক্সেস কী ও এন্ড-টু-এন্ড কী-ও আছে। “আবার পেয়ার করুন” নতুন কী ও নতুন রুম তৈরি করে।",
+ "pt-BR": "Este código também inclui a chave de acesso e a chave de ponta a ponta do relay {host}. «Parear de novo» cria uma chave e uma sala novas.",
+ "ru": "Этот код также содержит ключ доступа и сквозной ключ для ретранслятора {host}. «Сопрячь заново» создаёт новый ключ и новую комнату.",
+ "id": "Kode ini juga memuat kunci akses dan kunci ujung ke ujung untuk relay {host}. «Sandingkan ulang» membuat kunci dan ruang baru."
}
}
}
diff --git a/windows/src/i18n/strings.json b/windows/src/i18n/strings.json
index e5a98f79..b844d463 100644
--- a/windows/src/i18n/strings.json
+++ b/windows/src/i18n/strings.json
@@ -24,6 +24,17 @@
"ru": " готов.",
"id": " siap."
},
+ "4 active — remove which?": {
+ "zh-Hans": "4 个激活 — 删除哪个?",
+ "hi": "4 सक्रिय — कौन सा हटाएं?",
+ "es": "4 activas — ¿cuál quitar?",
+ "ar": "4 نشطة — أيها أزيل؟",
+ "fr": "4 actives — laquelle retirer ?",
+ "bn": "4টি সক্রিয় — কোনটি সরাবো?",
+ "pt-BR": "4 ativas — qual remover?",
+ "ru": "4 активно — что удалить?",
+ "id": "4 aktif — mana yang dihapus?"
+ },
"5 hours": {
"zh-Hans": "5 小时",
"hi": "5 घंटे",
@@ -101,6 +112,17 @@
"ru": "Активность",
"id": "Aktivitas"
},
+ "Add your Anthropic API key in Settings → Chat first.": {
+ "zh-Hans": "请先在设置 → 聊天中添加你的 Anthropic API 密钥。",
+ "hi": "पहले सेटिंग्स → चैट में अपनी Anthropic API कुंजी जोड़ो।",
+ "es": "Primero añade tu clave de API de Anthropic en Ajustes → Chat.",
+ "ar": "أضف أولًا مفتاح Anthropic API في الإعدادات ← الدردشة.",
+ "fr": "Ajoute d'abord ta clé API Anthropic dans Réglages → Chat.",
+ "bn": "আগে সেটিংস → চ্যাটে তোমার Anthropic API কী যোগ করো।",
+ "pt-BR": "Primeiro adicione sua chave de API da Anthropic em Ajustes → Chat.",
+ "ru": "Сначала добавь ключ Anthropic API в Настройки → Чат.",
+ "id": "Tambahkan dulu kunci API Anthropic-mu di Pengaturan → Chat."
+ },
"Advertisement": {
"zh-Hans": "广告",
"hi": "विज्ञापन",
@@ -112,6 +134,17 @@
"ru": "Реклама",
"id": "Iklan"
},
+ "After «OK Coucou», what you say goes to Claude with your Anthropic API key, with what Coucou reads to answer (your pills, your services' data, a contact's address). It acts and searches the web. Never audio.": {
+ "zh-Hans": "说「OK Coucou」后,你说的话会用你的 Anthropic API 密钥发送给 Claude,同时发送 Coucou 为回答而读取的内容(你的药丸、你的服务数据、联系人地址)。它会执行操作并进行网页搜索。从不发送音频。",
+ "hi": "«OK Coucou» के बाद तुम जो कहते हो वह तुम्हारी Anthropic API कुंजी से Claude को जाता है, साथ में वह जो Coucou जवाब देने के लिए पढ़ता है (तुम्हारी पिल्स, तुम्हारी सेवाओं का डेटा, किसी संपर्क का पता)। वह काम करता है और वेब पर खोजता है। ऑडियो कभी नहीं।",
+ "es": "Tras «OK Coucou», lo que dices va a Claude con tu clave de API de Anthropic, junto con lo que Coucou lee para responder (tus píldoras, los datos de tus servicios, la dirección de un contacto). Actúa y busca en la web. Nunca el audio.",
+ "ar": "بعد «OK Coucou»، يُرسل ما تقوله إلى Claude بمفتاح Anthropic API الخاص بك، مع ما يقرؤه Coucou للإجابة (حبوبك، بيانات خدماتك، عنوان جهة اتصال). ينفّذ ويبحث على الويب. لا يُرسل الصوت أبدًا.",
+ "fr": "Après « OK Coucou », ce que tu dis part chez Claude avec ta clé API Anthropic, avec ce que Coucou lit pour répondre (tes pilules, les données de tes services, l'adresse d'un contact). Il agit et cherche sur le web. Jamais l'audio.",
+ "bn": "«OK Coucou»-এর পরে তুমি যা বলো তা তোমার Anthropic API কী দিয়ে Claude-এর কাছে যায়, সঙ্গে Coucou উত্তর দিতে যা পড়ে (তোমার পিল, তোমার সার্ভিসের ডেটা, কোনো কন্টাক্টের ঠিকানা)। সে কাজ করে আর ওয়েবে খোঁজে। অডিও কখনো নয়।",
+ "pt-BR": "Depois de «OK Coucou», o que você diz vai para o Claude com sua chave de API da Anthropic, junto com o que o Coucou lê para responder (suas pílulas, os dados dos seus serviços, o endereço de um contato). Ele age e pesquisa na web. Nunca o áudio.",
+ "ru": "После «OK Coucou» сказанное уходит в Claude по твоему ключу Anthropic API вместе с тем, что Coucou читает для ответа (твои пилюли, данные твоих сервисов, адрес контакта). Он действует и ищет в интернете. Звук — никогда.",
+ "id": "Setelah «OK Coucou», ucapanmu dikirim ke Claude dengan kunci API Anthropic-mu, beserta apa yang dibaca Coucou untuk menjawab (pil-mu, data layananmu, alamat kontak). Ia bertindak dan mencari di web. Tidak pernah audio."
+ },
"Agent": {
"zh-Hans": "代理",
"hi": "एजेंट",
@@ -167,6 +200,17 @@
"ru": "Разрешить Coucou управлять Spotify",
"id": "Izinkan Coucou mengontrol Spotify"
},
+ "Already active": {
+ "zh-Hans": "已激活",
+ "hi": "पहले से सक्रिय",
+ "es": "Ya activo",
+ "ar": "مفعّل بالفعل",
+ "fr": "Déjà actif",
+ "bn": "ইতিমধ্যে সক্রিয়",
+ "pt-BR": "Já ativo",
+ "ru": "Уже активно",
+ "id": "Sudah aktif"
+ },
"Always": {
"zh-Hans": "始终允许",
"hi": "हमेशा",
@@ -332,6 +376,17 @@
"ru": "Автозакрытие · {seconds} с",
"id": "Tutup otomatis · {seconds}dt"
},
+ "Automatic (your Mac’s dictation language)": {
+ "zh-Hans": "自动(Mac 听写语言)",
+ "hi": "स्वचालित (Mac की डिक्टेशन भाषा)",
+ "es": "Automático (idioma de dictado del Mac)",
+ "ar": "تلقائي (لغة الإملاء في الماك)",
+ "fr": "Automatique (langue de dictée du Mac)",
+ "bn": "স্বয়ংক্রিয় (Mac-এর ডিক্টেশনের ভাষা)",
+ "pt-BR": "Automático (idioma de ditado do Mac)",
+ "ru": "Автоматически (язык диктовки Mac)",
+ "id": "Otomatis (bahasa dikte Mac)"
+ },
"Automation not allowed": {
"zh-Hans": "不允许自动化",
"hi": "स्वचालन की अनुमति नहीं",
@@ -442,6 +497,17 @@
"ru": "Выбери инструменты, которые ты используешь. Coucou показывает только то, что ты здесь объявишь.",
"id": "Pilih alat yang Anda gunakan. Coucou hanya menampilkan yang Anda deklarasikan di sini."
},
+ "City": {
+ "zh-Hans": "城市",
+ "hi": "शहर",
+ "es": "Ciudad",
+ "ar": "المدينة",
+ "fr": "Ville",
+ "bn": "শহর",
+ "pt-BR": "Cidade",
+ "ru": "Город",
+ "id": "Kota"
+ },
"Classic token with repo scope, or fine-grained with read access to Pull requests, commit statuses, and Actions.": {
"zh-Hans": "具有 repo 权限的经典令牌,或具有 Pull requests、Commit statuses 和 Actions 读取权限的细粒度令牌。",
"hi": "repo स्कोप के साथ क्लासिक टोकन, या Pull requests, Commit statuses और Actions में रीड एक्सेस के साथ फाइन-ग्रेन्ड टोकन।",
@@ -486,6 +552,17 @@
"ru": "Claude Code спрашивает",
"id": "Claude Code bertanya"
},
+ "Claude as Coucou's brain": {
+ "zh-Hans": "由 Claude 担任 Coucou 的大脑",
+ "hi": "Coucou का दिमाग: Claude",
+ "es": "Claude como cerebro de Coucou",
+ "ar": "Claude عقل Coucou",
+ "fr": "Claude comme cerveau de Coucou",
+ "bn": "Coucou-র মস্তিষ্ক: Claude",
+ "pt-BR": "Claude como cérebro do Coucou",
+ "ru": "Claude — мозг Coucou",
+ "id": "Claude sebagai otak Coucou"
+ },
"Claude is reading {name}…": {
"zh-Hans": "Claude 正在读取 {name}…",
"hi": "Claude {name} पढ़ रहा है…",
@@ -607,6 +684,17 @@
"ru": "Скоро",
"id": "Segera hadir"
},
+ "Command not recognised": {
+ "zh-Hans": "无法识别指令",
+ "hi": "आदेश पहचाना नहीं",
+ "es": "Comando no reconocido",
+ "ar": "الأمر غير مُتعرَّف عليه",
+ "fr": "Commande non reconnue",
+ "bn": "কমান্ড চেনা যায়নি",
+ "pt-BR": "Comando não reconhecido",
+ "ru": "Команда не распознана",
+ "id": "Perintah tidak dikenali"
+ },
"Completed successfully.": {
"zh-Hans": "已成功完成。",
"hi": "सफलतापूर्वक पूर्ण हुआ।",
@@ -717,6 +805,39 @@
"ru": "Скопировать",
"id": "Salin"
},
+ "Coucou answers in": {
+ "zh-Hans": "Coucou 回答语言",
+ "hi": "Coucou जवाब देता है",
+ "es": "Coucou responde en",
+ "ar": "Coucou يجيب بـ",
+ "fr": "Coucou répond en",
+ "bn": "Coucou উত্তর দেয়",
+ "pt-BR": "Coucou responde em",
+ "ru": "Coucou отвечает на",
+ "id": "Coucou menjawab dalam"
+ },
+ "Coucou reads back results in the spoken language, using a synthesized voice. 100% on-device.": {
+ "zh-Hans": "Coucou 用语音语言朗读结果。完全在设备上处理。",
+ "hi": "Coucou बोली जाने वाली भाषा में परिणाम पढ़ता है। सब कुछ डिवाइस पर।",
+ "es": "Coucou lee los resultados en el idioma hablado con una voz sintetizada. Todo en el dispositivo.",
+ "ar": "يقرأ كوكو النتائج باللغة المنطوقة باستخدام صوت مُركَّب. كل شيء يتم على الجهاز.",
+ "fr": "Coucou lit les résultats dans la langue parlée. Tout se passe sur l'appareil.",
+ "bn": "Coucou কথ্য ভাষায় ফলাফল পড়ে। সবকিছু ডিভাইসেই হয়।",
+ "pt-BR": "Coucou lê os resultados no idioma falado. Tudo no dispositivo.",
+ "ru": "Coucou зачитывает результаты на языке команды. Всё на устройстве.",
+ "id": "Coucou membaca hasil dalam bahasa yang diucapkan. Semuanya di perangkat."
+ },
+ "Coucou responds aloud": {
+ "zh-Hans": "Coucou 大声回应",
+ "hi": "Coucou ज़ोर से जवाब देता है",
+ "es": "Coucou responde en voz alta",
+ "ar": "كوكو يرد بصوت عالٍ",
+ "fr": "Coucou répond à voix haute",
+ "bn": "Coucou জোরে জবাব দেয়",
+ "pt-BR": "Coucou responde em voz alta",
+ "ru": "Coucou отвечает вслух",
+ "id": "Coucou merespons dengan suara"
+ },
"Custom…": {
"zh-Hans": "自定义…",
"hi": "कस्टम…",
@@ -882,6 +1003,17 @@
"ru": "Редактирует",
"id": "Mengedit"
},
+ "ElevenLabs API key": {
+ "zh-Hans": "ElevenLabs API 密钥",
+ "hi": "ElevenLabs API कुंजी",
+ "es": "Clave API de ElevenLabs",
+ "ar": "مفتاح ElevenLabs API",
+ "fr": "Clé API ElevenLabs",
+ "bn": "ElevenLabs API কী",
+ "pt-BR": "Chave de API ElevenLabs",
+ "ru": "API-ключ ElevenLabs",
+ "id": "Kunci API ElevenLabs"
+ },
"Emails": {
"zh-Hans": "邮件",
"hi": "ईमेल",
@@ -904,6 +1036,17 @@
"ru": "Включить звуки",
"id": "Aktifkan suara"
},
+ "Enable voice command": {
+ "zh-Hans": "启用语音命令",
+ "hi": "वॉइस कमांड सक्षम करें",
+ "es": "Activar comando de voz",
+ "ar": "تفعيل الأوامر الصوتية",
+ "fr": "Activer la commande vocale",
+ "bn": "ভয়েস কমান্ড সক্ষম করুন",
+ "pt-BR": "Ativar comando de voz",
+ "ru": "Включить голосовые команды",
+ "id": "Aktifkan perintah suara"
+ },
"Explore all features without an API key or Claude Code. Nothing is written to disk.": {
"zh-Hans": "无需 API 密钥或 Claude Code,探索所有功能。不会写入任何内容到磁盘。",
"hi": "API कुंजी या Claude Code के बिना सभी सुविधाएँ एक्सप्लोर करें। डिस्क पर कुछ नहीं लिखा जाता।",
@@ -959,6 +1102,28 @@
"ru": "Получает",
"id": "Mengambil"
},
+ "For a more natural voice, download a Premium voice: System Settings → Accessibility → Spoken Content → System Voice → Manage Voices. In English: Ava for a woman, Jamie for a man (British).": {
+ "zh-Hans": "想要更自然的声音,请下载 Premium 语音:系统设置 → 辅助功能 → 朗读内容 → 系统语音 → 管理语音。英语:女声选 Ava,男声选 Jamie(英式)。",
+ "hi": "ज़्यादा स्वाभाविक आवाज़ के लिए Premium आवाज़ डाउनलोड करें: System Settings → Accessibility → Spoken Content → System Voice → Manage Voices। अंग्रेज़ी में: महिला के लिए Ava, पुरुष के लिए Jamie (ब्रिटिश)।",
+ "es": "Para una voz más natural, descarga una voz Premium: Ajustes del Sistema → Accesibilidad → Contenido leído → Voz del sistema → Gestionar voces. En inglés: Ava para mujer, Jamie para hombre (británico).",
+ "ar": "لصوت أكثر طبيعية، نزّل صوتًا Premium: إعدادات النظام ← تسهيلات الاستخدام ← المحتوى المنطوق ← صوت النظام ← إدارة الأصوات. بالإنجليزية: Ava لامرأة، Jamie لرجل (بريطاني).",
+ "fr": "Pour une voix plus naturelle, télécharge une voix Premium : Réglages Système → Accessibilité → Contenu énoncé → Voix du système → Gérer les voix. En anglais : Ava pour une femme, Jamie pour un homme (britannique).",
+ "bn": "আরও স্বাভাবিক কণ্ঠের জন্য একটি Premium কণ্ঠ ডাউনলোড করো: System Settings → Accessibility → Spoken Content → System Voice → Manage Voices। ইংরেজিতে: নারী হলে Ava, পুরুষ হলে Jamie (ব্রিটিশ)।",
+ "pt-BR": "Para uma voz mais natural, baixe uma voz Premium: Ajustes do Sistema → Acessibilidade → Conteúdo Falado → Voz do Sistema → Gerenciar Vozes. Em inglês: Ava para mulher, Jamie para homem (britânico).",
+ "ru": "Для более естественного голоса скачай голос Premium: Системные настройки → Универсальный доступ → Устная речь → Системный голос → Управлять голосами. По-английски: Ava — женский, Jamie — мужской (британский).",
+ "id": "Untuk suara yang lebih alami, unduh suara Premium: Pengaturan Sistem → Aksesibilitas → Konten Lisan → Suara Sistem → Kelola Suara. Bahasa Inggris: Ava untuk wanita, Jamie untuk pria (Inggris)."
+ },
+ "From Open-Meteo for this city, only when you ask.": {
+ "zh-Hans": "仅在你询问时,从 Open-Meteo 获取该城市的天气。",
+ "hi": "इस शहर के लिए Open-Meteo से, सिर्फ़ पूछने पर।",
+ "es": "De Open-Meteo para esta ciudad, solo cuando preguntas.",
+ "ar": "من Open-Meteo لهذه المدينة، فقط عندما تسأل.",
+ "fr": "Open-Meteo pour cette ville, seulement quand tu demandes.",
+ "bn": "এই শহরের জন্য Open-Meteo থেকে, শুধু জিজ্ঞেস করলে।",
+ "pt-BR": "Do Open-Meteo para esta cidade, só quando você pergunta.",
+ "ru": "Из Open-Meteo для этого города, только когда спрашиваешь.",
+ "id": "Dari Open-Meteo untuk kota ini, hanya saat kamu bertanya."
+ },
"Gemini CLI hooks": {
"zh-Hans": "Gemini CLI 钩子",
"hi": "Gemini CLI हुक",
@@ -1080,6 +1245,17 @@
"ru": "Google AI",
"id": "Google AI"
},
+ "Granted": {
+ "zh-Hans": "已授权",
+ "hi": "अनुमत",
+ "es": "Concedido",
+ "ar": "ممنوح",
+ "fr": "Accordé",
+ "bn": "অনুমোদিত",
+ "pt-BR": "Concedido",
+ "ru": "Разрешено",
+ "id": "Diberikan"
+ },
"Hermes Agent": {
"zh-Hans": "Hermes Agent",
"hi": "Hermes Agent",
@@ -1344,6 +1520,17 @@
"ru": "Ключ не настроен",
"id": "Kunci belum dikonfigurasi"
},
+ "Key saved in Keychain": {
+ "zh-Hans": "密钥已存入钥匙串",
+ "hi": "कुंजी कीचेन में सहेजी गई",
+ "es": "Clave guardada en el llavero",
+ "ar": "المفتاح محفوظ في سلسلة المفاتيح",
+ "fr": "Clé enregistrée dans le Trousseau",
+ "bn": "কী কিচেইনে সংরক্ষিত",
+ "pt-BR": "Chave salva nas Chaves",
+ "ru": "Ключ сохранён в Связке ключей",
+ "id": "Kunci tersimpan di Keychain"
+ },
"LM Studio disconnected.": {
"zh-Hans": "LM Studio 已断开连接。",
"hi": "LM Studio डिस्कनेक्ट हो गया।",
@@ -1388,6 +1575,17 @@
"ru": "Позволять iPhone отправлять инструкции в Claude Code",
"id": "Biarkan iPhone saya mengirim instruksi ke Claude Code"
},
+ "Listening…": {
+ "zh-Hans": "我在听…",
+ "hi": "सुन रहा हूँ…",
+ "es": "Te escucho…",
+ "ar": "أنا أستمع…",
+ "fr": "Je t’écoute…",
+ "bn": "শুনছি…",
+ "pt-BR": "Estou ouvindo…",
+ "ru": "Слушаю…",
+ "id": "Mendengarkan…"
+ },
"Lists": {
"zh-Hans": "列出",
"hi": "सूची",
@@ -1421,6 +1619,50 @@
"ru": "Загрузка…",
"id": "Memuat…"
},
+ "Local AI model: Apple Intelligence is off": {
+ "zh-Hans": "本地 AI 模型:Apple Intelligence 已关闭",
+ "hi": "स्थानीय AI मॉडल: Apple Intelligence बंद है",
+ "es": "Modelo de IA local: Apple Intelligence está desactivado",
+ "ar": "نموذج الذكاء الاصطناعي المحلي: Apple Intelligence معطَّل",
+ "fr": "Modèle IA local : Apple Intelligence est désactivée",
+ "bn": "স্থানীয় AI মডেল: Apple Intelligence বন্ধ আছে",
+ "pt-BR": "Modelo de IA local: Apple Intelligence está desativado",
+ "ru": "Локальная модель ИИ: Apple Intelligence отключена",
+ "id": "Model AI lokal: Apple Intelligence dimatikan"
+ },
+ "Local AI model: available": {
+ "zh-Hans": "本地 AI 模型:可用",
+ "hi": "स्थानीय AI मॉडल: उपलब्ध",
+ "es": "Modelo de IA local: disponible",
+ "ar": "نموذج الذكاء الاصطناعي المحلي: متاح",
+ "fr": "Modèle IA local : disponible",
+ "bn": "স্থানীয় AI মডেল: উপলব্ধ",
+ "pt-BR": "Modelo de IA local: disponível",
+ "ru": "Локальная модель ИИ: доступна",
+ "id": "Model AI lokal: tersedia"
+ },
+ "Local AI model: language not supported": {
+ "zh-Hans": "本地 AI 模型:不支持该语言",
+ "hi": "स्थानीय AI मॉडल: भाषा समर्थित नहीं है",
+ "es": "Modelo de IA local: idioma no compatible",
+ "ar": "نموذج الذكاء الاصطناعي المحلي: اللغة غير مدعومة",
+ "fr": "Modèle IA local : langue non prise en charge",
+ "bn": "স্থানীয় AI মডেল: ভাষা সমর্থিত নয়",
+ "pt-BR": "Modelo de IA local: idioma não suportado",
+ "ru": "Локальная модель ИИ: язык не поддерживается",
+ "id": "Model AI lokal: bahasa tidak didukung"
+ },
+ "Local AI model: requires macOS 26 or later": {
+ "zh-Hans": "本地 AI 模型:需要 macOS 26 或更高版本",
+ "hi": "स्थानीय AI मॉडल: macOS 26 या बाद का संस्करण आवश्यक है",
+ "es": "Modelo de IA local: requiere macOS 26 o posterior",
+ "ar": "نموذج الذكاء الاصطناعي المحلي: يتطلب macOS 26 أو أحدث",
+ "fr": "Modèle IA local : nécessite macOS 26 ou plus",
+ "bn": "স্থানীয় AI মডেল: macOS 26 বা তার পরবর্তী প্রয়োজন",
+ "pt-BR": "Modelo de IA local: requer macOS 26 ou posterior",
+ "ru": "Локальная модель ИИ: требуется macOS 26 или новее",
+ "id": "Model AI lokal: membutuhkan macOS 26 atau lebih baru"
+ },
"Local models": {
"zh-Hans": "本地模型",
"hi": "स्थानीय मॉडल",
@@ -1443,6 +1685,17 @@
"ru": "Самая долгая сессия",
"id": "Sesi terpanjang"
},
+ "Mac voice": {
+ "zh-Hans": "Mac 语音",
+ "hi": "Mac की आवाज़",
+ "es": "Voz del Mac",
+ "ar": "صوت الماك",
+ "fr": "Voix du Mac",
+ "bn": "Mac-এর কণ্ঠ",
+ "pt-BR": "Voz do Mac",
+ "ru": "Голос Mac",
+ "id": "Suara Mac"
+ },
"Mail not available.": {
"zh-Hans": "邮件不可用。",
"hi": "मेल उपलब्ध नहीं है।",
@@ -1465,6 +1718,50 @@
"ru": "Главный",
"id": "Utama"
},
+ "Main: {0}": {
+ "zh-Hans": "主要:{0}",
+ "hi": "मुख्य: {0}",
+ "es": "Principal: {0}",
+ "ar": "الرئيسي: {0}",
+ "fr": "Principal : {0}",
+ "bn": "মূল: {0}",
+ "pt-BR": "Principal: {0}",
+ "ru": "Главный: {0}",
+ "id": "Utama: {0}"
+ },
+ "Man": {
+ "zh-Hans": "男声",
+ "hi": "पुरुष",
+ "es": "Hombre",
+ "ar": "رجل",
+ "fr": "Homme",
+ "bn": "পুরুষ",
+ "pt-BR": "Homem",
+ "ru": "Мужской",
+ "id": "Pria"
+ },
+ "Microphone unavailable": {
+ "zh-Hans": "麦克风不可用",
+ "hi": "माइक्रोफ़ोन अनुपलब्ध",
+ "es": "Micrófono no disponible",
+ "ar": "الميكروفون غير متاح",
+ "fr": "Microphone indisponible",
+ "bn": "মাইক্রোফোন অনুপলব্ধ",
+ "pt-BR": "Microfone indisponível",
+ "ru": "Микрофон недоступен",
+ "id": "Mikrofon tidak tersedia"
+ },
+ "Microphone:": {
+ "zh-Hans": "麦克风:",
+ "hi": "माइक्रोफ़ोन:",
+ "es": "Micrófono:",
+ "ar": "الميكروفون:",
+ "fr": "Microphone :",
+ "bn": "মাইক্রোফোন:",
+ "pt-BR": "Microfone:",
+ "ru": "Микрофон:",
+ "id": "Mikrofon:"
+ },
"Missing recipient.": {
"zh-Hans": "收件人缺失。",
"hi": "प्राप्तकर्ता गुम है।",
@@ -1619,6 +1916,17 @@
"ru": "Следующая вкладка",
"id": "Tab berikutnya"
},
+ "Next track": {
+ "zh-Hans": "下一首",
+ "hi": "अगला ट्रैक",
+ "es": "Siguiente pista",
+ "ar": "المقطع التالي",
+ "fr": "Morceau suivant",
+ "bn": "পরবর্তী ট্র্যাক",
+ "pt-BR": "Próxima faixa",
+ "ru": "Следующий трек",
+ "id": "Lagu berikutnya"
+ },
"No activity last week": {
"zh-Hans": "上周无活动",
"hi": "पिछले सप्ताह कोई गतिविधि नहीं",
@@ -1685,6 +1993,39 @@
"ru": "Нет моделей — скачай одну в {name} сначала.",
"id": "Belum ada model — unduh satu di {name} terlebih dahulu."
},
+ "No music app running": {
+ "zh-Hans": "没有音乐应用",
+ "hi": "कोई म्यूज़िक ऐप नहीं",
+ "es": "Sin app de música",
+ "ar": "لا يوجد تطبيق موسيقى",
+ "fr": "Aucune app musicale active",
+ "bn": "কোনো মিউজিক অ্যাপ নেই",
+ "pt-BR": "Nenhum app de música",
+ "ru": "Нет музыкального приложения",
+ "id": "Tidak ada app musik"
+ },
+ "No speech recognition model available on this device. Install one in System Settings → Keyboard → Dictation.": {
+ "zh-Hans": "此设备上没有可用的语音识别模型。在系统设置 → 键盘 → 听写中安装一个。",
+ "hi": "इस डिवाइस पर कोई वाक् पहचान मॉडल उपलब्ध नहीं है। सिस्टम सेटिंग्स → कीबोर्ड → डिक्टेशन में एक इंस्टॉल करें।",
+ "es": "No hay modelo de reconocimiento de voz disponible en este dispositivo. Instala uno en Ajustes del Sistema → Teclado → Dictado.",
+ "ar": "لا يوجد نموذج للتعرف على الكلام متاح على هذا الجهاز. قم بتثبيت واحد في إعدادات النظام → لوحة المفاتيح → الإملاء.",
+ "fr": "Aucun modèle de reconnaissance vocale disponible sur cet appareil. Installez un modèle dans Réglages Système → Clavier → Dictée.",
+ "bn": "এই ডিভাইসে কোনো বক্তৃতা স্বীকৃতি মডেল পাওয়া যায়নি। সিস্টেম সেটিংস → কীবোর্ড → ডিকটেশনে একটি ইনস্টল করুন।",
+ "pt-BR": "Nenhum modelo de reconhecimento de fala disponível neste dispositivo. Instale um em Ajustes do Sistema → Teclado → Ditado.",
+ "ru": "На этом устройстве нет доступной модели распознавания речи. Установите её в Системных настройках → Клавиатура → Диктовка.",
+ "id": "Tidak ada model pengenalan ucapan yang tersedia di perangkat ini. Instal satu di Pengaturan Sistem → Keyboard → Dikte."
+ },
+ "Not active": {
+ "zh-Hans": "未激活",
+ "hi": "सक्रिय नहीं",
+ "es": "No activo",
+ "ar": "غير نشط",
+ "fr": "Non actif",
+ "bn": "সক্রিয় নয়",
+ "pt-BR": "Não ativo",
+ "ru": "Не активно",
+ "id": "Tidak aktif"
+ },
"Not connected": {
"zh-Hans": "未连接",
"hi": "कनेक्ट नहीं",
@@ -1696,6 +2037,28 @@
"ru": "Не подключено",
"id": "Tidak terhubung"
},
+ "Not found: {0}": {
+ "zh-Hans": "未找到:{0}",
+ "hi": "नहीं मिला: {0}",
+ "es": "No encontrado: {0}",
+ "ar": "غير موجود: {0}",
+ "fr": "Introuvable : {0}",
+ "bn": "পাওয়া যায়নি: {0}",
+ "pt-BR": "Não encontrado: {0}",
+ "ru": "Не найдено: {0}",
+ "id": "Tidak ditemukan: {0}"
+ },
+ "Not in your library, opened search for {0}": {
+ "zh-Hans": "不在你的资料库中,已打开 {0} 的搜索",
+ "hi": "तुम्हारी लाइब्रेरी में नहीं है, {0} के लिए सर्च खोला",
+ "es": "No está en tu biblioteca, abrí la búsqueda de {0}",
+ "ar": "غير موجود في مكتبتك، فتحت البحث عن {0}",
+ "fr": "Introuvable dans ta bibliothèque, j'ai ouvert la recherche pour {0}",
+ "bn": "তোমার লাইব্রেরিতে নেই, {0} এর জন্য সার্চ খুলেছি",
+ "pt-BR": "Não está na sua biblioteca, abri a busca por {0}",
+ "ru": "Нет в библиотеке, открыл поиск для {0}",
+ "id": "Tidak ada di perpustakaan, membuka pencarian untuk {0}"
+ },
"Not installed": {
"zh-Hans": "未安装",
"hi": "इंस्टॉल नहीं",
@@ -1718,6 +2081,28 @@
"ru": "Не воспроизводится",
"id": "Tidak diputar"
},
+ "Not recognised: « {0} »": {
+ "zh-Hans": "无法理解:« {0} »",
+ "hi": "समझ नहीं आया: « {0} »",
+ "es": "No entendido: « {0} »",
+ "ar": "غير مفهوم: « {0} »",
+ "fr": "Pas compris : « {0} »",
+ "bn": "বোঝা যায়নি: « {0} »",
+ "pt-BR": "Não entendido: « {0} »",
+ "ru": "Непонятно: « {0} »",
+ "id": "Tidak dimengerti: « {0} »"
+ },
+ "Not requested": {
+ "zh-Hans": "未请求",
+ "hi": "अनुरोध नहीं किया गया",
+ "es": "No solicitado",
+ "ar": "لم يُطلب",
+ "fr": "Non demandé",
+ "bn": "অনুরোধ করা হয়নি",
+ "pt-BR": "Não solicitado",
+ "ru": "Не запрошено",
+ "id": "Belum diminta"
+ },
"Notch shortcuts — active when the notch is in front": {
"zh-Hans": "岛快捷键 — 岛获得焦点时有效",
"hi": "आइलैंड शॉर्टकट — आइलैंड फोकस में होने पर सक्रिय",
@@ -1773,6 +2158,17 @@
"ru": "ОК",
"id": "OK"
},
+ "OK, leaving it as is": {
+ "zh-Hans": "好的,保持原样",
+ "hi": "ठीक है, जैसा है वैसा छोड़ता हूँ",
+ "es": "De acuerdo, lo dejo como está",
+ "ar": "حسنًا، أتركه كما هو",
+ "fr": "D'accord, je laisse comme ça",
+ "bn": "ঠিক আছে, এটা যেমন আছে রেখে দিচ্ছি",
+ "pt-BR": "Ok, vou deixar como está",
+ "ru": "Хорошо, оставляю как есть",
+ "id": "Baik, biarkan seperti itu"
+ },
"Ollama disconnected.": {
"zh-Hans": "Ollama 已断开连接。",
"hi": "Ollama डिस्कनेक्ट हो गया।",
@@ -1795,6 +2191,17 @@
"ru": "Поддерживаются только URL с http:// и https://.",
"id": "Hanya URL http:// dan https:// yang didukung."
},
+ "Only: {0}": {
+ "zh-Hans": "仅:{0}",
+ "hi": "केवल: {0}",
+ "es": "Solo: {0}",
+ "ar": "فقط: {0}",
+ "fr": "Seulement : {0}",
+ "bn": "শুধুমাত্র: {0}",
+ "pt-BR": "Apenas: {0}",
+ "ru": "Только: {0}",
+ "id": "Hanya: {0}"
+ },
"Open": {
"zh-Hans": "打开",
"hi": "खोलें",
@@ -1839,6 +2246,17 @@
"ru": "Открыть / закрыть гардероб",
"id": "Buka / tutup lemari"
},
+ "Open Accessibility settings": {
+ "zh-Hans": "打开辅助功能",
+ "hi": "Accessibility खोलें",
+ "es": "Abrir Accesibilidad",
+ "ar": "افتح تسهيلات الاستخدام",
+ "fr": "Ouvrir Accessibilité",
+ "bn": "Accessibility খোলো",
+ "pt-BR": "Abrir Acessibilidade",
+ "ru": "Открыть Универсальный доступ",
+ "id": "Buka Aksesibilitas"
+ },
"Open Codex": {
"zh-Hans": "打开 Codex",
"hi": "Codex खोलें",
@@ -2026,6 +2444,17 @@
"ru": "Плагин OpenCode",
"id": "Plugin OpenCode"
},
+ "Opening Apple Music…": {
+ "zh-Hans": "正在打开 Apple Music…",
+ "hi": "Apple Music खुल रहा है…",
+ "es": "Abriendo Apple Music…",
+ "ar": "فتح Apple Music…",
+ "fr": "Ouverture d'Apple Music…",
+ "bn": "Apple Music খুলছে…",
+ "pt-BR": "Abrindo Apple Music…",
+ "ru": "Открытие Apple Music…",
+ "id": "Membuka Apple Music…"
+ },
"Other…": {
"zh-Hans": "其他…",
"hi": "अन्य…",
@@ -2059,6 +2488,17 @@
"ru": "Пауза",
"id": "Jeda"
},
+ "Paused": {
+ "zh-Hans": "已暂停",
+ "hi": "रुका हुआ",
+ "es": "En pausa",
+ "ar": "متوقف مؤقتاً",
+ "fr": "En pause",
+ "bn": "বিরতি",
+ "pt-BR": "Em pausa",
+ "ru": "Пауза",
+ "id": "Dijeda"
+ },
"Payments": {
"zh-Hans": "付款",
"hi": "भुगतान",
@@ -2070,6 +2510,17 @@
"ru": "Платежи",
"id": "Pembayaran"
},
+ "Permissions": {
+ "zh-Hans": "权限",
+ "hi": "अनुमतियाँ",
+ "es": "Permisos",
+ "ar": "الأذونات",
+ "fr": "Permissions",
+ "bn": "অনুমতি",
+ "pt-BR": "Permissões",
+ "ru": "Разрешения",
+ "id": "Izin"
+ },
"Pin / unpin notch": {
"zh-Hans": "固定/取消固定岛",
"hi": "आइलैंड पिन / अनपिन",
@@ -2081,6 +2532,17 @@
"ru": "Закрепить / открепить нотч",
"id": "Sematkan / lepas island"
},
+ "Pitch": {
+ "zh-Hans": "音调",
+ "hi": "आवाज़ की पिच",
+ "es": "Tono",
+ "ar": "حدّة الصوت",
+ "fr": "Hauteur",
+ "bn": "কণ্ঠের তীক্ষ্ণতা",
+ "pt-BR": "Tom",
+ "ru": "Высота голоса",
+ "id": "Nada suara"
+ },
"Plan usage": {
"zh-Hans": "计划用量",
"hi": "प्लान उपयोग",
@@ -2103,6 +2565,17 @@
"ru": "Воспроизвести",
"id": "Putar"
},
+ "Playing": {
+ "zh-Hans": "正在播放",
+ "hi": "चल रहा है",
+ "es": "Reproduciendo",
+ "ar": "يشغّل",
+ "fr": "Lecture",
+ "bn": "চলছে",
+ "pt-BR": "Reproduzindo",
+ "ru": "Воспроизведение",
+ "id": "Memutar"
+ },
"Playing · {title}": {
"zh-Hans": "正在播放 · {title}",
"hi": "चल रहा है · {title}",
@@ -2169,6 +2642,17 @@
"ru": "Предыдущая вкладка",
"id": "Tab sebelumnya"
},
+ "Previous track": {
+ "zh-Hans": "上一首",
+ "hi": "पिछला ट्रैक",
+ "es": "Pista anterior",
+ "ar": "المقطع السابق",
+ "fr": "Morceau précédent",
+ "bn": "আগের ট্র্যাক",
+ "pt-BR": "Faixa anterior",
+ "ru": "Предыдущий трек",
+ "id": "Lagu sebelumnya"
+ },
"Projects": {
"zh-Hans": "项目",
"hi": "प्रोजेक्ट",
@@ -2213,6 +2697,17 @@
"ru": "Недавние",
"id": "Terbaru"
},
+ "Recently heard phrases": {
+ "zh-Hans": "最近听到的语句",
+ "hi": "हाल में सुने गए वाक्य",
+ "es": "Frases escuchadas recientemente",
+ "ar": "العبارات المسموعة مؤخرًا",
+ "fr": "Dernières phrases entendues",
+ "bn": "সম্প্রতি শোনা বাক্য",
+ "pt-BR": "Frases ouvidas recentemente",
+ "ru": "Недавно услышанные фразы",
+ "id": "Kalimat yang baru didengar"
+ },
"Refresh": {
"zh-Hans": "刷新",
"hi": "रिफ्रेश",
@@ -2323,6 +2818,17 @@
"ru": "Ответить в терминале",
"id": "Balas di terminal"
},
+ "Request permissions": {
+ "zh-Hans": "请求权限",
+ "hi": "अनुमतियाँ अनुरोध करें",
+ "es": "Solicitar permisos",
+ "ar": "طلب الأذونات",
+ "fr": "Demander les permissions",
+ "bn": "অনুমতি অনুরোধ করুন",
+ "pt-BR": "Solicitar permissões",
+ "ru": "Запросить разрешения",
+ "id": "Minta izin"
+ },
"Resend": {
"zh-Hans": "重新发送",
"hi": "पुनः भेजें",
@@ -2455,6 +2961,17 @@
"ru": "Сохранить…",
"id": "Simpan…"
},
+ "Say your command": {
+ "zh-Hans": "说出您的命令",
+ "hi": "अपना आदेश बोलें",
+ "es": "Di tu comando",
+ "ar": "قل أمرك",
+ "fr": "Dites votre commande",
+ "bn": "আপনার কমান্ড বলুন",
+ "pt-BR": "Diga seu comando",
+ "ru": "Скажите команду",
+ "id": "Katakan perintah Anda"
+ },
"Schedule": {
"zh-Hans": "日程",
"hi": "शेड्यूल",
@@ -2697,6 +3214,17 @@
"ru": "Перемешивание вкл.",
"id": "Acak aktif"
},
+ "Sorry, can you say that again?": {
+ "zh-Hans": "抱歉,可以再说一遍吗?",
+ "hi": "माफ़ करना, फिर से बोलोगे?",
+ "es": "Perdona, ¿puedes repetir?",
+ "ar": "عفوًا، هل يمكنك التكرار؟",
+ "fr": "Pardon, tu peux répéter ?",
+ "bn": "দুঃখিত, আবার বলবে?",
+ "pt-BR": "Desculpa, pode repetir?",
+ "ru": "Прости, можешь повторить?",
+ "id": "Maaf, bisa diulang?"
+ },
"Sound": {
"zh-Hans": "声音",
"hi": "ध्वनि",
@@ -2708,6 +3236,17 @@
"ru": "Звук",
"id": "Suara"
},
+ "Speech recognition:": {
+ "zh-Hans": "语音识别:",
+ "hi": "वाक् पहचान:",
+ "es": "Reconocimiento de voz:",
+ "ar": "التعرف على الكلام:",
+ "fr": "Reconnaissance vocale :",
+ "bn": "বক্তৃতা স্বীকৃতি:",
+ "pt-BR": "Reconhecimento de fala:",
+ "ru": "Распознавание речи:",
+ "id": "Pengenalan ucapan:"
+ },
"Spotify not installed": {
"zh-Hans": "未安装 Spotify",
"hi": "Spotify इंस्टॉल नहीं है",
@@ -2763,6 +3302,17 @@
"ru": "Тема",
"id": "Subjek"
},
+ "Subtitles under the notch": {
+ "zh-Hans": "刘海下方显示字幕",
+ "hi": "नॉच के नीचे सबटाइटल",
+ "es": "Subtítulos bajo el notch",
+ "ar": "ترجمة نصية أسفل النوتش",
+ "fr": "Sous-titres sous le notch",
+ "bn": "নচের নিচে সাবটাইটেল",
+ "pt-BR": "Legendas abaixo do notch",
+ "ru": "Субтитры под вырезом",
+ "id": "Subtitel di bawah notch"
+ },
"Success": {
"zh-Hans": "成功",
"hi": "सफलता",
@@ -2807,6 +3357,17 @@
"ru": "ВРЕМЯ КОДИНГА",
"id": "WAKTU PEMROGRAMAN"
},
+ "Talk to Coucou": {
+ "zh-Hans": "与 Coucou 对话",
+ "hi": "Coucou से बात करें",
+ "es": "Hablar con Coucou",
+ "ar": "التحدث إلى Coucou",
+ "fr": "Parler à Coucou",
+ "bn": "Coucou-এর সাথে কথা বলুন",
+ "pt-BR": "Falar com Coucou",
+ "ru": "Говорить с Coucou",
+ "id": "Bicara ke Coucou"
+ },
"Tasks": {
"zh-Hans": "任务",
"hi": "कार्य",
@@ -2818,6 +3379,17 @@
"ru": "Задачи",
"id": "Tugas"
},
+ "Test the voice": {
+ "zh-Hans": "试听声音",
+ "hi": "आवाज़ आज़माएँ",
+ "es": "Probar la voz",
+ "ar": "جرّب الصوت",
+ "fr": "Tester la voix",
+ "bn": "কণ্ঠ পরীক্ষা",
+ "pt-BR": "Testar a voz",
+ "ru": "Проверить голос",
+ "id": "Coba suara"
+ },
"Tests": {
"zh-Hans": "测试",
"hi": "परीक्षण करता है",
@@ -2972,6 +3544,39 @@
"ru": "Используется чатом. Список берётся из твоего аккаунта Anthropic.",
"id": "Digunakan oleh chat. Daftar berasal dari akun Anthropic Anda."
},
+ "Voice": {
+ "zh-Hans": "声音",
+ "hi": "आवाज़",
+ "es": "Voz",
+ "ar": "الصوت",
+ "fr": "Voix",
+ "bn": "কণ্ঠ",
+ "pt-BR": "Voz",
+ "ru": "Голос",
+ "id": "Suara"
+ },
+ "Voice in use: {0}": {
+ "zh-Hans": "当前声音:{0}",
+ "hi": "उपयोग में आवाज़: {0}",
+ "es": "Voz en uso: {0}",
+ "ar": "الصوت المستخدم: {0}",
+ "fr": "Voix utilisée : {0}",
+ "bn": "ব্যবহৃত কণ্ঠ: {0}",
+ "pt-BR": "Voz em uso: {0}",
+ "ru": "Используется голос: {0}",
+ "id": "Suara yang dipakai: {0}"
+ },
+ "Voice type": {
+ "zh-Hans": "声音类型",
+ "hi": "आवाज़ का प्रकार",
+ "es": "Tipo de voz",
+ "ar": "نوع الصوت",
+ "fr": "Type de voix",
+ "bn": "কণ্ঠের ধরন",
+ "pt-BR": "Tipo de voz",
+ "ru": "Тип голоса",
+ "id": "Jenis suara"
+ },
"Volume": {
"zh-Hans": "音量",
"hi": "वॉल्यूम",
@@ -2983,6 +3588,28 @@
"ru": "Громкость",
"id": "Volume"
},
+ "Volume down": {
+ "zh-Hans": "调低音量",
+ "hi": "आवाज़ घटाएं",
+ "es": "Bajar volumen",
+ "ar": "خفض الصوت",
+ "fr": "Volume −",
+ "bn": "ভলিউম কমছে",
+ "pt-BR": "Volume mais baixo",
+ "ru": "Тише",
+ "id": "Volume turun"
+ },
+ "Volume up": {
+ "zh-Hans": "调高音量",
+ "hi": "आवाज़ बढ़ाएं",
+ "es": "Subir volumen",
+ "ar": "رفع الصوت",
+ "fr": "Volume +",
+ "bn": "ভলিউম বাড়ছে",
+ "pt-BR": "Volume mais alto",
+ "ru": "Громче",
+ "id": "Volume naik"
+ },
"Volume {0}%": {
"zh-Hans": "音量 {0}%",
"hi": "वॉल्यूम {0}%",
@@ -2994,6 +3621,17 @@
"ru": "Громкость {0}%",
"id": "Volume {0}%"
},
+ "Volume: {0}%": {
+ "zh-Hans": "音量:{0}%",
+ "hi": "वॉल्यूम: {0}%",
+ "es": "Volumen: {0}%",
+ "ar": "الصوت: {0}%",
+ "fr": "Volume : {0}%",
+ "bn": "ভলিউম: {0}%",
+ "pt-BR": "Volume: {0}%",
+ "ru": "Громкость: {0}%",
+ "id": "Volume: {0}%"
+ },
"Waiting for a response from Claude Code": {
"zh-Hans": "等待 Claude Code 回复",
"hi": "Claude Code के जवाब का इंतजार",
@@ -3027,6 +3665,17 @@
"ru": "Наблюдение: {count} из {total}",
"id": "Melihat {count} dari {total}"
},
+ "Weather by voice": {
+ "zh-Hans": "语音天气",
+ "hi": "आवाज़ से मौसम",
+ "es": "El tiempo por voz",
+ "ar": "الطقس بالصوت",
+ "fr": "Météo à la voix",
+ "bn": "কণ্ঠে আবহাওয়া",
+ "pt-BR": "Clima por voz",
+ "ru": "Погода голосом",
+ "id": "Cuaca lewat suara"
+ },
"Week": {
"zh-Hans": "一周",
"hi": "सप्ताह",
@@ -3060,6 +3709,72 @@
"ru": "Что вы хотите с ним сделать?",
"id": "Apa yang ingin Anda lakukan dengannya?"
},
+ "When enabled, Coucou listens for the wake word « OK Coucou ». Speech recognition runs entirely on-device — no audio or transcript leaves your Mac.": {
+ "zh-Hans": "启用后,Coucou 会监听唤醒词« OK Coucou »。语音识别完全在设备上运行—任何音频或文字记录都不会离开您的 Mac。",
+ "hi": "सक्षम होने पर, Coucou वेक शब्द « OK Coucou » सुनता है। वाक् पहचान पूरी तरह डिवाइस पर चलती है — कोई ऑडियो या ट्रांसक्रिप्ट आपके Mac को नहीं छोड़ता।",
+ "es": "Cuando está activado, Coucou escucha la palabra de activación « OK Coucou ». El reconocimiento de voz se ejecuta completamente en el dispositivo — ningún audio ni transcripción sale de tu Mac.",
+ "ar": "عند التفعيل، يستمع Coucou لكلمة التنشيط « OK Coucou ». يعمل التعرف على الكلام بالكامل على الجهاز — لا يغادر أي صوت أو نص جهاز Mac.",
+ "fr": "Quand cette option est activée, Coucou écoute le mot de réveil « OK Coucou ». La reconnaissance vocale se fait entièrement sur l’appareil — aucun audio ni transcription ne quitte votre Mac.",
+ "bn": "সক্ষম হলে, Coucou ওয়েক ওয়ার্ড « OK Coucou » শোনে। ভাষণ স্বীকৃতি সম্পূর্ণ ডিভাইসে চলে — কোনো অডিও বা ট্রান্সক্রিপ্ট আপনার Mac ছেড়ে যায় না।",
+ "pt-BR": "Quando ativado, o Coucou escuta a palavra de ativação « OK Coucou ». O reconhecimento de fala é executado inteiramente no dispositivo — nenhum áudio ou transcrição sai do seu Mac.",
+ "ru": "Когда включено, Coucou слушает слово активации « OK Coucou ». Распознавание речи работает полностью на устройстве — никакие аудиозаписи или транскрипции не покидают ваш Mac.",
+ "id": "Saat diaktifkan, Coucou mendengarkan kata pengaktif « OK Coucou ». Pengenalan ucapan berjalan sepenuhnya di perangkat — tidak ada audio atau transkrip yang meninggalkan Mac Anda."
+ },
+ "Which pill do you want to add?": {
+ "zh-Hans": "要添加哪个胶囊?",
+ "hi": "कौन-सी पिल जोड़नी है?",
+ "es": "¿Qué píldora quieres añadir?",
+ "ar": "أي حبة تريد أن تضيف؟",
+ "fr": "Quelle pilule tu veux ajouter ?",
+ "bn": "কোন পিল যোগ করবে?",
+ "pt-BR": "Qual pílula você quer adicionar?",
+ "ru": "Какую пилюлю добавить?",
+ "id": "Pil mana yang mau ditambahkan?"
+ },
+ "Which pill do you want to remove?": {
+ "zh-Hans": "要移除哪个胶囊?",
+ "hi": "कौन-सी पिल हटानी है?",
+ "es": "¿Qué píldora quieres quitar?",
+ "ar": "أي حبة تريد أن تزيل؟",
+ "fr": "Quelle pilule tu veux retirer ?",
+ "bn": "কোন পিল সরাবে?",
+ "pt-BR": "Qual pílula você quer remover?",
+ "ru": "Какую пилюлю убрать?",
+ "id": "Pil mana yang mau dihapus?"
+ },
+ "Which playlist?": {
+ "zh-Hans": "哪个播放列表?",
+ "hi": "कौन-सी प्लेलिस्ट?",
+ "es": "¿Qué playlist?",
+ "ar": "أي قائمة تشغيل؟",
+ "fr": "Quelle playlist ?",
+ "bn": "কোন প্লেলিস্ট?",
+ "pt-BR": "Qual playlist?",
+ "ru": "Какой плейлист?",
+ "id": "Playlist yang mana?"
+ },
+ "While listening, macOS shows the orange microphone dot in the top-right of the menu bar. This is normal system behaviour.": {
+ "zh-Hans": "收听时,macOS 会在菜单栏右上角显示橙色麦克风指示灯。这是正常的系统行为。",
+ "hi": "सुनते समय, macOS मेनू बार के ऊपर-दाईं ओर नारंगी माइक्रोफ़ोन बिंदु दिखाता है। यह सामान्य सिस्टम व्यवहार है।",
+ "es": "Durante la escucha, macOS muestra el punto naranja del micrófono en la parte superior derecha de la barra de menús. Este es el comportamiento normal del sistema.",
+ "ar": "أثناء الاستماع، يعرض macOS نقطة الميكروفون البرتقالية في أعلى يمين شريط القوائم. هذا هو السلوك الطبيعي للنظام.",
+ "fr": "Pendant l’écoute, macOS affiche le point orange du microphone en haut à droite de la barre de menus. C’est le comportement normal du système.",
+ "bn": "শোনার সময়, macOS মেনু বারের উপরের-ডানে কমলা মাইক্রোফোন বিন্দু দেখায়। এটি স্বাভাবিক সিস্টেম আচরণ।",
+ "pt-BR": "Durante a escuta, o macOS exibe o ponto laranja do microfone no canto superior direito da barra de menus. Este é o comportamento normal do sistema.",
+ "ru": "Во время прослушивания macOS отображает оранжевую точку микрофона в правом верхнем углу строки меню. Это нормальное поведение системы.",
+ "id": "Saat mendengarkan, macOS menampilkan titik mikrofon oranye di kanan atas bilah menu. Ini adalah perilaku sistem yang normal."
+ },
+ "Woman": {
+ "zh-Hans": "女声",
+ "hi": "महिला",
+ "es": "Mujer",
+ "ar": "امرأة",
+ "fr": "Femme",
+ "bn": "নারী",
+ "pt-BR": "Mulher",
+ "ru": "Женский",
+ "id": "Wanita"
+ },
"Workflow stopped.": {
"zh-Hans": "工作流已停止。",
"hi": "वर्कफ़्लो रुक गया।",
@@ -3104,6 +3819,17 @@
"ru": "Запишет:\n• ~/.claude/coucou/nb-hook\n• ~/.claude/settings.json (резервная копия создаётся сначала)",
"id": "Akan menulis:\n• ~/.claude/coucou/nb-hook\n• ~/.claude/settings.json (backup dibuat terlebih dahulu)"
},
+ "You speak": {
+ "zh-Hans": "你说的语言",
+ "hi": "आप बोलते हैं",
+ "es": "Tú hablas",
+ "ar": "أنت تتحدث",
+ "fr": "Tu parles",
+ "bn": "তুমি বলো",
+ "pt-BR": "Você fala",
+ "ru": "Ты говоришь",
+ "id": "Kamu berbicara"
+ },
"Your answer…": {
"zh-Hans": "您的答案…",
"hi": "आपका उत्तर…",
@@ -3280,6 +4006,28 @@
"ru": "с {name}",
"id": "dengan {name}"
},
+ "{0} added": {
+ "zh-Hans": "已添加 {0}",
+ "hi": "{0} जोड़ा गया",
+ "es": "{0} añadido",
+ "ar": "تمت إضافة {0}",
+ "fr": "{0} ajouté",
+ "bn": "{0} যোগ হয়েছে",
+ "pt-BR": "{0} adicionado",
+ "ru": "{0} добавлено",
+ "id": "{0} ditambahkan"
+ },
+ "{0} added — hooks not installed": {
+ "zh-Hans": "已添加 {0} — 钩子未安装",
+ "hi": "{0} जोड़ा — hooks इंस्टॉल नहीं",
+ "es": "{0} añadido — hooks no instalados",
+ "ar": "تمت إضافة {0} — الخطافات غير مثبّتة",
+ "fr": "{0} ajouté — hooks non installés",
+ "bn": "{0} যোগ হয়েছে — হুকস ইনস্টল নেই",
+ "pt-BR": "{0} adicionado — hooks não instalados",
+ "ru": "{0} добавлено — хуки не установлены",
+ "id": "{0} ditambahkan — hooks tidak terpasang"
+ },
"{0} custom": {
"zh-Hans": "{0} 个自定义",
"hi": "{0} कस्टम",
@@ -3291,6 +4039,17 @@
"ru": "своих: {0}",
"id": "{0} kustom"
},
+ "{0} removed": {
+ "zh-Hans": "已移除 {0}",
+ "hi": "{0} हटाया गया",
+ "es": "{0} eliminado",
+ "ar": "تمت إزالة {0}",
+ "fr": "{0} retiré",
+ "bn": "{0} সরানো হয়েছে",
+ "pt-BR": "{0} removido",
+ "ru": "{0} удалено",
+ "id": "{0} dihapus"
+ },
"{0} — open Spotify": {
"zh-Hans": "{0} — 打开 Spotify",
"hi": "{0} — Spotify खोलें",
@@ -3302,6 +4061,17 @@
"ru": "{0} — открыть Spotify",
"id": "{0} — buka Spotify"
},
+ "{0} → {1}": {
+ "zh-Hans": "{0} → {1}",
+ "hi": "{0} → {1}",
+ "es": "{0} → {1}",
+ "ar": "{0} → {1}",
+ "fr": "{0} → {1}",
+ "bn": "{0} → {1}",
+ "pt-BR": "{0} → {1}",
+ "ru": "{0} → {1}",
+ "id": "{0} → {1}"
+ },
"{count}/4 slots used": {
"zh-Hans": "已用 {count}/4 个插槽",
"hi": "{count}/4 स्लॉट उपयोग में",
@@ -3346,6 +4116,17 @@
"ru": "{n} мин назад",
"id": "{n} menit lalu"
},
+ "« OK Coucou » — voice wake word": {
+ "zh-Hans": "« OK Coucou » — 语音唤醒词",
+ "hi": "« OK Coucou » — वॉइस वेक वर्ड",
+ "es": "« OK Coucou » — palabra de activación de voz",
+ "ar": "« OK Coucou » — كلمة التنشيط الصوتية",
+ "fr": "« OK Coucou » — commande vocale mains libres",
+ "bn": "« OK Coucou » — ভয়েস ওয়েক ওয়ার্ড",
+ "pt-BR": "« OK Coucou » — palavra de ativação de voz",
+ "ru": "« OK Coucou » — голосовая активация",
+ "id": "« OK Coucou » — kata pengaktif suara"
+ },
"✓ Amp plugin installed in ~/.config/amp/plugins/coucou.ts": {
"zh-Hans": "✓ Amp 插件已安装至 ~/.config/amp/plugins/coucou.ts",
"hi": "✓ ~/.config/amp/plugins/coucou.ts में Amp प्लगइन इंस्टॉल हुआ",
diff --git a/windows/src/island/hooks.ts b/windows/src/island/hooks.ts
index 63e5cb08..ad01493d 100644
--- a/windows/src/island/hooks.ts
+++ b/windows/src/island/hooks.ts
@@ -23,7 +23,7 @@ const CURSOR_ID = "agent_cursor";
let pendingTimeout: number | null = null;
/** Takes the approval or question card down and gives the island back. */
-function dropPendingCard(island: Island): void {
+export function dropPendingCard(island: Island): void {
if (!State.pendingApproval) return;
State.endApproval();
island.dropPin();
diff --git a/windows/src/island/phone-link.ts b/windows/src/island/phone-link.ts
new file mode 100644
index 00000000..840603bc
--- /dev/null
+++ b/windows/src/island/phone-link.ts
@@ -0,0 +1,234 @@
+// What the island tells the phone link (src-tauri/src/phone_link).
+//
+// While the link is on, the island publishes a picture of its agent sessions and
+// of the permission request waiting for an answer; Rust works out what changed
+// and sends it to the paired phone. A phone's Allow or Deny comes back through
+// Rust (which answers the waiting hook) and only the card on the island is
+// closed here. While the link is off nothing is computed and no timer runs.
+
+import { Bridge, onEvent, type PhoneLinkPlan, type PhoneLinkUsage, type PhoneLinkApproval, type PhoneLinkDiff, type PhoneLinkFile, type PhoneLinkQuestion, type PhoneLinkSession } from "../core/bridge";
+import { fileName, parseDiffStep, type FileDiff } from "../core/diff";
+import type { PlanUsage, CodexPlanUsage } from "../core/plan";
+import { State } from "../core/state";
+import { parseOutfit } from "../mochi/wardrobe";
+import { dropPendingCard } from "./hooks";
+import { serviceCards } from "./phone-services";
+import type { Island } from "./island";
+
+/** Changes arrive in bursts (a tool call is several events); one picture per burst. */
+const DEBOUNCE_MS = 250;
+
+export interface LinkSnapshot {
+ sessions: PhoneLinkSession[];
+ approval: PhoneLinkApproval | null;
+ /** The question Claude Code is asking, offered only to phones that may answer (Rust decides who). */
+ question: PhoneLinkQuestion | null;
+}
+
+/**
+ * The island labels what it shows as "Bash · npm test". The phone shows the tool on its own
+ * line, so it gets the bare command.
+ */
+export function bareCommand(tool: string, command: string): string {
+ const prefix = `${tool} · `;
+ return command.startsWith(prefix) ? command.slice(prefix.length) : command;
+}
+
+/** Only the last segment of a folder path, whichever way it is written; never the path itself. */
+export function folderName(path: string | null | undefined): string | undefined {
+ const last = (path ?? "").split(/[\\/]+/).filter(Boolean).pop();
+ return last && last !== "." && last !== ".." ? last : undefined;
+}
+
+/** A step as the phone sees it: a file diff by its file name, anything else as it is. */
+function stepText(step: string): string {
+ const diff = parseDiffStep(step);
+ return diff ? diff.filename : step;
+}
+
+/** One plan as the phone gets it: the percentages and reset times the pills show, and nothing else. */
+function planFor(u: PlanUsage | CodexPlanUsage | null | undefined): PhoneLinkPlan | null {
+ if (!u || (!u.fiveHour && !u.sevenDay)) return null;
+ const plan: PhoneLinkPlan = { updatedAt: u.updatedAt };
+ if (u.fiveHour) plan.fiveHour = { usedPct: u.fiveHour.usedPct, resetsAt: u.fiveHour.resetsAt };
+ if (u.sevenDay) plan.sevenDay = { usedPct: u.sevenDay.usedPct, resetsAt: u.sevenDay.resetsAt };
+ const codex = u as CodexPlanUsage;
+ if (typeof codex.resetCredits === "number") plan.resetCredits = codex.resetCredits;
+ if (codex.planType) plan.planType = codex.planType;
+ return plan;
+}
+
+export function linkUsage(): PhoneLinkUsage {
+ return { claude: planFor(State.planUsage), codex: planFor(State.codexPlanUsage) };
+}
+
+/** The files a session changed, newest last, by name and counts only (the lines are sent when a phone asks). */
+export function linkFiles(pillId: string): PhoneLinkFile[] {
+ return (State.sessionDiffs.get(pillId) ?? []).slice(-20).map((d) => {
+ const f: PhoneLinkFile = { id: d.id, name: fileName(d.path), added: d.added, removed: d.removed };
+ if (d.tooLarge) f.tooLarge = true;
+ if (d.isNewFile) f.isNew = true;
+ return f;
+ });
+}
+
+/** One file's diff as lines of [kind, text]: "@" opens each hunk. A diff that was too large has counts only. */
+export function linkDiff(pillId: string, fileId: number): PhoneLinkDiff {
+ const d: FileDiff | null = State.findDiff(pillId, fileId);
+ const empty = { pillId, fileId, name: "", added: 0, removed: 0, tooLarge: false, lines: [] as [string, string][] };
+ if (!d) return { ...empty, gone: true };
+ const lines: [string, string][] = [];
+ for (const h of d.hunks) {
+ lines.push(["@", `@@ ${h.newStart}`]);
+ for (const l of h.lines) lines.push([l.kind === "added" ? "+" : l.kind === "removed" ? "-" : " ", l.text]);
+ }
+ return { pillId, fileId, name: fileName(d.path), added: d.added, removed: d.removed, tooLarge: d.tooLarge, gone: false, lines };
+}
+
+/** The agents' sessions — not the services — and the request the phone may answer. */
+export function linkSnapshot(): LinkSnapshot {
+ const sessions: PhoneLinkSession[] = State.tasks
+ .filter((t) => t.source !== "n8n")
+ .map((t) => {
+ const last = t.steps[t.steps.length - 1] ?? "";
+ // A step that stands for a file diff is shown by the file's name.
+ const diff = parseDiffStep(last);
+ return {
+ pillId: t.id,
+ agent: t.name,
+ state: t.state,
+ statusText: diff ? diff.filename : last,
+ stepIndex: t.stepIndex,
+ stepCount: t.steps.length,
+ // Session details. Rust sends them only to a phone that asked and was offered them (the user's
+ // switch), and cuts them to size; the folder's name is all that leaves this file, not the path.
+ steps: t.steps.slice(-20).map(stepText),
+ finalLine: t.finalLine || undefined,
+ project: folderName(t.sessionCwd),
+ color: t.color,
+ files: linkFiles(t.id),
+ };
+ });
+
+ // Permission requests (Allow / Deny) go to every phone. A question goes only to a phone that has the `answers`
+ // capability (Rust decides), as its own message: the options with their labels, nothing else of the request.
+ const a = State.pendingApproval;
+ const approval =
+ a && !a.questions && a.requestId
+ ? { requestId: a.requestId, sessionId: a.sessionId, pillId: a.pillId, tool: a.tool, command: bareCommand(a.tool, a.command) }
+ : null;
+ const question =
+ a && a.questions && a.questions.length > 0 && a.requestId
+ ? {
+ requestId: a.requestId,
+ sessionId: a.sessionId,
+ pillId: a.pillId,
+ questions: a.questions.map((q) => ({
+ question: q.question,
+ options: q.options.map((o) => ({ label: o.label, description: o.description ?? "" })),
+ multiSelect: q.multiSelect,
+ })),
+ }
+ : null;
+ return { sessions, approval, question };
+}
+
+/** Returns what undoes it (the tests use it; the app registers once and keeps it). */
+export function registerPhoneLink(island: Island): () => void {
+ let running = false;
+ let last = "";
+ /** What was last sent as the question; "" before anything was, so a link that comes up syncs the hub. */
+ let lastQuestion = "";
+ /** The outfit last sent; "" before anything was. */
+ let lastOutfit = "";
+ /** The plan usage last sent, as JSON; "" before anything was. */
+ let lastUsage = "";
+ /** The service cards last sent, as JSON; "" before anything was. */
+ let lastServices = "";
+ let timer: number | null = null;
+
+ const publish = () => {
+ timer = null;
+ publishQuestion();
+ publishOutfit();
+ publishUsage();
+ publishServices();
+ const snapshot = linkSnapshot();
+ const key = JSON.stringify(snapshot);
+ if (key === last) return;
+ last = key;
+ void Bridge.phoneLinkPublish(snapshot.sessions, snapshot.approval);
+ };
+
+ const publishQuestion = () => {
+ const key = JSON.stringify(linkSnapshot().question);
+ if (key === lastQuestion) return;
+ lastQuestion = key;
+ void Bridge.phoneLinkPublishQuestion(JSON.parse(key));
+ };
+
+ const publishOutfit = () => {
+ const outfit = parseOutfit(State.settings.mochiOutfit);
+ if (outfit === lastOutfit) return;
+ lastOutfit = outfit;
+ void Bridge.phoneLinkPublishPrefs(outfit);
+ };
+
+ const publishUsage = () => {
+ const usage = linkUsage();
+ const key = JSON.stringify(usage);
+ if (key === lastUsage) return;
+ lastUsage = key;
+ void Bridge.phoneLinkPublishUsage(usage);
+ };
+
+ const publishServices = () => {
+ const cards = serviceCards();
+ const key = JSON.stringify(cards);
+ if (key === lastServices) return;
+ lastServices = key;
+ void Bridge.phoneLinkPublishServices(cards);
+ };
+
+ const schedule = () => {
+ if (!running || timer != null) return;
+ timer = window.setTimeout(publish, DEBOUNCE_MS);
+ };
+
+ const refresh = async () => {
+ const status = await Bridge.phoneLinkStatus();
+ const now = status?.running ?? false;
+ if (now === running) return;
+ running = now;
+ last = ""; // a link that has just come up needs the whole picture
+ lastQuestion = "";
+ lastOutfit = "";
+ lastUsage = "";
+ lastServices = "";
+ if (running) schedule();
+ else if (timer != null) {
+ window.clearTimeout(timer);
+ timer = null;
+ }
+ };
+
+ const unsubscribe = State.subscribe(schedule);
+ // Turning the link on or off in Settings reaches the island as settings-changed.
+ void onEvent("settings-changed", () => void refresh());
+ // The phone answered: Rust has already told the agent; the card goes.
+ void onEvent<string>("phone-link-decided", (requestId) => {
+ if (State.pendingApproval?.requestId === requestId) dropPendingCard(island);
+ });
+ // A phone asked for a file's diff: the answer goes to that phone only (Rust cuts it to the limits).
+ void onEvent<{ conn: number; pillId: string; fileId: number }>("phone-link-getdiff", (ask) => {
+ if (!running || typeof ask?.conn !== "number") return;
+ void Bridge.phoneLinkSendDiff(ask.conn, linkDiff(String(ask.pillId), Number(ask.fileId)));
+ });
+ void refresh();
+ return () => {
+ unsubscribe();
+ if (timer != null) window.clearTimeout(timer);
+ timer = null;
+ running = false;
+ };
+}
diff --git a/windows/src/island/phone-services.ts b/windows/src/island/phone-services.ts
new file mode 100644
index 00000000..3284dd21
--- /dev/null
+++ b/windows/src/island/phone-services.ts
@@ -0,0 +1,128 @@
+// What the island's service pills show, written as small read-only cards for the phone (docs/ANDROID_LINK.md,
+// "Service cards"). Rust sends a phone only the services its user ticked in Settings -> Android phone; what is built
+// here is the most each card can say, kept short on purpose: a headline, why, and three lines.
+//
+// What never goes in a card: an email address or subject (Resend), a payment's description (Stripe), the text of an
+// n8n error, a link, a token. A card says what the pill's own header says and counts, nothing a click would reveal.
+
+import type { PhoneLinkService } from "../core/bridge";
+import { State } from "../core/state";
+import { t } from "../i18n/i18n";
+
+const obj = (id: string): Record<string, unknown> => (State.integrations[id]?.data ?? {}) as Record<string, unknown>;
+const list = (id: string, key: string): Record<string, unknown>[] => {
+ const v = obj(id)[key];
+ return Array.isArray(v) ? (v as Record<string, unknown>[]) : [];
+};
+
+/** "just now", "5m", "2h", "3d": the shorthand the pills use. */
+export function ago(value: unknown, now = Date.now()): string {
+ const date = typeof value === "number" ? new Date(value) : new Date(String(value));
+ const secs = (now - date.getTime()) / 1000;
+ if (!Number.isFinite(secs)) return "";
+ if (secs < 60) return t("just now");
+ if (secs < 3600) return t("{n}m", { n: Math.floor(secs / 60) });
+ if (secs < 86400) return t("{n}h", { n: Math.floor(secs / 3600) });
+ return t("{n}d", { n: Math.floor(secs / 86400) });
+}
+
+const money = (cents: unknown) => (Number(cents ?? 0) / 100).toFixed(2);
+const compact = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
+
+type Builder = (now: number) => PhoneLinkService | null;
+
+function usable(id: string): boolean {
+ const info = State.integrations[id];
+ return !!info && info.configured && !info.error;
+}
+
+const BUILDERS: Record<string, Builder> = {
+ integration_stripe: (now) => {
+ const d = obj("integration_stripe");
+ return {
+ id: "integration_stripe", title: "Stripe",
+ headline: `${money(d.balance)} ${String(d.currency ?? "eur").toUpperCase()}`,
+ reason: t("Payments"),
+ items: list("integration_stripe", "payments").slice(0, 3).map((p) => ({
+ label: p.status === "succeeded" ? t("Payment") : t("Payment failed"),
+ detail: `+${money(p.amount)} · ${ago(p.createdAt, now)}`,
+ })),
+ };
+ },
+ integration_github: () => {
+ const d = obj("integration_github");
+ return {
+ id: "integration_github", title: "GitHub",
+ headline: `${compact(Number(d.totalStars ?? 0))} ${t("Total stars")}`,
+ reason: t("Overview"),
+ items: [{ label: t("Repositories"), detail: String(Number(d.totalRepos ?? 0)) }],
+ };
+ },
+ integration_vercel: (now) => {
+ const deployments = list("integration_vercel", "deployments");
+ const ready = (d: Record<string, unknown>) => d.state === "READY";
+ return {
+ id: "integration_vercel", title: "Vercel",
+ headline: deployments.length === 0 ? "—" : ready(deployments[0]) ? t("Ready") : t("Failed"),
+ reason: t("Deployments"),
+ items: deployments.slice(0, 3).map((d) => ({ label: String(d.projectName ?? ""), detail: `${ready(d) ? t("Ready") : t("Failed")} · ${ago(d.createdAt, now)}` })),
+ };
+ },
+ integration_resend: (now) => {
+ const emails = list("integration_resend", "emails");
+ const total = obj("integration_resend").total;
+ return {
+ id: "integration_resend", title: "Resend",
+ headline: total != null ? String(total) : String(emails.length),
+ reason: t("Emails"),
+ // No address and no subject: only whether it arrived.
+ items: emails.slice(0, 3).map((e) => ({ label: e.lastEvent === "delivered" ? t("Delivered") : t("Not delivered"), detail: ago(e.createdAt, now) })),
+ };
+ },
+ integration_notion: (now) => {
+ const pages = list("integration_notion", "pages");
+ return {
+ id: "integration_notion", title: "Notion",
+ headline: String(pages.length),
+ reason: t("Recent"),
+ items: pages.slice(0, 3).map((p) => ({ label: String(p.title ?? t("Untitled")), detail: ago(p.lastEditedAt, now) })),
+ };
+ },
+ integration_calcom: () => {
+ const bookings = list("integration_calcom", "bookings")
+ .slice()
+ .sort((a, b) => new Date(String(a.start)).getTime() - new Date(String(b.start)).getTime());
+ const when = (b: Record<string, unknown>) => {
+ const d = new Date(String(b.start));
+ return `${String(d.getDate()).padStart(2, "0")}/${String(d.getMonth() + 1).padStart(2, "0")} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
+ };
+ return {
+ id: "integration_calcom", title: "Cal.com",
+ headline: bookings.length === 0 ? t("No calls scheduled") : when(bookings[0]),
+ reason: t("Schedule"),
+ items: bookings.slice(0, 3).map((b) => ({ label: String(b.title ?? t("Meeting")), detail: when(b) })),
+ };
+ },
+ integration_n8n: () => {
+ const task = State.tasks.find((x) => x.id === "integration_n8n");
+ if (!task || (task.state !== "finished" && task.state !== "error")) return null;
+ // The workflow's name and whether it worked; the error text stays on the computer.
+ return {
+ id: "integration_n8n", title: "n8n",
+ headline: task.state === "finished" ? t("Success") : t("Failed"),
+ reason: t("Workflow"),
+ items: task.steps[0] ? [{ label: task.steps[0], detail: "" }] : [],
+ };
+ },
+};
+
+/** The cards of the services the island has data for (Rust then keeps only the ones the user allowed). */
+export function serviceCards(now = Date.now()): PhoneLinkService[] {
+ const cards: PhoneLinkService[] = [];
+ for (const [id, build] of Object.entries(BUILDERS)) {
+ if (id !== "integration_n8n" && !usable(id)) continue;
+ const card = build(now);
+ if (card) cards.push(card);
+ }
+ return cards;
+}
diff --git a/windows/src/main.ts b/windows/src/main.ts
index 349e1cda..dfa4fbbe 100644
--- a/windows/src/main.ts
+++ b/windows/src/main.ts
@@ -6,6 +6,7 @@ import { Sound } from "./core/sound";
import { State, type Settings } from "./core/state";
import { Island } from "./island/island";
import { registerHookHandlers } from "./island/hooks";
+import { registerPhoneLink } from "./island/phone-link";
import { registerIntegrationHandlers, refreshConfigured } from "./island/integrations";
import { registerShortcutHandlers } from "./island/shortcuts";
import { applySpotify, registerSpotifyHandlers } from "./island/spotify";
@@ -98,6 +99,7 @@ async function main() {
});
registerHookHandlers(island);
+ registerPhoneLink(island);
registerIntegrationHandlers(island);
registerShortcutHandlers(island, () => setPaused(false));
registerSpotifyHandlers(island);
diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.ts
index c7ff6608..45eb9a88 100644
--- a/windows/src/settings/main.ts
+++ b/windows/src/settings/main.ts
@@ -17,6 +17,7 @@ import {
} from "../core/pills";
import { h, clear } from "../views/dom";
import { agentsSection } from "./agents";
+import { phoneSection } from "./phone";
import { colorDot } from "./colors";
import { renderDiff, statusDot } from "./parts";
import {
@@ -1367,6 +1368,7 @@ async function render() {
localSection(customKey),
activePillsSection(connected),
integrationsSection(present),
+ phoneSection(settings.phoneLink ?? false, toggle, settings),
generalSection(),
shortcutsSection(shortcutReport),
h("div", {
diff --git a/windows/src/settings/phone.ts b/windows/src/settings/phone.ts
new file mode 100644
index 00000000..14b219cd
--- /dev/null
+++ b/windows/src/settings/phone.ts
@@ -0,0 +1,516 @@
+// Settings → Android phone: the switch for the phone link and the code that
+// pairs a phone with this computer. Off until the user turns it on.
+
+import { Bridge, type PhoneChatStatus, type PhoneLinkPairing, type PhoneLinkStatus, type PhoneRelayState, type PhoneRelayStatus } from "../core/bridge";
+import { modelId, modelsOf, toggleModel, usableProviders } from "../core/phone-chat";
+import { PROVIDERS, type ProviderDef } from "../core/providers";
+import type { Settings } from "../core/state";
+import { h } from "../views/dom";
+import { t } from "../i18n/i18n";
+
+type Toggle = (on: boolean, onChange: (v: boolean) => void) => HTMLElement;
+
+/**
+ * The relay block ("Away from home Wi-Fi") is hidden until a relay is ready to use: the code and its tests stay, and
+ * turning this on shows it again. Nothing else changes.
+ */
+const SHOW_RELAY_SETTINGS = false;
+
+export function phoneSection(on: boolean, makeToggle: Toggle, settings: Settings): HTMLElement {
+ const detail = h("div", {});
+ const note = h("div", { class: "hint" });
+ /** Where the pairing code is drawn, so showing it never hides the switches below. */
+ const pairingBox = h("div", {});
+
+ const showError = (message: string) => {
+ note.textContent = t("Could not turn it on: {error}", { error: message });
+ };
+
+ /** The code itself, which lets a phone in: shown only when asked for. */
+ const reveal = async (status: PhoneLinkStatus | null, newCode: boolean) => {
+ try {
+ const pairing = newCode ? await Bridge.phoneLinkNewPairing() : await Bridge.phoneLinkPairing();
+ pairingBox.replaceChildren(...pairingRows(pairing, () => void reveal(status, true)));
+ } catch (err) {
+ showError(String(err));
+ }
+ };
+
+ /** After the relay settings change, a code that is on screen would be stale: show the current one. */
+ const refreshPairing = async () => {
+ if (pairingBox.childElementCount === 0) return;
+ try {
+ pairingBox.replaceChildren(...pairingRows(await Bridge.phoneLinkPairing(), () => void reveal(null, true)));
+ } catch (err) {
+ showError(String(err));
+ }
+ };
+
+ /** Draws what is below the switch from the link's state. */
+ const draw = (status: PhoneLinkStatus | null) => {
+ detail.replaceChildren();
+ pairingBox.replaceChildren();
+ note.textContent = "";
+ if (status?.error) showError(status.error);
+ if (!status?.running) return;
+ const show = h("button", { text: t("Show pairing code") });
+ show.addEventListener("click", () => void reveal(status, false));
+ const address = status.host ? `${status.host}:${status.port}` : `:${status.port}`;
+ clients.textContent = t("Phones connected: {count}", { count: status.clients });
+ detail.append(
+ h("div", { class: "row" }, show),
+ pairingBox,
+ clients,
+ h("div", { class: "hint", text: t("The phone connects to {address}", { address }) }),
+ h("div", { class: "hint", text: t("If Windows asks about the firewall, allow Coucou on private networks. The phone and this computer must be on the same Wi-Fi.") }),
+ h("div", { class: "hint", text: t("Your phone finds this computer again by itself when the network changes. It is announced on your local network only while this switch is on. Some hotspots and guest networks block this.") }),
+ ...(SHOW_RELAY_SETTINGS ? [relayBlock(makeToggle, () => void refreshPairing())] : []),
+ detailsBlock(makeToggle),
+ answersBlock(makeToggle),
+ diffsBlock(makeToggle),
+ usageBlock(makeToggle),
+ servicesBlock(),
+ chatBlock(makeToggle, settings),
+ );
+ };
+
+ /** Kept up to date while the window is open and the link is on; nothing runs otherwise. */
+ const clients = h("div", { class: "hint" });
+ const watch = window.setInterval(() => {
+ if (!section.isConnected) return window.clearInterval(watch);
+ if (document.visibilityState !== "visible" || !clients.isConnected) return;
+ void Bridge.phoneLinkStatus().then((s) => {
+ if (s?.running) clients.textContent = t("Phones connected: {count}", { count: s.clients });
+ });
+ }, 5000);
+
+ const switchEl = makeToggle(on, (next) => {
+ void (async () => {
+ try {
+ draw(await Bridge.phoneLinkSetEnabled(next));
+ } catch (err) {
+ // It could not start: the switch goes back off and says why.
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ detail.replaceChildren();
+ showError(String(err));
+ }
+ })();
+ });
+
+ void Bridge.phoneLinkStatus().then(draw);
+
+ const section = h(
+ "section",
+ {},
+ h("h2", {}, h("span", { text: t("Android phone") })),
+ h("div", { class: "hint", text: t("Send your agents' sessions to Coucou for Android and answer permission requests from the phone. Off by default; it only listens on your local network.") }),
+ h("div", { class: "hint", text: t("Allow on the phone asks for the fingerprint or the screen lock. Deny does not.") }),
+ h("div", { class: "row" }, h("label", { text: t("Phone link") }), switchEl),
+ note,
+ detail,
+ );
+ return section;
+}
+
+/** What the status line says about the relay. */
+export function relayStateText(state: PhoneRelayState): string {
+ switch (state) {
+ case "connecting": return t("Reaching the relay…");
+ case "waiting": return t("Connected to the relay, waiting for the phone.");
+ case "linked": return t("The phone is connected through the relay.");
+ case "accessRefused": return t("The relay refused the access key.");
+ case "unreachable": return t("The relay cannot be reached. Trying again.");
+ case "roomTaken": return t("This pairing is in use somewhere else. Press Pair again.");
+ case "tooMany": return t("The relay is limiting connections from here. Trying again later.");
+ default: return t("Off");
+ }
+}
+
+/**
+ * "Away from home Wi-Fi": reach the phone through a relay the user deployed on their own account. Off until the user
+ * enters the address and the access key and turns it on. The access key is write-only: it goes to the system keystore
+ * and the window never gets it back. Rust re-reads the switch for every connection.
+ */
+function relayBlock(makeToggle: Toggle, changed: () => void): HTMLElement {
+ const note = h("div", { class: "hint" });
+ const state = h("div", { class: "hint" });
+ const address = h("input", { type: "text", placeholder: "wss://", style: "width:100%", autocomplete: "off", spellcheck: "false" }) as HTMLInputElement;
+ const access = h("input", { type: "password", style: "width:100%", autocomplete: "off", spellcheck: "false" }) as HTMLInputElement;
+ let current: PhoneRelayStatus = { enabled: false, url: "", hasAccess: false, state: "off" };
+
+ const show = (status: PhoneRelayStatus | null) => {
+ if (!status) return;
+ current = status;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ if (document.activeElement !== address) address.value = status.url;
+ access.placeholder = status.hasAccess ? "••••••••" : "";
+ state.textContent = status.enabled ? relayStateText(status.state) : "";
+ };
+ const fail = (err: unknown) => {
+ note.textContent = String(err);
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ };
+ const apply = async (enabled: boolean) => {
+ note.textContent = "";
+ try {
+ show(await Bridge.phoneRelaySet(enabled, address.value));
+ changed();
+ } catch (err) {
+ fail(err);
+ }
+ };
+ const switchEl = makeToggle(false, (next) => void apply(next));
+ const saveAddress = h("button", { text: t("Save address") });
+ saveAddress.addEventListener("click", () => void apply(current.enabled));
+ const saveKey = h("button", { text: t("Save key") });
+ saveKey.addEventListener("click", () => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ const next = await Bridge.phoneRelaySetAccess(access.value);
+ access.value = ""; // never kept on the page
+ show(next);
+ changed();
+ } catch (err) {
+ note.textContent = String(err);
+ }
+ })();
+ });
+
+ void Bridge.phoneRelayStatus().then(show);
+ // Kept up to date while the window is open; nothing runs while it is hidden.
+ const watch = window.setInterval(() => {
+ if (!state.isConnected) return window.clearInterval(watch);
+ if (document.visibilityState !== "visible") return;
+ void Bridge.phoneRelayStatus().then(show);
+ }, 5000);
+
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Away from home Wi-Fi") }), switchEl),
+ h("div", { class: "hint", text: t("Reach this computer from your phone on mobile data or another network, through a relay you deployed yourself. Everything is encrypted end to end: the relay only forwards data it cannot read. Off by default.") }),
+ h("div", { class: "row" }, h("label", { text: t("Relay address") })),
+ h("div", { class: "row" }, address, saveAddress),
+ h("div", { class: "row" }, h("label", { text: t("Relay access key") })),
+ h("div", { class: "row" }, access, saveKey),
+ h("div", { class: "hint", text: t("Paste the access key you set when you deployed the relay. It is kept in the system keystore and never shown again.") }),
+ state,
+ note,
+ );
+}
+
+/**
+ * Session details for the phone (the steps, the last line, the folder name, the colour): off until the
+ * user turns it on. The phone is told only if it asks; Rust re-reads this switch for every connection.
+ */
+function detailsBlock(makeToggle: Toggle): HTMLElement {
+ const note = h("div", { class: "hint" });
+ const switchEl = makeToggle(false, (next) => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ await Bridge.phoneDetailsSetEnabled(next);
+ } catch (err) {
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ note.textContent = String(err);
+ }
+ })();
+ });
+ // The switch shows what Rust says, not what the page remembers.
+ void Bridge.phoneDetailsStatus().then((status) => {
+ if (!status) return;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ });
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Show session details on the phone") }), switchEl),
+ h("div", { class: "hint", text: t("Sends the last steps (as shown on the island, so they can include commands), the final line, the project's folder name and the colour. Never a path.") }),
+ note,
+ );
+}
+
+/**
+ * Answering the questions Claude Code asks, from the phone: off until the user turns it on. The phone shows the question
+ * and its options; its screen lock confirms every answer. Rust re-reads this switch for every connection.
+ */
+function answersBlock(makeToggle: Toggle): HTMLElement {
+ const note = h("div", { class: "hint" });
+ const switchEl = makeToggle(false, (next) => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ await Bridge.phoneAnswersSetEnabled(next);
+ } catch (err) {
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ note.textContent = String(err);
+ }
+ })();
+ });
+ void Bridge.phoneAnswersStatus().then((status) => {
+ if (!status) return;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ });
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Let the phone answer Claude Code's questions") }), switchEl),
+ h("div", { class: "hint", text: t("The phone shows each question with its options. Every answer is confirmed with the phone's fingerprint or screen lock.") }),
+ note,
+ );
+}
+
+/** The service pills the phone may show, with the names the pills carry (brand names, not translated). */
+const PHONE_SERVICES: [string, string][] = [
+ ["integration_stripe", "Stripe"], ["integration_github", "GitHub"], ["integration_vercel", "Vercel"],
+ ["integration_n8n", "n8n"], ["integration_resend", "Resend"], ["integration_notion", "Notion"], ["integration_calcom", "Cal.com"],
+];
+
+/**
+ * Service cards on the phone, read-only, one tick per service and none ticked until the user does it: what each card
+ * says is a headline and three short lines, never an address, a link or a secret. Rust re-reads the ticks for every
+ * connection and sends a phone only the services ticked here.
+ */
+function servicesBlock(): HTMLElement {
+ const note = h("div", { class: "hint" });
+ let ticked: string[] = [];
+ const boxes = PHONE_SERVICES.map(([id, name]) => {
+ const box = h("input", { type: "checkbox" }) as HTMLInputElement;
+ box.addEventListener("change", () => {
+ void (async () => {
+ note.textContent = "";
+ const next = box.checked ? [...new Set([...ticked, id])] : ticked.filter((x) => x !== id);
+ try {
+ ticked = (await Bridge.phoneServicesSet(next)).services;
+ } catch (err) {
+ box.checked = ticked.includes(id);
+ note.textContent = String(err);
+ }
+ })();
+ });
+ return { id, box, row: h("div", { class: "row" }, h("label", {}, box, h("span", { text: ` ${name}` }))) };
+ });
+ void Bridge.phoneServicesStatus().then((status) => {
+ if (!status) return;
+ ticked = status.services;
+ for (const b of boxes) b.box.checked = ticked.includes(b.id);
+ });
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Show these services on the phone") })),
+ h("div", { class: "hint", text: t("Each tick lets your paired phone see that service's card: a headline and up to three short lines, read-only. Nothing is shown until you tick it. No addresses, subjects, links or keys are ever sent.") }),
+ ...boxes.map((b) => b.row),
+ note,
+ );
+}
+
+/**
+ * The plan usage on the phone: off until the user turns it on. Only the percentages and reset times the pills show,
+ * for the Claude and Codex plans. Rust re-reads this switch for every connection.
+ */
+function usageBlock(makeToggle: Toggle): HTMLElement {
+ const note = h("div", { class: "hint" });
+ const switchEl = makeToggle(false, (next) => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ await Bridge.phoneUsageSetEnabled(next);
+ } catch (err) {
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ note.textContent = String(err);
+ }
+ })();
+ });
+ void Bridge.phoneUsageStatus().then((status) => {
+ if (!status) return;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ });
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Show my plan usage on the phone") }), switchEl),
+ h("div", { class: "hint", text: t("The phone shows how much of your Claude and Codex plans is used and when they reset: the same percentages as the pills here, nothing else.") }),
+ note,
+ );
+}
+
+/**
+ * The files an agent changed, on the phone: off until the user turns it on. The list (names and counts) rides on the
+ * session; the lines of a file are sent only when the phone asks for that file. Rust re-reads this for every connection.
+ */
+function diffsBlock(makeToggle: Toggle): HTMLElement {
+ const note = h("div", { class: "hint" });
+ const switchEl = makeToggle(false, (next) => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ await Bridge.phoneDiffsSetEnabled(next);
+ } catch (err) {
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ note.textContent = String(err);
+ }
+ })();
+ });
+ void Bridge.phoneDiffsStatus().then((status) => {
+ if (!status) return;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ });
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Show the files an agent changed on the phone") }), switchEl),
+ h("div", { class: "hint", text: t("The phone lists the files each agent changed and, when you tap one, shows what changed in it (200 lines at most, long lines cut). File names and lines go only to your paired phone, over the pinned encrypted link, and only when it asks.") }),
+ note,
+ );
+}
+
+/**
+ * Chat from the phone: off until the user turns it on, and then only the models ticked here.
+ * The phone gets text; the keys stay on this computer (src-tauri/src/phone_link/chat.rs).
+ */
+function chatBlock(makeToggle: Toggle, settings: Settings): HTMLElement {
+ let allowed: string[] = [];
+ const body = h("div", {});
+ const note = h("div", { class: "hint" });
+
+ const save = async (next: string[]) => {
+ try {
+ allowed = (await Bridge.phoneChatSetModels(next)).models;
+ } catch (err) {
+ note.textContent = String(err);
+ }
+ emptyNote.hidden = allowed.length > 0;
+ };
+ const emptyNote = h("div", { class: "hint", text: t("Nothing is allowed yet: the phone cannot chat until you tick a model.") });
+
+ /** One provider: a button that asks it for its models (only now), then a tick box per model. */
+ const providerRow = (p: ProviderDef): HTMLElement => {
+ const list = h("div", {});
+ const button = h("button", { text: t("Choose models") });
+ const head = h("div", { class: "row" }, h("label", { text: p.name }), button);
+ const show = (models: string[]) => {
+ list.replaceChildren(
+ ...[...new Set([...models, ...modelsOf(allowed, p.id)])].map((model) => {
+ const id = modelId(p.id, model);
+ const box = h("input", { type: "checkbox" }) as HTMLInputElement;
+ box.checked = allowed.includes(id);
+ box.addEventListener("change", () => void save(toggleModel(allowed, id, box.checked)));
+ return h("div", { class: "row" }, h("label", {}, box, h("span", { text: ` ${model}` })));
+ }),
+ );
+ };
+ button.addEventListener("click", () => {
+ list.replaceChildren(h("div", { class: "hint", text: t("Loading models…") }));
+ Bridge.chatModels(p.id).then(
+ (models) => show(models.map((m) => m.id)),
+ (err) => list.replaceChildren(h("div", { class: "hint", text: String(err).replace(/^Error:\s*/, "") })),
+ );
+ });
+ return h("div", {}, head, list);
+ };
+
+ const draw = async (status: PhoneChatStatus) => {
+ allowed = status.models;
+ body.replaceChildren();
+ if (!status.enabled) return;
+ const hasKey: Record<string, boolean> = {};
+ for (const p of usableProvidersCandidates()) hasKey[p.id] = (await Bridge.secretPresent(p.key!)) ?? false;
+ const providers = usableProviders(settings, hasKey);
+ body.append(h("div", { class: "hint", text: t("Models the phone may use") }));
+ if (providers.length === 0) body.append(h("div", { class: "hint", text: t("No provider is ready: add an API key or connect a local model first.") }));
+ for (const p of providers) body.append(providerRow(p));
+ emptyNote.hidden = allowed.length > 0;
+ body.append(emptyNote);
+ };
+
+ const switchEl = makeToggle(false, (next) => {
+ void (async () => {
+ note.textContent = "";
+ try {
+ await draw(await Bridge.phoneChatSetEnabled(next));
+ } catch (err) {
+ switchEl.classList.remove("on");
+ switchEl.setAttribute("aria-pressed", "false");
+ body.replaceChildren();
+ note.textContent = String(err);
+ }
+ })();
+ });
+ // The switch shows what Rust says, not what the page remembers.
+ void Bridge.phoneChatStatus().then((status) => {
+ if (!status) return;
+ switchEl.classList.toggle("on", status.enabled);
+ switchEl.setAttribute("aria-pressed", String(status.enabled));
+ void draw(status);
+ });
+
+ return h(
+ "div",
+ {},
+ h("div", { class: "row" }, h("label", { text: t("Let the phone chat with my AI providers") }), switchEl),
+ h("div", { class: "hint", text: t("Chat uses the API keys saved on this computer. The phone never sees them, and each message may cost money.") }),
+ note,
+ body,
+ );
+}
+
+function usableProvidersCandidates(): ProviderDef[] {
+ return PROVIDERS.filter((p) => p.key !== null);
+}
+
+/**
+ * Said after the link is copied: the link is the pairing code itself, so whoever reads it (the clipboard, a chat, a
+ * screenshot) can pair a phone until a new code is made. Hidden until the link has been copied.
+ */
+export function copyLinkHint(): HTMLElement {
+ const hint = h("div", {
+ class: "hint",
+ text: t("The link you copied contains the pairing code: anyone who gets it can pair a phone with this computer. If it ends up somewhere it should not, press Pair again to make a new code; the old one stops working."),
+ });
+ hint.hidden = true;
+ return hint;
+}
+
+function pairingRows(pairing: PhoneLinkPairing, again: () => void): HTMLElement[] {
+ // The QR comes from Rust (qrcode crate) as an SVG made only of paths.
+ const qr = h("div", { class: "qr" });
+ qr.innerHTML = pairing.qrSvg;
+
+ const link = h("input", { type: "text", readonly: "true", value: pairing.link, style: "width:100%" }) as HTMLInputElement;
+ link.addEventListener("focus", () => link.select());
+
+ const copy = h("button", { text: t("Copy link") });
+ const copied = copyLinkHint();
+ copy.addEventListener("click", () => {
+ void navigator.clipboard?.writeText(pairing.link).then(() => {
+ copied.hidden = false; // stays after the button text is restored
+ copy.textContent = t("Copied");
+ window.setTimeout(() => (copy.textContent = t("Copy link")), 1500);
+ });
+ });
+
+ const repair = h("button", { text: t("Pair again") });
+ repair.addEventListener("click", again);
+
+ return [
+ h("div", { class: "hint", text: t("In Coucou for Android, scan this code with the camera or paste the link.") }),
+ qr,
+ h("div", { class: "row" }, link, copy),
+ copied,
+ ...(pairing.relay ? [h("div", { class: "hint", text: t("This code also carries the access key and the end-to-end key for the relay {host}. Pair again makes a new key and a new room.", { host: pairing.relay }) })] : []),
+ h("div", { class: "row" }, repair, h("span", { class: "hint", text: t("The phone that was paired is disconnected and needs the new code.") })),
+ ];
+}
diff --git a/windows/src/settings/settings.css b/windows/src/settings/settings.css
index da46bfa8..792739d5 100644
--- a/windows/src/settings/settings.css
+++ b/windows/src/settings/settings.css
@@ -427,3 +427,7 @@ select option {
html[dir="rtl"] :is(.diff, .path, .keycap, input[type="password"], input[type="text"]) {
direction: ltr;
}
+
+/* Settings → Android phone: the pairing QR code (an SVG from Rust, black on white). */
+.qr { width: 220px; max-width: 100%; background: #fff; border-radius: 8px; padding: 4px; }
+.qr svg { display: block; width: 100%; height: auto; }
diff --git a/windows/tests/phone-chat.test.mjs b/windows/tests/phone-chat.test.mjs
new file mode 100644
index 00000000..32537335
--- /dev/null
+++ b/windows/tests/phone-chat.test.mjs
@@ -0,0 +1,44 @@
+// Settings → Android phone → chat: how the list of models the phone may use is built.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { MAX_ALLOWED, modelId, modelsOf, providerOf, toggleModel, usableProviders } from "../src/core/phone-chat.ts";
+import { DEFAULT_SETTINGS } from "../src/core/state.ts";
+
+test("an id is provider/model and the provider must be one the app knows", () => {
+ assert.equal(modelId("openai", "gpt-4o"), "openai/gpt-4o");
+ assert.equal(providerOf("openai/gpt-4o"), "openai");
+ assert.equal(providerOf("openrouter/openrouter/auto"), "openrouter");
+ for (const bad of ["", "openai", "openai/", "nope/x", "/x"]) assert.equal(providerOf(bad), null, bad);
+});
+
+test("ticking adds once, unticking removes, the order is kept", () => {
+ let list = [];
+ list = toggleModel(list, "openai/a", true);
+ list = toggleModel(list, "google/b", true);
+ list = toggleModel(list, "openai/a", true);
+ assert.deepEqual(list, ["google/b", "openai/a"]);
+ list = toggleModel(list, "google/b", false);
+ assert.deepEqual(list, ["openai/a"]);
+ assert.deepEqual(toggleModel(list, "nothing/there", false), ["openai/a"]);
+});
+
+test("the list stops at the cap", () => {
+ let list = [];
+ for (let i = 0; i < MAX_ALLOWED + 10; i++) list = toggleModel(list, `openai/m${i}`, true);
+ assert.equal(list.length, MAX_ALLOWED);
+});
+
+test("only providers with a key, or a connected server, are offered", () => {
+ const none = usableProviders(DEFAULT_SETTINGS, {});
+ assert.deepEqual(none, []);
+ const some = usableProviders({ ...DEFAULT_SETTINGS, ollamaUrl: "http://127.0.0.1:11434" }, { anthropic: true, openai: false });
+ assert.deepEqual(some.map((p) => p.id), ["anthropic", "ollama"]);
+});
+
+test("the models of one provider are told apart from the others'", () => {
+ const list = ["openai/a", "openai/b", "google/a", "openrouter/openrouter/auto"];
+ assert.deepEqual(modelsOf(list, "openai"), ["a", "b"]);
+ assert.deepEqual(modelsOf(list, "openrouter"), ["openrouter/auto"]);
+ assert.deepEqual(modelsOf(list, "ollama"), []);
+});
diff --git a/windows/tests/phone-link.test.mjs b/windows/tests/phone-link.test.mjs
new file mode 100644
index 00000000..e98e2327
--- /dev/null
+++ b/windows/tests/phone-link.test.mjs
@@ -0,0 +1,439 @@
+// What the island tells the phone link (src/island/phone-link.ts): the picture it
+// publishes, that nothing runs while the link is off, and that a phone's answer
+// closes the card for that request and no other.
+
+import { afterEach, beforeEach, mock, test } from "node:test";
+import assert from "node:assert/strict";
+import { calls, emit, internals, sent } from "./tauri.mjs";
+import { bareCommand, folderName, linkSnapshot, registerPhoneLink } from "../src/island/phone-link.ts";
+import { makeDiffStep } from "../src/core/diff.ts";
+import { DEFAULT_SETTINGS, State } from "../src/core/state.ts";
+
+const CLAUDE = "integration_claude";
+
+let status = { enabled: true, running: true, port: 47821, host: "192.168.1.2", name: "PC", clients: 0, error: null };
+const original = internals.invoke;
+internals.invoke = async (cmd, args) => (cmd === "phone_link_status" ? status : original(cmd, args));
+
+let asked;
+let dispose = () => {};
+const island = {
+ setView: (view) => asked.push(`setView:${view}`),
+ dropPin: () => asked.push("dropPin"),
+};
+
+/** Lets the async status call settle (setImmediate is not mocked). */
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+const tick = (ms) => mock.timers.tick(ms);
+
+beforeEach(() => {
+ mock.timers.enable({ apis: ["setTimeout"] });
+ asked = [];
+ calls.length = 0;
+ status = { ...status, running: true };
+ State.tasks = [];
+ State.focusId = null;
+ State.pendingApproval = null;
+ State.settings = { ...DEFAULT_SETTINGS, activeIntegrations: ["integration_github"] };
+ State.loadIntegrationTasks();
+});
+
+afterEach(() => {
+ dispose();
+ mock.timers.runAll();
+ mock.timers.reset();
+});
+
+test("the phone sees the agents, not the services", () => {
+ const { sessions } = linkSnapshot();
+ const ids = sessions.map((s) => s.pillId);
+ assert.ok(ids.includes(CLAUDE));
+ assert.ok(!ids.includes("integration_github"), "a service is not an agent session");
+ const claude = sessions.find((s) => s.pillId === CLAUDE);
+ assert.equal(claude.state, "idle");
+ assert.equal(claude.statusText, "");
+});
+
+test("a session carries its state, its last step and its progress", () => {
+ State.updateTask(CLAUDE, "working");
+ State.appendStep(CLAUDE, "Reading the project");
+ State.appendStep(CLAUDE, "Editing files");
+ const claude = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE);
+ assert.equal(claude.state, "working");
+ assert.equal(claude.statusText, "Editing files");
+ assert.equal(claude.stepCount, 2);
+ assert.equal(claude.stepIndex, 1);
+});
+
+test("a step that stands for a file diff is shown by the file's name", () => {
+ State.appendStep(CLAUDE, makeDiffStep("src/app.ts", 3, 1, 7));
+ const claude = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE);
+ assert.equal(claude.statusText, "src/app.ts");
+});
+
+test("only a permission request goes to the phone, not a question", () => {
+ assert.equal(linkSnapshot().approval, null);
+
+ State.beginApproval({ requestId: "r1", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "npm test" });
+ assert.deepEqual(linkSnapshot().approval, {
+ requestId: "r1", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "npm test",
+ });
+
+ State.endApproval();
+ State.beginApproval({
+ requestId: "r2", sessionId: "s1", pillId: CLAUDE, tool: "AskUserQuestion", command: "Which branch?",
+ questions: [{ question: "Which branch?", options: [], multiSelect: false }],
+ });
+ assert.equal(linkSnapshot().approval, null, "a question needs its options picked on the island");
+
+ State.endApproval();
+ State.beginApproval({ requestId: "", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "ls" });
+ assert.equal(linkSnapshot().approval, null, "no request id, nothing the phone could answer");
+});
+
+test("the phone gets the bare command, not the island's \"Bash · \" label", () => {
+ State.beginApproval({ requestId: "r1", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "Bash · npm run build" });
+ assert.equal(linkSnapshot().approval.command, "npm run build");
+ assert.equal(bareCommand("Edit", "Edit · src/a.ts"), "src/a.ts");
+ // A tool with no command to show, or a command that merely mentions the tool, is left alone.
+ assert.equal(bareCommand("Task", "Task"), "Task");
+ assert.equal(bareCommand("Bash", "echo Bash · hi"), "echo Bash · hi");
+});
+
+test("a burst of changes is one picture, and an unchanged picture is not sent again", async () => {
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ assert.equal(sent("phone_link_publish").length, 1, "the whole picture goes out when the link is up");
+
+ State.updateTask(CLAUDE, "working");
+ State.appendStep(CLAUDE, "one");
+ State.appendStep(CLAUDE, "two");
+ assert.equal(sent("phone_link_publish").length, 1, "waits for the burst to end");
+ tick(250);
+ assert.equal(sent("phone_link_publish").length, 2);
+ const last = sent("phone_link_publish")[1];
+ assert.equal(last.sessions.find((s) => s.pillId === CLAUDE).statusText, "two");
+ assert.equal(last.approval, null);
+
+ State.notify(); // something redrew, nothing changed for the phone
+ tick(250);
+ assert.equal(sent("phone_link_publish").length, 2);
+});
+
+test("while the link is off nothing is published", async () => {
+ status = { ...status, running: false };
+ dispose = registerPhoneLink(island);
+ await settle();
+ State.updateTask(CLAUDE, "working");
+ State.appendStep(CLAUDE, "busy");
+ tick(1000);
+ assert.equal(sent("phone_link_publish").length, 0);
+});
+
+test("turning the link on in Settings sends the whole picture at once", async () => {
+ status = { ...status, running: false };
+ dispose = registerPhoneLink(island);
+ await settle();
+ State.updateTask(CLAUDE, "thinking");
+ tick(1000);
+ assert.equal(sent("phone_link_publish").length, 0);
+
+ status = { ...status, running: true };
+ emit("settings-changed", {});
+ await settle();
+ tick(250);
+ assert.equal(sent("phone_link_publish").length, 1);
+ assert.equal(sent("phone_link_publish")[0].sessions.find((s) => s.pillId === CLAUDE).state, "thinking");
+
+ // And off again: the next change is not sent.
+ status = { ...status, running: false };
+ emit("settings-changed", {});
+ await settle();
+ State.updateTask(CLAUDE, "working");
+ tick(1000);
+ assert.equal(sent("phone_link_publish").length, 1);
+});
+
+test("a request waiting for an answer is published, and withdrawn once it is answered", async () => {
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ State.beginApproval({ requestId: "r1", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "rm -rf build" });
+ tick(250);
+ assert.equal(sent("phone_link_publish").at(-1).approval.requestId, "r1");
+ State.endApproval(); // answered at the desk
+ tick(250);
+ assert.equal(sent("phone_link_publish").at(-1).approval, null);
+});
+
+test("an answer from the phone closes the card for that request only", async () => {
+ dispose = registerPhoneLink(island);
+ await settle();
+ State.beginApproval({ requestId: "r1", sessionId: "s1", pillId: CLAUDE, tool: "Bash", command: "ls" });
+
+ emit("phone-link-decided", "some-other-request");
+ assert.ok(State.pendingApproval, "another request's answer must not close this card");
+
+ emit("phone-link-decided", "r1");
+ assert.equal(State.pendingApproval, null);
+ assert.ok(asked.includes("dropPin"));
+ // The island itself sends nothing: Rust already answered the agent.
+ assert.equal(sent("approval_decision").length, 0);
+});
+
+// ── session details (cap `details`) ──────────────────────────────────────────────────────────
+
+test("a session carries its last steps, its final line, its folder name and its colour", () => {
+ State.appendStep(CLAUDE, "Reading the project");
+ State.appendStep(CLAUDE, makeDiffStep("src/app.ts", 3, 1, 7));
+ const task = State.tasks.find((t) => t.id === CLAUDE);
+ task.finalLine = "All done";
+ task.sessionCwd = "/home/me/private/coucou";
+ const claude = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE);
+ assert.deepEqual(claude.steps.slice(-2), ["Reading the project", "src/app.ts"], "a diff step is its file name");
+ assert.equal(claude.finalLine, "All done");
+ assert.equal(claude.project, "coucou", "the folder's name, not the path");
+ assert.equal(claude.color, task.color);
+ assert.ok(!JSON.stringify(claude).includes("private"));
+});
+
+test("at most the last twenty steps go to Rust", () => {
+ for (let i = 0; i < 30; i++) State.appendStep(CLAUDE, `step ${i}`);
+ const claude = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE);
+ assert.equal(claude.steps.length, 20);
+ assert.equal(claude.steps.at(-1), "step 29");
+});
+
+test("a folder name is the last segment, whichever way the path is written", () => {
+ assert.equal(folderName("/home/me/work/app"), "app");
+ assert.equal(folderName("/home/me/work/app/"), "app");
+ assert.equal(folderName("C:\\Users\\me\\app"), "app");
+ assert.equal(folderName("C:\\Users\\me\\app\\"), "app");
+ assert.equal(folderName("app"), "app");
+ for (const none of [null, undefined, "", "/", "\\", "..", "/a/.."]) assert.equal(folderName(none), undefined, String(none));
+});
+
+test("a session with nothing to add has no empty details", () => {
+ const task = State.tasks.find((t) => t.id === "agent_gemini") ?? State.tasks[0];
+ const s = linkSnapshot().sessions.find((x) => x.pillId === task.id);
+ if (s) {
+ assert.equal(s.finalLine, undefined);
+ assert.equal(s.project, undefined);
+ }
+});
+
+test("a question goes to the phone as its own message, with the options and nothing else of the request", () => {
+ assert.equal(linkSnapshot().question, null);
+ State.beginApproval({
+ requestId: "q1", sessionId: "s1", pillId: CLAUDE, tool: "AskUserQuestion", command: "Which branch?",
+ questions: [
+ { question: "Which branch?", options: [{ label: "main", description: "the default" }, { label: "dev", description: "" }], multiSelect: false },
+ { question: "Which checks?", options: [{ label: "lint", description: "style" }], multiSelect: true },
+ ],
+ });
+ const snap = linkSnapshot();
+ assert.equal(snap.approval, null, "it is not a permission request");
+ assert.deepEqual(snap.question, {
+ requestId: "q1", sessionId: "s1", pillId: CLAUDE,
+ questions: [
+ { question: "Which branch?", options: [{ label: "main", description: "the default" }, { label: "dev", description: "" }], multiSelect: false },
+ { question: "Which checks?", options: [{ label: "lint", description: "style" }], multiSelect: true },
+ ],
+ });
+ assert.ok(!JSON.stringify(snap.question).includes("command"), "the island's command text is not part of it");
+});
+
+test("a request without an id, or a question without options, is not offered", () => {
+ State.beginApproval({ requestId: "", sessionId: "s1", pillId: CLAUDE, tool: "AskUserQuestion", command: "x", questions: [{ question: "A?", options: [{ label: "y", description: "" }], multiSelect: false }] });
+ assert.equal(linkSnapshot().question, null);
+ State.endApproval();
+ State.beginApproval({ requestId: "q2", sessionId: "s1", pillId: CLAUDE, tool: "AskUserQuestion", command: "x", questions: [] });
+ assert.equal(linkSnapshot().question, null);
+});
+
+test("the question is published when it appears and withdrawn when it is answered, and not repeated", async () => {
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ const q = () => sent("phone_link_publish_question");
+ assert.equal(q().length, 1, "the hub is told there is none when the link comes up");
+ assert.equal(q()[0].question, null);
+
+ State.beginApproval({ requestId: "q1", sessionId: "s1", pillId: CLAUDE, tool: "AskUserQuestion", command: "x", questions: [{ question: "A?", options: [{ label: "y", description: "" }], multiSelect: false }] });
+ tick(250);
+ assert.equal(q().length, 2);
+ assert.equal(q()[1].question.requestId, "q1");
+
+ State.notify();
+ tick(250);
+ assert.equal(q().length, 2, "unchanged: not sent again");
+
+ State.endApproval();
+ tick(250);
+ assert.equal(q().length, 3);
+ assert.equal(q()[2].question, null);
+});
+
+test("the outfit is published when the link comes up and whenever the wardrobe changes, and not repeated", async () => {
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ const p = () => sent("phone_link_publish_prefs");
+ assert.equal(p().length, 1);
+ assert.equal(p()[0].outfit, "auto", "the default of the wardrobe");
+
+ State.settings.mochiOutfit = "beanie";
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 2);
+ assert.equal(p()[1].outfit, "beanie");
+
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 2, "unchanged: not sent again");
+
+ State.settings.mochiOutfit = "topHat"; // a value no build knows: the wardrobe reads it as auto
+ State.notify();
+ tick(250);
+ assert.equal(p().at(-1).outfit, "auto");
+});
+
+test("a session lists the files it changed by name and counts, never a path", async () => {
+ const { fromEdit } = await import("../src/core/diff.ts");
+ State.appendSessionDiff(CLAUDE, fromEdit("a\nb\n", "a\nc\n", "/home/me/secret/proj/src/app.ts"));
+ const claude = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE);
+ assert.equal(claude.files.length, 1);
+ assert.equal(claude.files[0].name, "app.ts");
+ assert.equal(claude.files[0].added, 1);
+ assert.equal(claude.files[0].removed, 1);
+ assert.ok(!JSON.stringify(claude.files).includes("secret"));
+ assert.ok(!JSON.stringify(claude.files).includes("lines"), "the lines are sent only when asked for");
+});
+
+test("at most twenty files are listed, the newest", async () => {
+ const { fromEdit } = await import("../src/core/diff.ts");
+ for (let i = 0; i < 30; i++) State.appendSessionDiff(CLAUDE, fromEdit("a\n", "b\n", `/p/f${i}.ts`));
+ const files = linkSnapshot().sessions.find((s) => s.pillId === CLAUDE).files;
+ assert.equal(files.length, 20);
+ assert.equal(files.at(-1).name, "f29.ts");
+});
+
+test("a diff is answered as lines with hunk headers, and a missing one as gone", async () => {
+ const { fromEdit } = await import("../src/core/diff.ts");
+ const { linkDiff } = await import("../src/island/phone-link.ts");
+ const id = State.appendSessionDiff(CLAUDE, fromEdit("one\ntwo\nthree\n", "one\n2\nthree\n", "C:\\Users\\me\\x\\note.md"));
+ const d = linkDiff(CLAUDE, id);
+ assert.equal(d.gone, false);
+ assert.equal(d.name, "note.md");
+ assert.equal(d.lines[0][0], "@");
+ assert.deepEqual(d.lines.filter((l) => l[0] === "-" || l[0] === "+"), [["-", "two"], ["+", "2"]]);
+ assert.equal(linkDiff(CLAUDE, 999999).gone, true);
+ assert.equal(linkDiff("nobody", id).gone, true);
+});
+
+test("a phone's request is answered to that phone only, and not while the link is off", async () => {
+ const { fromEdit } = await import("../src/core/diff.ts");
+ const id = State.appendSessionDiff(CLAUDE, fromEdit("a\n", "b\n", "/x/y.ts"));
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ emit("phone-link-getdiff", { conn: 5, pillId: CLAUDE, fileId: id });
+ await settle();
+ const sentDiffs = sent("phone_link_send_diff");
+ assert.equal(sentDiffs.length, 1);
+ assert.equal(sentDiffs[0].conn, 5);
+ assert.equal(sentDiffs[0].diff.fileId, id);
+});
+
+test("only the percentages and reset times of the plans are published, and not repeated", async () => {
+ const { linkUsage } = await import("../src/island/phone-link.ts");
+ State.planUsage = null;
+ State.codexPlanUsage = null;
+ assert.deepEqual(linkUsage(), { claude: null, codex: null });
+
+ State.planUsage = { fiveHour: { usedPct: 40, resetsAt: 2e12 }, updatedAt: 5 };
+ State.codexPlanUsage = { sevenDay: { usedPct: 10, resetsAt: 2e12 }, resetCredits: 2, planType: "plus", updatedAt: 6 };
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ const p = () => sent("phone_link_publish_usage");
+ assert.equal(p().length, 1);
+ assert.deepEqual(p()[0].usage.claude, { updatedAt: 5, fiveHour: { usedPct: 40, resetsAt: 2e12 } });
+ assert.equal(p()[0].usage.codex.resetCredits, 2);
+ assert.equal(p()[0].usage.codex.planType, "plus");
+
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 1, "unchanged: not sent again");
+ State.planUsage = { fiveHour: { usedPct: 55, resetsAt: 2e12 }, updatedAt: 9 };
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 2);
+ assert.equal(p()[1].usage.claude.fiveHour.usedPct, 55);
+ State.planUsage = null;
+ State.codexPlanUsage = null;
+});
+
+function service(id, data, extra = {}) {
+ State.integrations[id] = { data, error: null, loaded: true, configured: true, ...extra };
+}
+
+test("service cards say what the pills say and never an address, a subject, a description or a link", async () => {
+ const { serviceCards } = await import("../src/island/phone-services.ts");
+ const now = Date.now();
+ service("integration_stripe", { balance: 1250, currency: "eur", payments: [{ status: "succeeded", amount: 900, description: "Alice Martin invoice 42", createdAt: now - 120_000 }, { status: "failed", amount: 100, createdAt: now - 3_600_000 * 3 }] });
+ service("integration_resend", { total: 31, emails: [{ to: ["[email protected]"], subject: "Your secret order", lastEvent: "delivered", createdAt: now - 60_000 }] });
+ service("integration_notion", { pages: [{ title: "Roadmap", url: "https://notion.so/secret", lastEditedAt: now - 5_000 }] });
+ service("integration_github", { totalStars: 1520, totalRepos: 12 });
+ service("integration_vercel", { deployments: [{ projectName: "shop", state: "READY", createdAt: now - 600_000 }] });
+ service("integration_calcom", { bookings: [{ title: "Intro call", start: new Date(now + 3_600_000).toISOString() }] });
+ const cards = serviceCards(now);
+ const byId = Object.fromEntries(cards.map((c) => [c.id, c]));
+ assert.equal(byId.integration_stripe.headline, "12.50 EUR");
+ assert.deepEqual(byId.integration_stripe.items[0], { label: "Payment", detail: "+9.00 · 2m" });
+ assert.equal(byId.integration_stripe.items[1].label, "Payment failed");
+ assert.equal(byId.integration_resend.headline, "31");
+ assert.deepEqual(byId.integration_resend.items, [{ label: "Delivered", detail: "1m" }]);
+ assert.equal(byId.integration_notion.items[0].label, "Roadmap");
+ assert.equal(byId.integration_github.headline, "1.5k Total stars");
+ assert.equal(byId.integration_vercel.items[0].label, "shop");
+ assert.equal(byId.integration_calcom.items[0].label, "Intro call");
+ const all = JSON.stringify(cards);
+ for (const secret of ["alice", "secret", "Alice", "invoice", "https://", "example.com"]) assert.ok(!all.includes(secret), `${secret} must not be in a card`);
+ for (const id of Object.keys(State.integrations)) delete State.integrations[id];
+});
+
+test("a service that is not configured or is failing has no card, and n8n shows its name and result only", async () => {
+ const { serviceCards } = await import("../src/island/phone-services.ts");
+ service("integration_stripe", { balance: 1 }, { configured: false });
+ service("integration_github", { totalStars: 1 }, { error: "boom" });
+ State.tasks = State.tasks.filter((x) => x.id !== "integration_n8n");
+ assert.deepEqual(serviceCards().map((c) => c.id), []);
+ const n8n = { id: "integration_n8n", name: "n8n", color: "#fff", state: "error", stepIndex: 0, steps: ["Nightly sync", "Error: password=hunter2 at node 3"], source: "n8n", isIntegration: true };
+ State.tasks.push(n8n);
+ const card = serviceCards().find((c) => c.id === "integration_n8n");
+ assert.equal(card.headline, "Failed");
+ assert.deepEqual(card.items, [{ label: "Nightly sync", detail: "" }]);
+ assert.ok(!JSON.stringify(card).includes("hunter2"));
+ State.tasks = State.tasks.filter((x) => x.id !== "integration_n8n");
+ for (const id of Object.keys(State.integrations)) delete State.integrations[id];
+});
+
+test("service cards are published when the link comes up and when they change, and not repeated", async () => {
+ service("integration_github", { totalStars: 3, totalRepos: 1 });
+ dispose = registerPhoneLink(island);
+ await settle();
+ tick(250);
+ const p = () => sent("phone_link_publish_services");
+ assert.equal(p().length, 1);
+ assert.equal(p()[0].services[0].id, "integration_github");
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 1);
+ service("integration_github", { totalStars: 4, totalRepos: 1 });
+ State.notify();
+ tick(250);
+ assert.equal(p().length, 2);
+ for (const id of Object.keys(State.integrations)) delete State.integrations[id];
+});
diff --git a/windows/tests/phone-pairing-hint.test.mjs b/windows/tests/phone-pairing-hint.test.mjs
new file mode 100644
index 00000000..a34ccabe
--- /dev/null
+++ b/windows/tests/phone-pairing-hint.test.mjs
@@ -0,0 +1,26 @@
+// Settings → Android phone: what the pairing link says about itself after "Copy link".
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { installFakeDom } from "./fakedom.mjs";
+import { copyLinkHint } from "../src/settings/phone.ts";
+
+installFakeDom();
+
+test("the hint about the copied link is there but hidden until the link is copied", () => {
+ const hint = copyLinkHint();
+ assert.equal(hint.hidden, true);
+ const text = hint.textContent ?? "";
+ assert.match(text, /pairing code/);
+ assert.match(text, /Pair again/);
+ assert.match(text, /old one stops working/);
+});
+
+test("copying the link shows the hint and keeps it after the button text goes back", () => {
+ const src = readFileSync(new URL("../src/settings/phone.ts", import.meta.url), "utf8");
+ const click = src.slice(src.indexOf('copy.addEventListener("click"'), src.indexOf("const repair"));
+ assert.ok(click.includes("copied.hidden = false"), "the hint is shown by the click");
+ assert.ok(!click.includes("copied.hidden = true"), "and not hidden again by the timer");
+ assert.match(src, /\n\s*copied,\r?\n/, "it sits right under the link");
+});
diff --git a/windows/tests/phone-relay.test.mjs b/windows/tests/phone-relay.test.mjs
new file mode 100644
index 00000000..7288b509
--- /dev/null
+++ b/windows/tests/phone-relay.test.mjs
@@ -0,0 +1,35 @@
+// Settings → Android phone → Away from home Wi-Fi: the status line and the way the access key is handled.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { installFakeDom } from "./fakedom.mjs";
+import { relayStateText } from "../src/settings/phone.ts";
+
+installFakeDom();
+
+const STATES = ["off", "connecting", "waiting", "linked", "accessRefused", "unreachable", "roomTaken", "tooMany"];
+
+test("every relay state has its own plain sentence", () => {
+ const lines = STATES.map((s) => relayStateText(s));
+ for (const line of lines) assert.ok(line.length > 2);
+ assert.equal(new Set(lines).size, STATES.length, "no two states say the same thing");
+});
+
+test("the access key is typed into a password field, sent once and wiped from the page", () => {
+ const src = readFileSync(new URL("../src/settings/phone.ts", import.meta.url), "utf8");
+ const block = src.slice(src.indexOf("function relayBlock"), src.indexOf("function detailsBlock"));
+ assert.match(block, /type: "password"/);
+ assert.match(block, /access\.value = ""/, "the field is emptied after saving");
+ assert.ok(!/localStorage|sessionStorage|console\./.test(block), "the key goes nowhere but Rust");
+ assert.ok(!block.includes("status.access"), "the window never gets the key back");
+});
+
+test("the bridge never asks Rust for the access key", () => {
+ const bridge = readFileSync(new URL("../src/core/bridge.ts", import.meta.url), "utf8");
+ assert.match(bridge, /phoneRelaySetAccess/);
+ assert.ok(!/phone_relay_get_access|relayAccess:/.test(bridge));
+ const status = bridge.slice(bridge.indexOf("export interface PhoneRelayStatus"), bridge.indexOf("export interface PhoneLinkStatus") > 0 ? undefined : undefined);
+ assert.match(status.slice(0, 400), /hasAccess: boolean/);
+ assert.ok(!/access: string/.test(status.slice(0, 400)));
+});