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.

Coucou for Android: the Android app (Kotlin, Jetpack Compose)

Rhytam Biswase0767fbc42e6
diff --git a/.gitattributes b/.gitattributes
index 3598ec2a..fa9d800e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,2 +1,6 @@
docs/** linguist-documentation
design/** linguist-documentation
+
+android/gradlew text eol=lf
+android/**/*.sh text eol=lf
+android/**/*.mjs text eol=lf
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 00000000..00159824
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,29 @@
+name: android
+on:
+ pull_request:
+ paths: ['android/**', 'docs/ANDROID_LINK.md', '.github/workflows/android.yml']
+ push:
+ branches: [main]
+ paths: ['android/**']
+jobs:
+ build:
+ runs-on: ubuntu-24.04
+ defaults: { run: { working-directory: android } }
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-java@v6
+ with: { distribution: temurin, java-version: '17' }
+ - uses: actions/setup-node@v7
+ with: { node-version: '22' }
+ - uses: gradle/actions/setup-gradle@v5
+ - name: English strings are up to date
+ run: node scripts/gen-strings.mjs --check
+ - name: Tests, debug build, lint
+ run: ./gradlew test assembleDebug lint --console=plain
+ - name: No ads, billing or analytics (condition of the author's permission)
+ run: "! grep -rEi 'admob|play-services-ads|billingclient|firebase-analytics|crashlytics|com.google.android.gms' app/build.gradle.kts"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: android-test-reports
+ path: android/app/build/reports
diff --git a/.github/workflows/phone-link.yml b/.github/workflows/phone-link.yml
new file mode 100644
index 00000000..372b42ff
--- /dev/null
+++ b/.github/workflows/phone-link.yml
@@ -0,0 +1,157 @@
+name: Phone link
+
+# Checks for the Android phone link (windows/src-tauri/src/phone_link):
+# the desktop tests on Windows, and the Kotlin client against the real Rust
+# server on Linux. Builds nothing that is published and uploads no artifact.
+
+on:
+ pull_request:
+ paths:
+ - 'windows/src-tauri/src/phone_link/**'
+ - 'android/app/src/**'
+ - 'docs/ANDROID_LINK.md'
+ - '.github/workflows/phone-link.yml'
+ push:
+ branches: [main]
+ paths:
+ - 'windows/**'
+ - 'android/**'
+ - 'docs/ANDROID_LINK.md'
+ - 'docs/RELAY_LINK.md'
+ - '.github/workflows/phone-link.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ windows:
+ runs-on: windows-latest
+ defaults: { run: { working-directory: windows } }
+ steps:
+ - uses: actions/checkout@v7
+ with: { persist-credentials: false }
+ - uses: actions/setup-node@v7
+ with: { node-version: 24, cache: npm, cache-dependency-path: windows/package-lock.json }
+ - uses: actions/cache@v6
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ windows/target
+ key: phone-link-win-${{ hashFiles('windows/Cargo.lock') }}
+ restore-keys: phone-link-win-
+ - run: npm ci
+ - run: npx tsc --noEmit
+ - run: npm test
+ - run: cargo build --release -p coucou-hook
+ - run: cargo test --workspace --locked
+
+ interop:
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v7
+ with: { persist-credentials: false }
+ - name: System libraries the Tauri app compiles against
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
+ librsvg2-dev libgtk-layer-shell-dev libsoup-3.0-dev libssl-dev libxdo-dev
+ - uses: actions/cache@v6
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ windows/target
+ key: phone-link-linux-${{ hashFiles('windows/Cargo.lock') }}
+ restore-keys: phone-link-linux-
+ - name: Rust tests (Linux)
+ working-directory: windows
+ run: |
+ cargo build --release -p coucou-hook
+ cargo test --workspace --locked
+ - uses: actions/setup-java@v6
+ with: { distribution: temurin, java-version: '17' }
+ - uses: gradle/actions/setup-gradle@v5
+ - name: Kotlin client against the Rust desktop
+ working-directory: android
+ env:
+ COUCOU_RUST_INTEROP: '1'
+ run: ./gradlew testDebugUnitTest --tests '*RustDesktopInteropTest' --console=plain
+
+ relay:
+ runs-on: ubuntu-24.04
+ defaults: { run: { working-directory: android/relay } }
+ steps:
+ - uses: actions/checkout@v7
+ with: { persist-credentials: false }
+ - uses: actions/setup-node@v7
+ with: { node-version: 24, cache: npm, cache-dependency-path: android/relay/package-lock.json }
+ - run: npm ci
+ - name: Types
+ run: npm run typecheck
+ - name: Relay behaviour (workerd and the Node twin), guards
+ run: npm test
+ - name: Test vectors are up to date
+ run: npm run vectors
+ - name: A deploy builds (nothing is uploaded)
+ env: { WRANGLER_SEND_METRICS: "false" }
+ run: npx wrangler deploy --dry-run --outdir "$RUNNER_TEMP/relay-build"
+
+ relay-e2e:
+ # The Rust computer and the Kotlin phone, end to end, through the real Cloudflare Worker running locally under
+ # `wrangler dev` (workerd), then through the Node twin. Nothing is deployed; the relay listens on 127.0.0.1 only.
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v7
+ with: { persist-credentials: false }
+ - name: System libraries the Tauri app compiles against
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
+ librsvg2-dev libgtk-layer-shell-dev libsoup-3.0-dev libssl-dev libxdo-dev
+ - uses: actions/cache@v6
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ windows/target
+ key: phone-link-linux-${{ hashFiles('windows/Cargo.lock') }}
+ restore-keys: phone-link-linux-
+ - uses: actions/setup-node@v7
+ with: { node-version: 24, cache: npm, cache-dependency-path: android/relay/package-lock.json }
+ - run: npm ci
+ working-directory: android/relay
+ - uses: actions/setup-java@v6
+ with: { distribution: temurin, java-version: '17' }
+ - uses: gradle/actions/setup-gradle@v5
+ - name: End to end through the Worker (workerd)
+ env: { WRANGLER_SEND_METRICS: "false" }
+ run: android/relay/tools/e2e.sh worker
+ - name: End to end through the Node twin
+ run: android/relay/tools/e2e.sh node
+
+ android:
+ runs-on: ubuntu-24.04
+ defaults: { run: { working-directory: android } }
+ steps:
+ - uses: actions/checkout@v7
+ with: { persist-credentials: false }
+ - uses: actions/setup-java@v6
+ with: { distribution: temurin, java-version: '17' }
+ - uses: actions/setup-node@v7
+ with: { node-version: '22' }
+ - uses: gradle/actions/setup-gradle@v5
+ - name: English strings are up to date
+ run: node scripts/gen-strings.mjs --check
+ - name: Relay test vectors are up to date
+ run: node relay/tools/gen-vectors.mjs --check
+ - name: Relay dependencies (the Node twin that the Kotlin WebSocket tests talk to)
+ working-directory: android/relay
+ run: npm ci
+ - name: Tests, debug build, lint
+ env:
+ COUCOU_NODE_RELAY: '1'
+ run: ./gradlew test assembleDebug lint --console=plain
+ - name: No ads, billing or analytics (condition of the author's permission)
+ run: "! grep -rEi 'admob|play-services|billingclient|firebase|crashlytics|com.google.android.gms|mlkit' app/build.gradle.kts"
diff --git a/android/.gitignore b/android/.gitignore
new file mode 100644
index 00000000..fdc3f200
--- /dev/null
+++ b/android/.gitignore
@@ -0,0 +1,16 @@
+build/
+.gradle/
+local.properties
+*.iml
+.idea/
+*.apk
+*.aab
+.kotlin/
+hs_err_pid*.log
+replay_pid*.log
+*.log
+# Release signing: never in git (the build reads the keystore path and passwords from the environment or Gradle properties)
+*.jks
+*.keystore
+*.p12
+keystore.properties
diff --git a/android/DEMO_VIDEO.md b/android/DEMO_VIDEO.md
new file mode 100644
index 00000000..8c592974
--- /dev/null
+++ b/android/DEMO_VIDEO.md
@@ -0,0 +1,38 @@
+# Demo video for Louis (about 90 seconds)
+
+Louis asked for a short screen recording of the main flow. Nothing is published: the file goes to Louis only.
+
+## Before recording
+
+- Phone: Coucou for Android from the latest `android` branch, Wi-Fi on, same network as the PC, notification volume up.
+- PC: the portable `coucou.exe` (no other Coucou running), Settings > Android phone > Phone link on, phone paired.
+- Claude Code (the command-line tool, not the Desktop app) in a folder you trust, started with `claude.cmd --permission-mode default`.
+- Phone: Do Not Disturb off, "Show Mochi over other apps" on if you want the island in the video.
+- Use a test folder and a harmless command (`echo hello > demo.txt`). No real secrets on screen.
+
+## Shot list
+
+1. Home, connected, Mochi and the agent card (5 s).
+2. Lock the phone. In the terminal, ask Claude Code to write `demo.txt` (10 s).
+3. The screen lights up with the notification: "Approval needed / Unlock to see the request" (8 s).
+4. Unlock and tap Allow with the fingerprint. The phone screen is black here, so cut to the PC with the caption "Request sent for approval", then the terminal continuing (20 s).
+5. A second request: the PC shows it waiting, Deny on the phone, the terminal says it was denied, caption "Denied on the phone" (15 s).
+6. Plan usage and the Chat tab, if switched on (15 s).
+7. Settings > About and Licences: the attribution to Louis (10 s).
+
+## The one catch: secure screens record black
+
+The pairing, chat and approval screens are marked secure on purpose, so a screen recording of them is black. The video
+does not remove that protection. During those seconds it shows the request from the other side instead:
+
+- Record the PC screen at the same time (the terminal waiting on the permission, and Coucou's island or card on the PC).
+- Put a caption over the black part: **"Request sent for approval"**, then **"Approved on the phone (fingerprint)"** or
+ **"Denied on the phone"**. Add the captions when editing (any video editor, or the Windows Clipchamp).
+- Cut between the phone (notification, Home, Settings, About) and the PC (terminal and island), so the viewer always sees
+ something real. Use the other phone as a camera only if Louis wants to see the approval sheet itself.
+
+## How to record
+
+Wireless or USB, from the PC: `adb shell screenrecord --time-limit 180 /sdcard/coucou-demo.mp4`, then
+`adb pull /sdcard/coucou-demo.mp4`. Or use Android's own screen recorder (swipe down twice, Screen recorder).
+Trim to about 90 seconds. Check the file for notifications from other apps before sending it.
diff --git a/android/HANDOFF.md b/android/HANDOFF.md
new file mode 100644
index 00000000..c2b8e462
--- /dev/null
+++ b/android/HANDOFF.md
@@ -0,0 +1,58 @@
+# Handoff: Coucou for Android (read this first)
+
+For a new coding session with no memory of the earlier work.
+
+## What this is
+
+**Coucou** (https://github.com/Louis-CFM/coucou, by Louis Raillé) is a macOS app, with a Windows/Linux Tauri port in `windows/`, where
+**Mochi** shows the state of AI coding agents and lets the user approve their permission requests. **Our project** is the
+Android port in `android/` (Kotlin + Compose), built by Rhytam Biswas (`Rhytam23`) with Claude on branch `android` of the fork
+`Rhytam23/coucou` (`upstream` = Louis-CFM/coucou, read-only for us).
+
+## Rules that must never be broken
+
+Louis agreed by email (`PERMISSION.md`): Mochi, the sounds, visuals, icon and the name "Coucou for Android" for this Android app only, and
+only if it is **free (no ads, paid features or analytics; CI greps for them)**, credits him in the app (About and Licences) with a link to his
+repo, keeps the MIT notice, and **he approves the build and the store listing BEFORE anything is published**. Pushing source to the fork is fine.
+Never create a release, upload an APK, submit to a store, or open a PR to `upstream` without the user saying so.
+
+Repo rules (`CLAUDE.md`): no third-party dependency unless unavoidable; secrets in the keystore; no telemetry; never block the agent; never
+approve a permission without an explicit click; don't restyle Louis's shipped desktop views; pill IDs are never renamed. Don't touch
+`NotchBuddy/`, `relay/` (Louis's APNs relay) or the Mac docs. Android app: English only, dark only. Commit messages end with
+`Co-Authored-By: Claude Sonnet 5.5 <[email protected]>`; push only to `origin android`; `change log.md` stays local.
+
+## Where things are
+
+- `android/app/src/main/kotlin/com/coucou/android`: `mochi/` (engine, painter, `outfit/`), `link/` (protocol, pairing, TLS client, discovery,
+ `WebSocket.kt`, `RelayLink.kt`, `RelayCrypto.kt`, `Transport.kt`, `LinkHealth.kt` (what Home says, the alarm and battery rules), `Reconnect.kt`, `Diagnostics.kt`), `core/` (pure rules), `ui/` (Compose), `app/` (`AppModel`, notifications,
+ `LinkService`, `SecureStore`, biometric gate), `scan/` (QR), `sound/`. Overview and features: `android/README.md`.
+- Desktop side: `windows/src-tauri/src/phone_link/` (hub = rules, server = TLS, pairing, admission, discovery, chat, `relay_client.rs`,
+ `relay_crypto.rs`), front end `windows/src/island/phone-link.ts` and `windows/src/settings/phone.ts`. Protocol: `docs/ANDROID_LINK.md`.
+- Internet relay: `android/relay/` (Worker + Node twin, test vectors), wire `docs/RELAY_LINK.md`, plan and decisions `android/RELAY_PLAN.md`,
+ threat check `android/RELAY_THREAT_CHECK.md`, deploy and test with a phone on mobile data `docs/RELAY_DEPLOY.md`, end to end `android/relay/tools/e2e.sh`.
+- `android/tools/dev-desktop.mjs`: a pretend computer for trying the app (fake data, test tool). `android/PROPOSAL_FOR_LOUIS.md`: draft for the user to send; nothing is opened upstream.
+- CI: `.github/workflows/phone-link.yml` ("Phone link": Windows tests, Linux interop, relay, relay end to end, Android build/tests/lint).
+
+## Checks
+
+```
+cd android && ./gradlew test assembleDebug lint
+node android/scripts/gen-strings.mjs --check # English strings in sync
+cd windows && cargo test --workspace --locked && npm test && npx tsc --noEmit
+cd android/relay && npm ci && npm test && npm run vectors
+```
+
+The Kotlin suite is about 640 tests (some need `node`/`cargo` and skip without them: set `COUCOU_RUST_INTEROP=1` and `COUCOU_NODE_RELAY=1`).
+Gradle and Compose compile only in CI in a cloud session; the pure Kotlin files can be compiled with kotlinc and JUnit.
+
+## What has and has not been seen on a real phone
+
+Seen (Samsung Galaxy A12s, Android 13, earlier stages): Mochi renders, demo mode, pairing over Wi-Fi, Allow reaches the computer.
+**Not seen on a device**: a release (R8) build, which has never been installed (CI builds it unsigned and checks the logs are gone, nothing more); the keep-alive alarm and "Can't connect?" (the Galaxy A12s with the screen off for 10+ minutes is the test), the redesigned screens, the island and its motion, the widget/tile/notification, QR scan, chat, answers,
+file changes, the relay path (and Doze/battery with it), anything on real Cloudflare. CI proves compilation, lint and the unit and
+interop tests, not how it looks or feels.
+
+## Still open
+
+- The user tests each feature on the phone; Louis has not approved a build or a listing.
+- Not built: stage I (send the next instruction to an agent), FCM push, a Play Store listing. Stage G (a VPN) was built and removed.
diff --git a/android/LICENSE b/android/LICENSE
new file mode 100644
index 00000000..aac305ec
--- /dev/null
+++ b/android/LICENSE
@@ -0,0 +1,24 @@
+MIT License
+
+Copyright (c) 2026 Rhytam Biswas
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+The name "Coucou", the Mochi character, the icon and the sounds are (c) Louis Raillé and are not covered by this
+licence; see ../LICENSE-ASSETS.md and PERMISSION.md.
diff --git a/android/PERMISSION.md b/android/PERMISSION.md
new file mode 100644
index 00000000..1dcde561
--- /dev/null
+++ b/android/PERMISSION.md
@@ -0,0 +1,25 @@
+> Update 2026-10-11: Android is now part of the official Coucou repository. Louis Raillé agreed (email) to the licence wording; the name, Mochi, the icon and the sounds are covered by `../LICENSE-ASSETS.md`, where Android is added on his side. This file keeps the history of the original permission, which still applies: the app is free, and nothing is published before both agree.
+
+# Permission from the author
+
+Coucou's name, the Mochi character, the app icon, the sounds and the visuals are
+(c) Louis Raille and are NOT covered by the MIT License (see `LICENSE-ASSETS.md`).
+
+On 8 Oct 2026 Louis Raille gave written permission (email, accepted by Rhytam Biswas)
+to use them in this Android port only, under these conditions:
+
+- Allowed: Mochi (look, expressions, animations), Coucou sounds and visuals, app icon,
+ and the name as "Coucou for Android" with a clear mention that it is an unofficial
+ port based on Coucou by Louis Raille, with a link to the GitHub repository.
+- The app must be free: no ads, no paid features, unless agreed otherwise in writing.
+- Non-exclusive, limited to this Android app, not transferable or sublicensable.
+- Do not use these assets in any other project or product (including IRREAL or anything
+ commercial) without asking first.
+- Keep the MIT notice for the code, and state that the name, character, icon and sounds
+ are (c) Louis Raille and used with permission.
+- Send Louis the build and the store listing (name, description, screenshots) and get
+ his approval BEFORE publishing anything.
+- The permission can be withdrawn if these conditions are not respected.
+
+Release checklist: [ ] attribution screen [ ] no ads/billing/analytics [ ] build and
+listing sent to Louis [ ] approval received
diff --git a/android/PROPOSAL_FOR_LOUIS.md b/android/PROPOSAL_FOR_LOUIS.md
new file mode 100644
index 00000000..f3492e7c
--- /dev/null
+++ b/android/PROPOSAL_FOR_LOUIS.md
@@ -0,0 +1,47 @@
+# Draft message to Louis (the user sends it; nothing is opened on his repo)
+
+Subject: Coucou for Android: an optional phone link in the Windows/Linux app (your call)
+
+Hi Louis,
+
+The Android port you allowed needs something from the desktop app to show real sessions: today Android
+has no CloudKit or APNs, so the phone connects straight to the computer over the local network.
+I wrote that desktop side for the Windows/Linux app, as a separate module, and I'd like to know if you
+want it in Coucou. It's your app and your decision; I'll keep it on my fork if you don't.
+
+What it is
+- Settings gets an "Android phone" section. The switch is **off by default**. When it's on, the app
+ listens for the Android app on the local network only; when it's off, nothing listens, nothing is
+ published and no timer runs.
+- The phone sees the agent sessions and the pending permission request. Allow/Deny from the phone is
+ applied only if it matches the request that is still pending (same fingerprint as the Mac's
+ ApprovalRelay), once, and not after 115 s. Allow asks for the fingerprint or screen lock on the phone.
+ It never blocks the agent: the card on the island keeps working, and the phone is just another way to click.
+- The code is in `windows/src-tauri/src/phone_link/` (about 900 lines with tests) plus a small publisher
+ (`src/island/phone-link.ts`) and the settings section. Existing views are not restyled; the only edits to
+ your code are a `phoneLink` setting, `dropPendingCard` exported from hooks.ts, and the secrets module
+ gaining entries the webview can't reach.
+
+Security choices
+- TLS 1.2/1.3 with a self-signed certificate made once. The phone pins its SHA-256 from the pairing QR.
+- The certificate key and the pairing token are in the OS keystore, never on disk. No keystore, no link.
+- Only private/loopback/link-local peers are accepted; 64 KiB line limit; 8 connections; constant-time
+ token check; "Pair again" revokes the old phone. The pairing code is shown only after a click.
+- No telemetry, no cloud, no relay.
+
+Cost
+- Two new crates: `rcgen` (certificate, plus its `yasna` dependency) and `qrcode` (pairing QR). rustls,
+ tokio-rustls and ring were already in the tree via reqwest. If you'd rather not have the QR, the link can
+ be pasted and `qrcode` goes away.
+
+Tested
+- 38 cargo tests (wrong token, fingerprint mismatch, oversize line, late decision, answered at the desk,
+ pairing again, local-network filter...), 9 front-end tests, and the real Android client against the
+ real server. Not yet verified on a real phone with real sessions. The Settings texts are translated
+ by me in the nine languages and need a native read.
+
+The Mac app is untouched; if you ever want the same on macOS, `docs/ANDROID_LINK.md` is the protocol.
+Nothing from the Android app is published until you've approved the build and the listing.
+
+Thanks,
+Rhytam
diff --git a/android/README.md b/android/README.md
new file mode 100644
index 00000000..4a1ce142
--- /dev/null
+++ b/android/README.md
@@ -0,0 +1,95 @@
+# Coucou for Android
+
+The Android app of [Coucou](https://github.com/Louis-CFM/coucou) by Louis Raillé, by Rhytam Biswas. It shows your coding
+agents as Mochi on your phone and lets you approve or deny their permission requests, answer their questions and chat
+through your computer's AI providers.
+
+The name, the Mochi character, the icon and the sounds are © Louis Raillé and used with permission (see
+[PERMISSION.md](PERMISSION.md)). The Android code is © Rhytam Biswas under the MIT License (see [LICENSE](LICENSE)). The app is free: no ads, no billing, no analytics.
+It is English only and dark only. Not published anywhere: Louis must approve the build and the store listing first.
+
+## Build and test
+
+Needs JDK 17 and the Android SDK (platform 35). From this folder:
+
+```bash
+./gradlew test assembleDebug lint
+node scripts/gen-strings.mjs --check # res/values/strings.xml is generated from i18n/app-strings.json
+```
+
+A release build (R8 shrinking and obfuscation, resources shrunk, `android.util.Log` calls removed, not debuggable) is `./gradlew assembleRelease`;
+`lint` already depends on it in CI, with a check that no debug log text is left in the APK. Signing keys are never in the repository: set
+`COUCOU_KEYSTORE_FILE`, `COUCOU_KEYSTORE_PASSWORD`, `COUCOU_KEY_ALIAS` (and `COUCOU_KEY_PASSWORD` if it differs) in the environment or in
+`~/.gradle/gradle.properties`. Without them the release APK is unsigned (it cannot be installed), never signed with a debug key. Keep
+`app/build/outputs/mapping/release/mapping.txt` with the build you ship. Nothing is published from here.
+
+Without a computer: open the app and tap *Try the demo*. Or run the pretend computer (fake sessions, a fake approval; a test tool):
+
+```bash
+node tools/dev-desktop.mjs --host <LAN IP> # prints a pairing link; flags: --details --answers --diffs --usage --services --fake-chat
+```
+
+The desktop side is in `windows/src-tauri/src/phone_link`; the protocol is `docs/ANDROID_LINK.md`, the internet relay
+`docs/RELAY_LINK.md` (deploy and test it with `docs/RELAY_DEPLOY.md`).
+
+## What it does
+
+- **Home**: the focused agent as a black hero panel (Mochi in the agent's colour, a plain sentence), the other agents below, plan
+ usage and service cards when the computer offers them, and *Recent* (your own Allow/Deny decisions, kept only on the phone).
+ Raw tool names become plain words (`core/ToolLabels.kt`); a command or path is never shown without a deliberate tap (`core/SafeText.kt`).
+- **Requests**: a sheet rises over any screen. Allow needs the fingerprint or screen lock, Deny does not, taps in the first 600 ms
+ are ignored, and each request expires after 120 s. Questions from Claude Code can be answered the same way (the computer must allow it).
+- **Island over other apps** (optional, off by default): a black island from the camera cut-out drops while an agent works, shows
+ the result for 10 s and goes back up with the computer's motion. Needs Android's "Display over other apps". Rules are pure and
+ tested (`core/Island*.kt`); `ui/IslandOverlay.kt` draws.
+- **Chat** (a tab, when the computer offers it), **session details**, **file changes** and **plan usage** are opt-in switches on the
+ computer (Settings > Android phone), all off by default; the phone is told only what it asks for and the computer allows.
+- **Pairing**: scan the QR code with the in-app camera (CameraX + zxing, offline) or paste the link; a scan or a `coucou://pair`
+ link always asks to confirm. The certificate is pinned. If the computer's address changes the phone finds it again by itself (mDNS,
+ checked against the pinned certificate before the token is sent), or you can type the address.
+- **Away from home Wi-Fi** (optional): through your own Cloudflare relay, end-to-end encrypted; the direct link is always tried first.
+- **Keeping the link alive with the screen off**: an alarm every few minutes checks that the computer still answers and reconnects if not (Doze allows nothing more); Home says when and why the link was lost; Settings > Computer > *Can't connect?* checks the network, address, discovery, certificate, pairing code and relay; a calm hint suggests the battery setting ("Unrestricted", with the Samsung steps) only if it would help. Details and limits: `docs/ANDROID_LINK.md`, "Keeping the link alive".
+- **Widget, quick-settings tile, ongoing notification**: agent names and state words only. Updated when something changes, never on a timer.
+- Mochi and his 11 outfits, sounds, wardrobe (Settings), a tap on Mochi slaps him, a long press pets him.
+
+## Getting the phone link running on Windows
+
+1. Download the portable build from the repository's **Windows** workflow run (Actions, Windows, the `Coucou-Windows-portable`
+ artifact). It holds `coucou.exe` and `coucou-hook.exe`.
+2. **Close any other Coucou first.** An installed copy (for example in `C:\Program Files\Coucou`) starts at login and has no
+ phone link, so the phone would say "Connecting…" forever. Then start the portable `coucou.exe`.
+3. Settings > **Android phone** > turn **Phone link** on. It is off by default and listens on your local network only. If Windows
+ asks about the firewall, allow Coucou on **private** networks (a network marked *Public* blocks the phone).
+4. **Show pairing code**, then scan the QR code with the app (or paste the link). The phone and the computer must be on the same Wi-Fi.
+5. Optional, each with its own switch on the same page: session details, answers to questions, file changes, chat through the
+ computer's own keys, plan usage, services.
+
+What to know when you try approvals from the phone:
+
+- Only **Claude Code** (the command-line tool), Codex, Copilot CLI and Muse Code can be approved from Coucou or the phone. Requests
+ from the **Claude Desktop app** are asked in that app only: the computer declines them at once (`windows/src/island/agents.ts`,
+ `APPROVAL_AGENTS`; the same rule as on the Mac).
+- Claude Code must be in a mode that **asks**. In auto or bypass mode it never asks, so nothing reaches the phone. To test:
+ `claude --permission-mode default "…"`, or press Shift+Tab until it says manual mode.
+- The plan usage numbers also come from Claude Code's status line, so they update from the command-line tool and not from the
+ Claude Desktop app.
+- In Windows PowerShell, `claude` can be blocked by the script policy (`claude.ps1 cannot be loaded`). Run `claude.cmd`, use
+ Command Prompt, or allow local scripts for your user with `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`.
+
+For testing without a cable once the phone has been connected by USB once: `adb tcpip 5555`, then
+`adb connect <phone address>:5555`. It resets when the phone restarts or its address changes.
+
+## Security rules the tests guard
+
+Certificate pinning and the pairing token; approval fingerprints, 120 s expiry and decide-once; the biometric gate for Allow;
+`MainActivity` ignores intent extras (only the non-exported `LaunchActivity` can ask for the Allow prompt); `FLAG_SECURE` on pairing,
+chat, approval and question screens; secrets only in the Android Keystore blob; no logging of tokens, answers or relay keys; no ad,
+billing or analytics library.
+
+## Layout
+
+- `app/src/main/kotlin/.../mochi` the engine (pure Kotlin) and the Compose painter; `mochi/outfit` the outfits (ported line by line)
+- `.../link` protocol, pairing, TLS client, WebSocket client, relay, transport choice, demo link
+- `.../core` pure rules (island, navigation, safe text, home text, glance); `.../ui` Compose screens; `.../app` model, notifications, service, storage
+- `relay/` the relay (Cloudflare Worker + Node twin); `tools/` the pretend computer and the outfit trace; `i18n/` the English strings
+- Tests compare pill IDs, colours, outfits and sounds with the desktop sources, so a drift fails the build
diff --git a/android/RELAY_PLAN.md b/android/RELAY_PLAN.md
new file mode 100644
index 00000000..fe55a1b7
--- /dev/null
+++ b/android/RELAY_PLAN.md
@@ -0,0 +1,439 @@
+# Relay plan: Coucou for Android away from home Wi-Fi (PROPOSAL, nothing is built)
+
+Status: **approved by the user on 2026-10-10**, with the decisions and two additions below. Implementation goes stage by stage
+(R0 first); the user is told the commit id after each stage. Nothing is deployed, published or sent to Louis, and Louis's
+`relay/` is not touched. The earlier "stage G" (VPN switch) was built and then removed at the user's request; this plan replaces it.
+
+### Approval record
+
+- **D1 yes** (`tokio-tungstenite` on the PC). **D2 yes**: in-house WebSocket client on Android, with tests for framing, masking,
+ fragmentation, oversized frames and a malformed-input fuzz test; **OkHttp stays the fallback**. **D3 yes** (no forward secrecy
+ for now). **D4 yes** (one phone per room). **D5 yes** (`android/relay/`). **D6 yes** (no FCM for now). **D7 yes** (pad to 128).
+ **D8 yes** (join proof in memory only).
+- **Addition 1, deploy-time access key.** The relay creates or joins rooms only for requests carrying a random 256-bit access key
+ the user sets at deploy time as a Worker secret (`wrangler secret put ACCESS_KEY`, never in git). The PC setting and the
+ pairing link carry it (the link is the only place the phone learns it). The relay **still never sees any content key**. It
+ is checked before any room is created, in constant time, and **the relay fails closed** (no key configured = every room
+ request refused). Rotation is documented in `docs/RELAY_LINK.md` section 7: set the new secret, paste it on the PC; live
+ sockets are closed at their next frame; the PC tells paired phones the new key inside the encrypted channel (`relayAccess`),
+ so they do not have to scan again. This also closes the "burn the free quota with random rooms" hole of section 5: that now
+ needs the access key.
+- **Addition 2, separate directions.** Each direction has its **own key** (`k_p2h`, `k_h2p`) **and** a direction byte in the
+ nonce (`nonce = direction ‖ 000 ‖ counter`), so a (key, nonce) pair cannot repeat across directions even if one of the two
+ protections had a bug; counters only go up by one; every connection derives fresh keys. The generator of the test vectors
+ asserts "no (key, nonce) twice" over thousands of frames, both directions and two sessions; R2 repeats it in Rust and Kotlin.
+- **Stage R0 (done):** `docs/RELAY_LINK.md` (the wire spec) and `android/relay/test-vectors.json` with its generator.
+
+Sources read: `android/HANDOFF.md`, `docs/ANDROID_LINK.md`, `relay/README.md` and `relay/src/index.ts` (Louis's APNs
+relay, for style), the former parity plan (stage G, row 16; deleted in the cleanup, it is in the git history), `CLAUDE.md`, and the phone-link code on both sides.
+
+## 1. Goal and non-goals
+
+**Goal.** The phone and the PC sync over the internet from different networks (phone on mobile data, PC on home
+Wi-Fi), with no USB, no VPN and no shared Wi-Fi. The direct LAN link stays as the fast path and is tried first.
+
+**Non-goals.**
+- No accounts, no sign-in, no database, no analytics, no push provider.
+- No change to protocol v1: sessions, approvals, decisions, chat, diffs and the rest ride inside the secure channel as they are.
+- No built-in third-party endpoint: the relay URL is empty until the user enters one (section 9).
+- Stage I (running instructions on the PC) stays "not planned".
+- Nothing is deployed or published by me. The user deploys with their own Cloudflare account.
+
+## 2. Architecture in one picture
+
+```
+ PC (Coucou, Rust) ──outbound WSS──► Cloudflare Worker ──► Durable Object "room" ◄── outbound WSS ── Phone (Kotlin)
+ (routes by room id) (forwards opaque frames)
+ └────────────────── direct LAN link (TLS, pinned) stays the fast path ──────────────────┘
+```
+
+- **Relay** = one Cloudflare Worker plus one Durable Object class, `Room`. The object's name is the room id. A room
+ holds at most two live WebSockets: one with role `pc`, one with role `phone`.
+- It **forwards binary frames from one socket to the other and nothing else.** It cannot read them (they are end-to-end
+ encrypted), stores nothing (no database, no KV, no R2, no storage API call), logs nothing (observability off, as in
+ Louis's `wrangler.toml`), has no accounts and holds no secret at all (unlike Louis's relay, which holds the APNs key).
+- **Both sides connect outward**, so no port opening, no router setting, no dynamic DNS. Works behind NAT and carrier NAT.
+- The Durable Object uses the **WebSocket Hibernation API**, so an idle room is not billed for duration and holds no memory.
+ Keep-alive pings are answered by the platform (`setWebSocketAutoResponse`) without waking the object.
+
+URL shape: `wss://<the user's worker>/v1/room/<roomId>?role=pc|phone`.
+
+## 3. Pairing and keys
+
+The pairing link and QR gain optional fields (old phones ignore unknown keys and keep pairing over the LAN only):
+
+```
+coucou://pair?v=1&host=...&port=...&fp=...&token=...&name=...&relay=wss%3A%2F%2Fmy-relay.example.workers.dev&room=<22 chars>&key=<43 chars>
+```
+
+- `room`: 128 random bits (base64url, 22 characters). Unguessable. It is a locator, not a secret the design leans on.
+- `key` (**K**): 256 random bits (base64url, 43 characters), created on the PC from the OS random source. Shown only in the
+ pairing code. Stored on the PC in the OS keystore (the same `keyring` store as the pairing token) and on the phone
+ encrypted by the Android Keystore (the same `SecureStore` as the token). Never written to a log, a file or the relay.
+- The existing LAN `token` stays: it keeps authenticating the phone to the PC inside the channel (defence in depth).
+- The phone shows `relay` (the host name) in the existing "Pair with this computer?" confirmation, so the user sees which
+ server is going to carry the traffic before pairing.
+
+**Derived values** (HKDF-SHA-256, RFC 5869, no new dependency: `ring` on the PC, `javax.crypto.Mac` on Android):
+
+| name | derivation | use |
+|---|---|---|
+| `K_auth` | `HKDF(K, info="coucou-relay/v1 auth")` | MACs the two handshake frames |
+| `K_join` | `HKDF(K, info="coucou-relay/v1 join")` | presented to the relay as a join proof (section 6) |
+| `k_p2h`, `k_h2p` | `HKDF(K, salt = N_phone ‖ N_pc, info="coucou-relay/v1 session")`, 32 bytes each | session keys, one per direction |
+
+**Cipher.** AES-256-GCM (hardware-accelerated on both sides; `ring::aead` and `javax.crypto`, so no new crate or library).
+One key per direction and per connection, and a **96-bit nonce = direction byte ‖ 3 zero bytes ‖ 64-bit frame counter** (addition 2). A counter nonce
+is safe here because the keys are fresh for every connection (a restart cannot reuse a (key, nonce) pair). Random
+nonces are not used. A session ends at 2^32 frames and re-handshakes.
+
+**Handshake** (the phone initiates; the PC only answers; the relay's "peer is here" notice is only a hint):
+
+1. Phone connects, then sends `init`: `N_phone` (16 random bytes) + `HMAC(K_auth, "init" ‖ room ‖ N_phone)`.
+2. PC checks the MAC, picks `N_pc`, sends `accept`: `N_pc` + `HMAC(K_auth, "accept" ‖ room ‖ N_phone ‖ N_pc)`.
+ Because the MAC covers the phone's *current* nonce, an old recorded `accept` is rejected.
+3. Both derive `k_p2h` and `k_h2p`. The first data frame each way proves the other side holds K.
+4. Inside the channel the existing v1 `hello`/`welcome` run as today (token, caps, protocol version).
+5. If either side reconnects, steps 1 to 4 run again with fresh nonces: new keys, counters back to 0.
+
+**Frame** (WebSocket binary message): `ver(1) ‖ type(1) ‖ counter(8) ‖ AES-GCM(ciphertext ‖ tag)`.
+- AAD = `"coucou-relay/v1" ‖ room ‖ direction ‖ ver ‖ type ‖ counter`. A frame cannot be moved to another room, turned
+ around, or have its header changed.
+- Data frames carry exactly one v1 line (UTF-8 JSON, at most 64 KiB, as on the LAN), padded to a multiple of 128 bytes
+ so the size does not tell "ping" from "approval" (decision D7).
+- **Replay and reordering:** the receiver requires the counter to be exactly the previous one plus 1. Anything else
+ (repeat, gap, jump back) tears the session down and re-handshakes. Duplicates are never delivered. Frames from an old
+ session fail authentication because the keys differ.
+- **Key rotation:** "Pair again" on the PC makes a new K and room, disconnects the old phone, and the old room stays
+ empty forever. Session keys already rotate on every connection.
+
+**Known limit, said plainly:** the session keys come from K and the two nonces only, so there is **no forward secrecy**.
+If K ever leaks, traffic someone recorded earlier could be decrypted. Adding an X25519 key agreement would fix that;
+`ring` has it, but Android's `KeyAgreement("X25519")` only exists from API 33 (our minSdk is 30), so it would need a small
+hand-written implementation. Decision D3 below; my recommendation is to ship without it and add it later if wanted.
+
+## 4. How protocol v1 rides inside, unchanged
+
+On the PC the existing server logic already runs over "any byte stream" (`server::run_with`). The relay client presents
+the decrypted frames as a newline-delimited stream to that same code, so `hello`, `welcome`, `sessions`, `approval`,
+`approvalResolved`, `decision`, `ping/pong`, `chat*`, `question/answer`, `getDiff/diff`, `usage`, `services`, `prefs` and
+their per-feature switches work **byte for byte as on the LAN**. On the phone, `LinkClient` gets a second connector
+(relay) next to the TLS-socket one. Nothing in `Protocol.kt` or `hub.rs` changes.
+
+What stays exactly as strict as on the LAN:
+
+| rule | on the relay |
+|---|---|
+| approval `fingerprint` (SHA-256 of pill, session, tool, command, input key) | unchanged; the decision names it, the PC applies it only to the approval **still pending** |
+| 120 s offer / 115 s PC dismissal | unchanged; the phone's timer and the PC's both run locally, the relay has no clock role |
+| decide once | unchanged; a second or late decision is ignored by the PC (`Hub::decide`) |
+| Allow needs the biometric or screen lock | unchanged; it is a phone-side gate before the `decision` is even built |
+| Deny does not | unchanged |
+| no "always allow" from the phone | unchanged |
+| per-feature PC switches (details, answers, diffs, usage, services, chat) | unchanged; re-read per connection |
+| command hidden on the lock screen; labels only on Home, island, notifications | unchanged (security hardening just done) |
+
+The relay adds **no new message that can approve anything**. Its own hints (peer online/offline) are shown as status
+only and are never trusted for a decision.
+
+## 5. Abuse and safety
+
+| threat | what happens |
+|---|---|
+| **Guessing a room id** | 128 bits: not feasible. Even with the id, an attacker cannot read or forge frames (no K). The join proof (section 6) also stops them occupying the slot once a real side is in the room. |
+| **Replay of a recorded frame** | Rejected: counter must be previous + 1, and old sessions used other keys. |
+| **Malicious or compromised relay** | Can drop, delay or cut frames (availability), and see metadata (below). **Cannot read content, forge a frame, forge an approval, or forge Allow/Deny.** A forged or altered frame fails the GCM tag and tears the session down. |
+| **Relay delays an approval** | The PC still only accepts a decision for the approval still pending; the phone offers it for at most 120 s from receipt; a late or duplicate decision is ignored. A delay cannot turn Deny into Allow. |
+| **Relay drops a decision** | The approval times out on the PC and is not allowed. Failure is on the safe side. |
+| **Relay truncates the end of a conversation** | Undetectable (a close looks like a close). It is a denial of service, not a break. |
+| **Stolen phone** | Has K and the token, but Allow still needs the biometric or screen lock; Deny does not. The user does "Pair again" on the PC: new K and room, the stolen phone is cut off at once. Phone-side storage is Keystore-encrypted. |
+| **Stolen PC / PC compromise** | Out of scope: it holds the agents and the keys anyway. |
+| **Eavesdropper on the network** | Sees TLS to the relay (and E2E ciphertext inside). |
+| **Flooding the relay** | Per-room message token bucket in the object (about 30 messages/s sustained, burst 60) and a per-IP connect limit at the Worker (Workers Rate Limiting binding); frame limit 66 KiB (anything bigger closes the socket with 1009); 2 sockets per room, newest of a role replaces the oldest only if it presents the join proof; the room id format is checked in the Worker before any object is created, so malformed paths cost nothing. |
+| **Creating many empty rooms to burn the free quota** | Needs the deploy-time access key (addition 1); a request without it is refused with `401` before any room exists. Someone who holds the key (every paired phone does) could still burn the quota; the fix is to rotate the access key (docs/RELAY_LINK.md section 7). If the quota is exhausted the app falls back to the LAN and shows "Relay unavailable"; the paid Workers plan removes the cap. |
+| **Reflection** (sending a side's own frame back) | Different key per direction and the direction in the AAD: rejected. |
+| **Downgrade** (pretending the peer has no relay) | Not a downgrade: the LAN path is a separate, equally strict, pinned-TLS path. |
+| **Phone talks to a fake PC through the relay** | The fake has no K: its `accept` MAC fails. |
+| **Two phones** | v1 of the relay supports one phone per room (D4); a second phone is a second pairing. The LAN link keeps supporting several. |
+
+**What the relay operator (the user, on their own Cloudflare account) and Cloudflare can learn:** the IP addresses of the
+PC and phone, that a pairing exists (the room id is stable per pairing), when each side is online, frame sizes
+(padded to 128 bytes) and timing, so roughly "something is happening". **They cannot learn:** any session name, command,
+path, approval, chat text or file name, and not K.
+
+## 6. The relay's rules, in detail
+
+- `GET /` answers `Coucou link relay` (a health check, like Louis's).
+- `GET /v1/room/<id>?role=pc|phone` with `Upgrade: websocket`; `<id>` must be 22 base64url characters, else 404 before any
+ object is touched; `Authorization: Bearer <access key>` must match the Worker secret (401, constant-time, fail closed).
+ Sub-protocol offer `coucou.v1, coucou.join.<K_join>` carries the join proof (base64url of 32 bytes). The wire is specified in `docs/RELAY_LINK.md`.
+- **Join proof, held in memory only:** the first socket of a room sets `verifier = SHA-256(K_join)` in the socket's
+ hibernation attachment (not storage). Later sockets must present a `K_join` that hashes to the same value or are refused
+ (1008). When the room is empty the verifier is gone, so nothing is ever stored. Consequence: an attacker who knows the
+ room id could squat an *empty* room before its owner connects; they still could not read or inject anything, and the
+ legitimate PC would be refused until the squatter leaves, so the PC would show "Relay room is taken" and "Pair again"
+ would fix it. I think that trade-off is right; the alternative (persisting a verifier) would make the relay stateful.
+- Hints sent by the relay as small text messages (`{"peer":"online"|"offline"}`) when the other side joins or leaves.
+- A role's new connection replaces the old one only with a valid proof (closes it with 1000 "replaced").
+- Keep-alive: a client text `ping` is answered `pong` by the platform without waking the object. No idle timer in the relay (a timer would wake the room); clients judge liveness themselves.
+- Limits: 66 KiB per frame, token bucket per room, 2 sockets per room, no queueing (a frame for an absent peer is dropped,
+ and the sender hears `{"peer":"offline"}`). No message is ever buffered, so nothing is stored by accident.
+- `wrangler.toml`: `[observability] enabled = false`, `new_sqlite_classes = ["Room"]` (Durable Objects on the free plan need the
+ SQLite-backed class; we do not use its storage), no `[vars]` with secrets. The one secret, `ACCESS_KEY`, is set with
+ `npx wrangler secret put ACCESS_KEY` and is never in git.
+- No third-party npm runtime dependencies in the Worker; dev dependencies: `wrangler`, `typescript`, `vitest`, `@cloudflare/vitest-pool-workers`.
+
+## 7. Android in the background
+
+Today `LinkService` is a foreground service of type `specialUse` that holds the LAN link, with a 20 s app-level ping.
+The relay transport lives inside the same service. Design:
+
+- **Transport choice:** try the saved LAN address first (2 s, as now), then NSD discovery, then the relay if the pairing has
+ one. When on the relay, retry the LAN once a minute while on Wi-Fi (and at once when the Wi-Fi changes) and switch back,
+ because the LAN is faster and costs the relay nothing. One transport is active at a time; a switch reconnects and the PC
+ re-sends the snapshot and any pending approval (the existing reconnect behaviour).
+- **Keep-alive:** a WebSocket ping every ~30 s answered by the platform (cheap for the relay), plus the existing encrypted v1
+ `ping/pong` every 20 s from the phone only while the screen is on or an agent is working; with the screen off and nothing
+ running, only the 30 s WebSocket ping. Carrier NATs often drop idle TCP flows between 30 s and a few minutes, so ~30 s is
+ the safe side. This is the main battery cost: radio wake-ups every 30 s while paired and away. **I have not measured it.**
+ The staging plan measures it with `dumpsys batterystats` over a night.
+- **Doze:** I do not know for certain how Doze treats network access for a `specialUse` foreground service on the A12s
+ (Android 13). It is the biggest unknown of this plan. The staging test (screen off, phone still, 30+ minutes, mobile data)
+ answers it. If the connection is cut, the first fixes are the standard ones (battery-optimisation exemption, shown to the
+ user with the exact setting); the next is FCM as a wake-up signal (below).
+- **Reconnect:** exponential backoff from 1 s to 60 s with jitter, reset on success; immediate retry when the network
+ changes (`NetworkWatch` exists); no retry loop while the phone has no network or the user disconnected.
+- **FCM, and why not now.** FCM would wake the phone reliably in Doze, but it needs Google Play services and a Firebase
+ project, the `google-services` plugin and `firebase-messaging` (a large closed-source dependency and a Google account in
+ the chain), would not work on phones without Google services, and a relay would then need a server credential (a secret to
+ guard). That is against "no third-party dependencies", against the "free of built-in third-party endpoints" goal, and
+ against the project's no-Play-services rule (the QR scanner was built without it for the same reason). So: **not now.**
+ If the Doze test shows the foreground service is not enough, I would propose FCM as an optional later stage carrying an empty
+ "wake up" signal only (no content: the phone then opens the WebSocket and gets everything E2E), decided with you after the data.
+- Notifications, the island and the biometric Allow are untouched: they react to the same `LinkListener` events.
+
+## 8. Cost, hosting and limits
+
+- **Who deploys:** you, with your own Cloudflare account (free). I write the Worker, a deploy guide and the commands; I do
+ not deploy it and no secret exists to put in git.
+- **Free-tier limits (from my memory of Cloudflare's published limits; I will re-check the pages before the deploy guide is written,
+ and you should too):** Workers about 100,000 requests/day; Durable Objects about 100,000 requests/day, with incoming
+ WebSocket messages counted at roughly 1/20 of a request, plus a daily duration allowance that hibernation keeps near zero
+ while idle. Rough budget for one PC and one phone: a few thousand frames a day while agents work, 2,880 pings/day: on the
+ order of a few hundred "requests" a day, far below the cap. A busy setup of ten paired phones is still comfortable.
+- **When exceeded:** Cloudflare refuses requests until the daily reset; the relay is unavailable, the app says "Relay
+ unavailable", the LAN keeps working, and nothing is lost (no data is stored anywhere). The paid Workers plan (about $5 a month)
+ removes the cap.
+- **Self-hosting:** the relay is about 150 lines of TypeScript with no secrets. I will also ship a Node reference
+ (`dev-relay.mjs`, used by the tests) that speaks the same wire, so it can be run on a small VPS or a Raspberry Pi. Any
+ server that forwards two WebSocket peers by room id and enforces the same limits works.
+- **Configurable relay URL, default none:** Settings on the PC has a field, empty by default, and the relay is off. The
+ phone receives the URL only through the pairing link and shows its host before pairing. The Android app has **no built-in
+ endpoint**, and neither does the PC app. This matches `CLAUDE.md` ("network calls only to services the user configured").
+
+## 9. Desktop side
+
+- **Settings → Android phone → "Away from home (relay)":** a switch next to Phone link, **off by default** (`phoneRelay` in
+ settings, owned by Rust like the other phone switches), the relay URL field (empty), a status line ("Off", "Connecting",
+ "Connected, phone online", "Connected, phone offline", "Relay unavailable", "Room is taken") and a hint under the pairing code
+ explaining that the link now also contains the key for the relay. Turning it on or off disconnects phones once, as the
+ other switches do. Needs the Phone link switch on; turning on with an empty URL is refused with a clear message.
+- **How the PC connects out:** an async task in the existing tokio runtime. It opens `wss://<relay>/v1/room/<room>?role=pc`,
+ waits for the phone's `init`, answers `accept`, then runs the existing v1 server code over the decrypted stream. It never
+ runs on the hook path: **it cannot block Claude Code** (rule from `CLAUDE.md`); if the relay is unreachable the agent is
+ unaffected.
+- **Admission:** the relay connection counts as one extra source in the existing admission policy and takes no LAN slot.
+- **Sleep and network changes:** when the PC sleeps the socket dies; the phone sees "Computer offline" and shows nothing
+ stale as live (it is marked offline within a few seconds of the relay's hint, and by the encrypted ping timeout otherwise).
+ On wake the task reconnects with backoff, and the phone re-handshakes. Agents do not run while the PC sleeps, so nothing
+ is missed; an approval that was pending when the PC fell asleep simply expires (the agent is not allowed). The PC does not
+ keep itself awake for this.
+- **Logging:** the relay URL host and status transitions only. Never K, tokens, frames, rooms or commands.
+
+## 10. What Louis should be told (draft for the user to send, or not)
+
+- Louis's `relay/` is a Cloudflare Worker that holds his **APNs key** and does one job: Live Activity pushes for the iPhone. It is
+ not touched.
+- The Android fork would add a **separate, key-less, user-deployed** relay (`android/relay/`, never under his `relay/`), used only
+ by Coucou for Android, **off by default, with no URL built in**, and nothing flows to any server he runs or pays for.
+- The PC-side part sits in `windows/src-tauri/src/phone_link/` behind an opt-in switch; if he ever wants it upstream it is a
+ small, self-contained, reviewed change, and no PR is opened without the user's decision.
+- No telemetry, no accounts, no third party in the data path except the user's own Cloudflare account, and the payload is
+ end-to-end encrypted, so even that account cannot read it.
+- `android/PROPOSAL_FOR_LOUIS.md` would get a short section with the above after you approve; nothing is sent.
+
+## 11. Stages
+
+Each stage is a small series of commits with tests, "Phone link" CI green, `Co-Authored-By`, pushed only to `android`.
+
+| # | Stage | What | Tests |
+|---|---|---|---|
+| R0 | Spec and vectors **(done)** | `docs/RELAY_LINK.md` (wire, access key, handshake, frame, limits, rotation) and `android/relay/test-vectors.json` + generator `android/relay/tools/gen-vectors.mjs` | generator self-checks (RFC 5869 vector, no (key, nonce) twice), CI `--check`, an independent Python re-computation; the vectors are used by R2 on both sides |
+| R1 | Relay service **(done)** | `android/relay/` Worker + `Room` object, `wrangler.toml` (observability off, no secrets), `dev-relay.mjs` (Node twin for tests/self-host), deploy README | **vitest + miniflare** (`@cloudflare/vitest-pool-workers`): routing by id, bad ids refused before object creation, join proof, replacement rules, size limit 1009, token bucket, peer hints, no buffering when the peer is absent, **no storage calls**, no plaintext handling. `tsc` clean. |
+| R2 | Secure channel core **(done)** | Rust module (`phone_link/relay_crypto.rs`: HKDF, AES-GCM frames, handshake, counters) and Kotlin twin (`link/RelayCrypto.kt`) with no I/O | RFC 5869 HKDF vectors; the shared vectors both ways; wrong key, wrong room, wrong direction, flipped bit, truncated, replay, gap, reorder, old `accept`, counter limit; K never in `Debug`/`toString`/log text (a test greps); cross-language: Rust decrypts what Kotlin made and the reverse |
+| R3 | PC client **(done)** | WS client task (**D1**), settings `phoneRelay` + URL, pairing link fields, status, Settings UI block + 9-language strings, admission, "Pair again" rotates K and room | Rust tests with an in-process fake relay; settings tests (off by default, wrong type stays off); i18n test; a flood/disconnect test; the PC never blocks on an unreachable relay |
+| R4 | Android client **(done)** | WS client (**D2**), `RelayConnector` for `LinkClient`, transport selection (LAN first, relay fallback, LAN retried), SecureStore for K, pairing parser, "Away from home Wi-Fi" card in Settings, debug trigger | Kotlin tests: WS framing against the Node twin, handshake, selection and switch-back rules (pure, fake clock), parser accepts old and new links, K stored only encrypted |
+| R5 | End to end and CI **(done)** | CI job runs the **real Worker under `wrangler dev` (miniflare)** and connects the Rust PC client and the Kotlin phone client through it: sessions, an approval, deny, allow-gate unchanged, decide-once, PC restart, phone restart, "Pair again" cuts the old phone | the full v1 suite once more over the relay; interop tests |
+| R6 | Review **(done)** | a written threat-model check against section 5 with a test or an explicit "cannot test" for every row; deploy guide; staging checklist | as above |
+
+### Findings while building R1
+
+- The Workers test plugin was renamed upstream: R1 uses `@cloudflare/vitest-plugin` 1.4.0 (the old `vitest-pool-workers` is
+ deprecated) with `vitest` 4.1.x. npm's resolver crashes on its peer range, so `android/relay/.npmrc` sets `legacy-peer-deps`.
+- The sub-protocol offer is `coucou.v1, coucou.join.<proof>` (a strict client needs the server's choice to be one it offered).
+- The relay has no idle timer (it would wake the room); the heartbeat is a text `ping` answered `pong` by the platform.
+- The Workers Rate Limiting binding works in workerd; the tests raise its limit and the 429 path has its own test.
+- Wrangler may send anonymous usage statistics (Cloudflare's tool, not ours): the guide says how to turn it off.
+
+### Findings while building R2
+
+- Rust (`phone_link/relay_crypto.rs`, `ring`: HKDF, HMAC, AES-256-GCM, no new crate) and Kotlin (`link/RelayCrypto.kt`,
+ `javax.crypto`, a hand-written 20-line HKDF checked against RFC 5869) both reproduce **every byte** of
+ `android/relay/test-vectors.json`, which Node and an independent Python implementation also produced. Because the vectors are
+ deterministic, "Rust reads what Kotlin wrote and the reverse" holds byte for byte.
+- A mutation test found a gap in my first Rust tests (both directions sharing one key went unnoticed because the vectors were
+ checked with the helper functions, not with the `Session` itself). Fixed: both twins now have a test where the sessions
+ themselves must reproduce the vector frames in each direction.
+- A frame whose counter byte is altered is refused by the counter rule (`BadCounter`) before its tag is looked at; the vector
+ file calls that case a bad tag, either way it is refused and the session is dead.
+- No forward secrecy, as decided (D3).
+
+### Decisions (all answered yes; the text is kept for the record)
+
+- **D1, WebSocket on the PC:** add the small `tokio-tungstenite` crate (MIT, rustls) or hand-write the WebSocket client over the
+ `tokio-rustls` we already have. Recommendation: the crate (a hand-rolled framing/handshake is where subtle bugs live; one
+ well-known dependency, justified in the commit as `CLAUDE.md` requires).
+- **D2, WebSocket on Android:** OkHttp (large, well-tested, Apache 2.0) or a minimal in-house client over `SSLSocket` (about
+ 250 lines: text/binary/ping/pong/close, no extensions; tested against the Node twin and the Worker). Recommendation: in-house,
+ to keep the "no third-party dependency" rule; fall back to OkHttp if it proves flaky in staging.
+- **D3, forward secrecy:** ship now without it (recommended) or add an X25519 exchange first (needs a hand-written X25519 on
+ Android below API 33).
+- **D4, one phone per room** in v1 of the relay (recommended); more phones = more pairings.
+- **D5, location:** `android/relay/` (recommended, so Louis's `relay/` is never touched) versus a new top-level folder.
+- **D6, FCM:** not now, revisit after the Doze test (recommended).
+- **D7, size padding to 128 bytes** (recommended; costs a few bytes per frame).
+- **D8, join proof held in memory only,** with the squatting trade-off in section 6 (recommended), versus persisting a verifier.
+
+## 12. Deploy guide (written in R6: `docs/RELAY_DEPLOY.md` is the real one; this outline is kept for the record)
+
+```
+cd android/relay
+npm install
+npx wrangler login
+npx wrangler deploy # prints https://coucou-link.<you>.workers.dev
+curl https://coucou-link.<you>.workers.dev/ # "Coucou link relay"
+```
+
+One secret is needed, the access key, and it never goes in git: `openssl rand -base64 32 | tr '+/' '-_' | tr -d '='` to make it, then `npx wrangler secret put ACCESS_KEY` and paste it. The relay holds no content key. `wrangler.toml` contains no key. On the PC: Settings → Android phone →
+"Away from home (relay)": paste the URL and the access key (write-only field, stored in the OS keystore), switch on, show the pairing code. On the phone: pair again (scan), check the host shown.
+
+## 13. Staging test plan (the real, numbered checklist is in `docs/RELAY_DEPLOY.md` section 4)
+
+1. Deploy as above. Confirm `curl` answers. In the Cloudflare dashboard confirm **Observability/logs are off** (we never log payloads).
+2. PC: switch the relay on, paste the URL, show the pairing code. Status should read "Connected, phone offline".
+3. Phone: turn Wi-Fi **off** (mobile data only), scan the code, read the host in the confirmation, pair.
+ Expect: "Away from home Wi-Fi: connected via relay" and the PC shows "phone online".
+4. Start an agent on the PC: sessions appear on the phone. Trigger a permission request: the sheet appears, Deny works, Allow asks for the
+ screen lock, then the agent proceeds. Press the same decision twice quickly: the second is ignored.
+5. Let a request sit 2 minutes: it expires on both sides, and a late tap is refused.
+6. Put the phone on the home Wi-Fi: it switches to the direct link within a minute, and back to the relay when you leave.
+7. Sleep the PC for a minute, wake it: the phone shows "Computer offline", then recovers by itself.
+8. Kill the relay URL (change it on the PC): the PC shows "Relay unavailable", the agent is never delayed, and the LAN still works at home.
+9. "Pair again" on the PC: the phone is cut off at once and must scan the new code; the old phone cannot reconnect.
+10. **Doze/battery:** phone on mobile data, screen off, stationary, 30 minutes: does an approval still arrive? Then overnight:
+ `adb shell dumpsys batterystats --reset` before, `--charged com.coucou.android` after; report the percentage used.
+11. `npx wrangler tail` during a session: it should show connections and **no frame contents** (there are none to show).
+
+## 14. What I will not be able to test, said now
+
+- Doze and carrier-NAT behaviour on a real phone (only you can, section 13).
+- The Cloudflare free-tier limits and billing (from memory; verify on their pages; the deploy is yours).
+- Real battery cost.
+- The Windows build against a real WebSocket server (CI covers Windows tests, not a live relay).
+- That Cloudflare's WebSocket Hibernation and auto-response behave as documented in production (miniflare approximates them).
+
+## 15. Rules kept
+
+Nothing published, no release, no store listing, no PR to upstream; commits end with
+`Co-Authored-By: Claude Sonnet 5.5 <[email protected]>`; pushes only to `android`; the Android app stays English only;
+new PC strings get the nine translations; `change log.md` stays local; secrets in the keystores; no telemetry; the agent is never blocked;
+no permission is ever approved without an explicit click and the phone's screen-lock check.
+
+### Findings while building R3
+
+- The WebSocket framing is `tokio-tungstenite` 0.26 with **no TLS feature** (D1): TLS is the `tokio-rustls`/`ring` already in the
+ tree, with the web roots (`webpki-roots`) that `reqwest` already pulled in, so no second crypto provider (aws-lc) is added. New
+ direct dependencies: `tokio-tungstenite`, `webpki-roots`, `futures-util` (sink trait only); `tokio` gained `macros`.
+- The relay client is one task (`phone_link/relay_client.rs`). It reuses the LAN server's conversation code unchanged: decrypted
+ lines go into an in-memory pipe whose other end is `server::run_with`, exactly the function the TLS path uses, so fingerprints,
+ 120 s offers, decide-once, per-feature switches and the token check are the same code, not a copy. A test sends a wrong token
+ and a wrong fingerprint through the relay and gets the same refusals as on the LAN.
+- **Admission.** Everything arriving through the relay is one source (`192.0.2.255`, a documentation address that is never
+ routable) with one slot at a time. A newer `init` replaces the previous conversation, so a flood of `init` frames cannot take
+ more than one slot; 3 bad handshake frames silence `init` for 10 s.
+- Secrets: the access key, the room and K are in the OS keystore (`phone-relay-access/-room/-key`), `Credentials` and the pairing
+ key print as `(..)`, the module has no logging at all (a test reads its source), and the Settings window can only write the
+ access key (the status it gets back says whether one is stored).
+- "Pair again" now also makes a new room and a new K, then reconnects, so a phone holding the old ones is cut off at the relay as
+ well as at the PC.
+- `relay` capability: offered to a phone that asks for it only while the relay switch is on; when the access key is replaced, the
+ phones that negotiated it are sent `relayAccess` inside the encrypted channel (an older phone is never sent it).
+- A test that replays a recorded frame, flips a frame and sends frames sealed under old session keys shows each one ends the
+ conversation and gives the slot back.
+- Not tested here: a real Cloudflare relay (R5 runs the real Worker under `wrangler dev`) and a real phone (R4).
+
+### Findings while building R4
+
+- **The WebSocket client is ours (D2)**: `link/WebSocket.kt`, about 350 lines, no library. Tests for framing (RFC 6455 section 5.7 examples, every
+ length boundary), masking (fresh mask per frame, an unmasked client frame is a bug), fragmentation (with a ping in between, a UTF-8
+ character split across fragments), oversize (a header claiming 1 GiB is refused before anything is allocated; a message over the limit
+ even in small fragments), the server rules (reserved bits, masked server frames, fragmented or long control frames, unknown opcodes,
+ bad close codes), a truncated stream, 30,000 random inputs and 20,000 bit-flipped valid streams (only a protocol error or end of stream
+ may come out), and the upgrade (RFC accept value, header injection, every wrong response). Six mutations (no masking, masked server
+ frames accepted, no size limit, no relay-first window, an accept for another init, partial relay fields accepted) are each caught.
+ OkHttp stays the fallback; `RelayGuardsTest` fails if any WebSocket library is added to Gradle without this decision being revisited.
+- **Checked against someone else's WebSocket**: `RelayNodeTwinTest` talks to the relay's Node twin (the `ws` package, a separate
+ implementation of the RFC): both directions, five 40 KB lines in a row, the unchanged `LinkClient` hello/welcome, a wrong access key
+ (401), a wrong pairing key in a room in use, a computer that is not there, one that joins later, one that leaves, and a second phone
+ replacing the first. It runs when `COUCOU_NODE_RELAY=1` (CI does `npm ci` in `android/relay` first); everything else runs everywhere.
+- The Node twin refused to start on Node 22 because `Bucket` used a constructor parameter property, which Node's type stripping does not
+ allow although the file said "erasable TypeScript only". Fixed in `src/protocol.ts` (plain fields); the relay's own tests still pass.
+- **`LinkClient` did not change** except for the new capability: the relay is a `Connector` returning a `Socket` whose bytes are the
+ encrypted lines (`RelayStreamSocket`). A test runs the real `LinkClient` over it (hello, welcome, approval, decision).
+- **Selection rules** are pure (`TransportPolicy`, tested with a fake clock): LAN first with a 2.5 s timeout, the relay when the LAN does
+ not answer, the relay first for 60 s after a LAN failure (with the LAN as fallback if the relay fails too), a LAN probe every 90 s
+ and on a network change while on the relay, and a switch back as soon as the LAN answers. The probe is one pinned TLS handshake that
+ is closed at once; it runs only while the link is on the relay.
+- A failure to write `init` hid the relay's close reason (the connection was already gone): the connector now reads the close frame
+ after a failed write, so "room is taken" is told apart from "network dropped". Found by a test.
+- The pairing, K and the access key stay in the same Keystore-encrypted blob as the token (`PairingCodec`; a pairing saved by an older
+ build loads as LAN-only). Nothing in the new code logs, and a test fails if a log line in `AppModel` names a relay secret.
+- New Settings card "Away from home Wi-Fi" (a switch, on by default, shown only when the pairing has a relay, and one sentence saying
+ how the phone is connected right now or why not). (A debug-only broadcast that skipped the direct link was removed in the cleanup.)
+- Not tested here: Compose and lint (CI only), a real phone, the Doze behaviour and battery cost of the foreground-service WebSocket, and
+ real Cloudflare. R5 runs the Rust PC against the Kotlin phone through the real Worker.
+
+### Findings while building R5
+
+- `android/relay/tools/e2e.sh [worker|node]` starts the relay (the real Worker under `wrangler dev`, i.e. workerd on this machine, or
+ the Node twin) on 127.0.0.1 with fixed test credentials, runs the **Rust** computer side
+ (`relay_client::tests::e2e_the_computer_side_for_the_phone_test`, ignored by default) and the **Kotlin** phone side
+ (`RelayE2ETest`) together, and reports OK only when the phone's decision reached the computer: the real `relay_client.rs`, the real
+ `LinkClient` over the in-house WebSocket, the real hub and the real relay code in between. Both modes passed here. It also checks the
+ Worker's `401` for a wrong access key.
+- This is the first test where Rust and Kotlin talk to each other through the relay, not only through shared vectors. It found nothing
+ to fix, which is also a result.
+- CI job `relay-e2e` runs both modes on every push. It deploys nothing and the relay listens on loopback only.
+- Still not covered: real Cloudflare (hibernation timing, the real rate-limit binding across data centres, the 100 s idle behaviour of
+ a WebSocket without traffic) and a phone on mobile data. That is the staging test (`docs/RELAY_DEPLOY.md`).
+
+### Findings while building R6
+
+- The threat check is in `android/RELAY_THREAT_CHECK.md`: every row of section 5 with the test that fails if it stopped being true, and
+ what is accepted or not covered. Reading the code again as an attacker found two real problems, both fixed with tests: the phone
+ refused links over 1,024 characters, which the relay fields plus a long accented computer name could exceed (limit now 2,048, and a
+ Rust and a Kotlin test build the longest realistic link and check the parser and the QR); and the phone's pairing confirmation did not
+ show the relay's host as the spec says (it does now). Two further tests were added for rows that had none (a fake computer without K,
+ and "Pair again" cutting off the old pairing).
+- The deploy guide and the staging checklist for the phone on mobile data and the computer on home Wi-Fi are `docs/RELAY_DEPLOY.md`.
+- What is still open is only what cannot be done here: a real phone (Doze, battery), real Cloudflare, and the look of the Settings card.
diff --git a/android/RELAY_THREAT_CHECK.md b/android/RELAY_THREAT_CHECK.md
new file mode 100644
index 00000000..db01fe74
--- /dev/null
+++ b/android/RELAY_THREAT_CHECK.md
@@ -0,0 +1,68 @@
+# Relay: threat-model check (stage R6)
+
+A line-by-line check of `RELAY_PLAN.md` section 5 against what was built. For each threat: what stops it, **which test would fail
+if that stopped being true**, and what is accepted or not covered. Written after the code, by reading it again as an attacker,
+not from the plan. "Not testable here" means exactly that; it is not a claim that it works.
+
+Test names are abbreviated: *Rust* = `windows/src-tauri/src/phone_link/` (`relay_crypto.rs`, `relay_client.rs`, `hub.rs`),
+*Kotlin* = `android/app/src/test/.../link/`, *relay* = `android/relay/tests/`.
+
+## The table
+
+| Threat | What stops it | Test that fails if it stops | Accepted / not covered |
+|---|---|---|---|
+| **Guessing a room id** | 128 random bits; a wrong path, id or role is `404` before any room exists; the join proof stops a second key in a held room | relay: *refuses a bad path, room id or role with 404 and creates no room*, *never contacts a room for a request it refuses*, *refuses a second key for a room that is held (1008)* | Squatting an **empty** room before its owner connects needs the access key *and* the room id. The owner then sees "in use somewhere else"; **Pair again** fixes it. Accepted (making the verifier persistent would make the relay stateful) |
+| **Replay of a recorded frame** | Counter must be exactly the previous plus 1; every connection derives new keys from fresh nonces | Rust *counter_sequences_follow_the_rule*, *a_tampered_replayed_or_reordered_frame_ends_the_conversation*; Kotlin *RelayCryptoTest* counter tests, *aTamperedReplayedOrReorderedFrameEndsTheStream* | none |
+| **Malicious or compromised relay** | AES-256-GCM with a key only the two ends hold; a changed or forged frame fails the tag and ends the session | Rust *frames_that_must_be_refused_are_refused...*, *a_tampered_...*; Kotlin the same vectors and *aTampered...* | The relay can **drop, delay, cut** frames and see metadata. Accepted: that is availability, not confidentiality or integrity |
+| **Relay delays an approval** | Unchanged v1 rules inside the channel: the computer accepts a decision only for the approval still pending (fingerprint match, decide-once), the phone offers it for at most 120 s from receipt | Rust *hub.rs* approval tests (same code as the LAN); *a_phone_pairs_through_the_relay...* (a decision for another fingerprint does nothing; the right one is applied once) | none |
+| **Relay drops a decision** | The approval expires on the computer and is not allowed (fails safe) | Rust *hub.rs* expiry tests | none |
+| **Relay truncates a conversation** | Nothing can detect it (a close looks like a close) | n/a | Denial of service only. Accepted |
+| **Relay forges "the phone left" or "the computer left"** | The `{"peer":...}` hints are unauthenticated and are used for the status line and to end a conversation, nothing else; **a client cannot send a text message** (anything but `ping` closes its socket with `1003`) so only the relay itself can say it | relay: *answers a text 'ping' with 'pong' and closes on any other text (1003)*; Rust *when_the_relay_says_the_phone_left...*; Kotlin *theComputerLeavingEndsTheStream* | A hostile relay can end a conversation. Same as truncation. Accepted |
+| **Stolen phone** | It has K and the token, but **Allow** still needs the fingerprint or screen lock; **Pair again** makes a new K and room, so the old phone is cut off; K is inside the Keystore-encrypted blob | Rust *after_pair_again_the_old_pairing_gets_no_answer_and_the_new_one_works*, *the_pairing_is_made_once_kept_and_replaced_on_demand*; Kotlin *PairingCodecTest*, *RelayGuardsTest.theSecureStoreKeepsEverything...* | A stolen **unlocked** phone is out of scope. The thief also has the relay's access key (quota only): rotate it if you care (`RELAY_DEPLOY.md` row 12) |
+| **Stolen or compromised computer** | Out of scope (it holds the agents and the keys anyway) | n/a | n/a |
+| **Eavesdropper on the network** | TLS to the relay, end-to-end ciphertext inside | Kotlin *RelayConnectorTest* (the access key and join proof are in headers only over TLS; K never leaves the app); `WsClient` enables host-name checking | The phone's `ws://` is refused for anything but this same device (`RelayUrl`); the real TLS path is only exercised by CI against loopback, not against Cloudflare |
+| **Flooding the relay** | Per-room token bucket (30/s, burst 60), 66,000-byte frame cap, per-address connection limit, room-id format checked first | relay: *closes a socket that sends a frame over 66,000 bytes (1009)*, *closes a socket that floods (1008)*, *answers 429 after too many new connections from one address, before checking the key* | The real rate-limit binding across Cloudflare data centres: not testable here |
+| **Flooding the computer** (init floods, junk frames) | One admission slot for the whole relay link; a newer `init` replaces the conversation; 3 bad handshake frames silence `init` for 10 s; the existing LAN caps for everything after | Rust *the_relay_connection_counts_as_one_source...*, *three_bad_handshakes_silence_init_for_a_while*, *nothing_is_served_before_the_phone_proves_it_holds_the_key* | none |
+| **Creating many empty rooms to burn the free quota** | The access key is checked (`401`) before any room exists; fail closed without one | relay: *refuses a missing, wrong or malformed access key with 401, before any room exists*, *fails closed...*; Kotlin *aWrongAccessKeyIsRefusedByTheRealRelay* (against the Worker) | Anyone who holds the key (every paired phone) can still spend your quota. Fix: rotate the key. Accepted |
+| **Reflection** | A different key per direction **and** the direction byte in the nonce and in the AAD | Rust and Kotlin *no_key_and_nonce_pair_repeats...*, *the_sessions_themselves_reproduce_the_vector_frames_in_each_direction* (mutation: a shared key is caught) | none |
+| **Phone talks to a fake computer** | The fake has no K: its `accept` MAC fails, and the MAC covers the phone's current nonce | Kotlin *aFakeComputerWithoutTheKeyIsNeverTrusted*, *anAcceptThatAnswersAnOtherInitIsIgnored* | none |
+| **A fake phone** | Its `init` MAC fails; nothing is served before a data frame decrypts | Rust *nothing_is_served_before_the_phone_proves_it_holds_the_key* | none |
+| **Downgrade** | Not applicable: the LAN link is a separate, equally strict, pinned-TLS path; the relay adds a way in, not a weaker one | Kotlin *TransportTest*; the same `LinkClient` and the same token, fingerprint and biometric rules run on both | none |
+| **Two phones** | One phone per room (decision D4): a second one replaces the first | Kotlin *aSecondPhoneReplacesTheFirstOne* (against the Node twin) | A second phone is a second pairing, or use the LAN link |
+| **Nonce reuse** | Direction byte plus a counter that only goes up and refuses to wrap; new keys on every connection | Rust and Kotlin property tests over thousands of frames, both directions, two sessions | Random 128-bit nonces: a collision needs about 2^64 sessions |
+
+## What I found while reading the code again (and fixed)
+
+1. **The pairing link had a size limit that the relay fields could break.** The phone refused links over 1,024 characters. With
+ the four relay fields, a long relay host and a 48-character accented computer name the link can reach about 900 characters
+ once percent-encoded; with the old limit a legitimate code could have been refused as "not a Coucou link". The limit is now
+ 2,048 and a test (Rust and Kotlin) builds the longest realistic link and checks both the phone's parser and the QR encoder.
+2. **The phone's pairing confirmation did not show the relay.** The spec says it must. It now names the relay's host, so a code
+ that points somewhere you did not set up is visible before anything is stored (`RelayLinkTest.theConfirmationShows...`).
+3. **The Node twin could not start on Node 22** (a TypeScript construct that type stripping does not accept). Fixed in R4; the
+ relay's own tests still pass.
+4. **A failed write of `init` hid why the relay had closed the connection**, so "this pairing is in use" read as "network
+ dropped". Fixed in R4 (the connector reads the close frame), found by a test.
+
+## Accepted limits, said plainly
+
+- **No forward secrecy** (decision D3). If K ever leaks, traffic someone recorded earlier can be read. K lives in the OS keystore on
+ the computer and in the Keystore-encrypted blob on the phone, and "Pair again" replaces it.
+- **Metadata is visible to the relay and Cloudflare:** IP addresses, that a pairing exists (the room id is stable), when each side
+ is online, frame sizes (padded to 128 bytes) and timing.
+- **The pairing code is a secret.** It contains the end-to-end key and the relay's access key. It is shown only in the settings
+ window after you press *Show pairing code*, the copy hint says so, the phone's pairing screen is excluded from screenshots, and
+ *Pair again* invalidates it. Anyone who photographs the QR code can pair a phone until you press *Pair again*, exactly as with the
+ local-network code.
+- **The relay can be used up by whoever holds the access key** (quota only).
+- **Cloudflare's behaviour in production** (hibernation timing, idle WebSocket handling, the real rate-limit binding, the free-tier
+ numbers) is from documentation and memory. The tests run the real Worker code under `wrangler dev` (workerd) only.
+- **Not seen on a real device:** Doze and battery cost of the connection, the Settings card's appearance, Compose and lint results
+ (CI only), the pairing confirmation text on a small screen.
+
+## Rules kept
+
+Nothing published, no release, no store listing, no pull request to upstream; Louis's `relay/` is untouched; no telemetry; the
+agent is never blocked by the relay (its own task, a failure only changes a status line); no permission is approved without an
+explicit tap and the phone's screen-lock check; secrets only in the OS keystore and the Android Keystore; the Android app stays
+English only and the new computer-side strings have all nine translations.
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 00000000..b9e0bcfe
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,101 @@
+import java.util.zip.ZipFile
+
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+ id("org.jetbrains.kotlin.plugin.compose")
+}
+
+// Release signing comes from the environment or from Gradle properties (-P on the command line, or ~/.gradle/gradle.properties), never
+// from a file in this repository. Without all of them the release build is made unsigned (it cannot be installed) rather than
+// signed with a debug key.
+fun signingValue(name: String): String? = (System.getenv(name) ?: providers.gradleProperty(name).orNull)?.takeIf { it.isNotBlank() }
+val releaseKeystore = signingValue("COUCOU_KEYSTORE_FILE")
+val releaseStorePassword = signingValue("COUCOU_KEYSTORE_PASSWORD")
+val releaseKeyAlias = signingValue("COUCOU_KEY_ALIAS")
+val releaseKeyPassword = signingValue("COUCOU_KEY_PASSWORD") ?: releaseStorePassword
+
+android {
+ namespace = "com.coucou.android"
+ compileSdk = 35
+ defaultConfig {
+ applicationId = "com.coucou.android"
+ minSdk = 30
+ targetSdk = 35
+ versionCode = 1
+ versionName = "0.1.0"
+ // English only: libraries' other languages are left out of the app too.
+ resourceConfigurations += listOf("en")
+ }
+ signingConfigs {
+ val keystore = releaseKeystore
+ val storePass = releaseStorePassword
+ val alias = releaseKeyAlias
+ if (keystore != null && storePass != null && alias != null) {
+ create("release") {
+ storeFile = file(keystore)
+ storePassword = storePass
+ keyAlias = alias
+ keyPassword = releaseKeyPassword
+ }
+ }
+ }
+ buildTypes {
+ release {
+ // Shrink, obfuscate and optimise with R8; unused resources go too. The rules (and why there are so few) are in proguard-rules.pro.
+ isMinifyEnabled = true
+ isShrinkResources = true
+ isDebuggable = false
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ signingConfig = signingConfigs.findByName("release") // null: unsigned
+ }
+ }
+ buildFeatures { compose = true }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions { jvmTarget = "17" }
+ sourceSets["main"].java.srcDirs("src/main/kotlin")
+ sourceSets["test"].java.srcDirs("src/test/kotlin")
+}
+
+dependencies {
+ val composeBom = platform("androidx.compose:compose-bom:2024.10.01")
+ implementation(composeBom)
+ implementation("androidx.activity:activity-compose:1.9.3")
+ implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
+ implementation("androidx.compose.material3:material3")
+ implementation("androidx.compose.ui:ui")
+ // Scanning the pairing QR code. CameraX (androidx) shows the camera; zxing-core (Apache 2.0, pure Java) reads the
+ // code. Neither talks to any server; the reasoning is in the commit message.
+ val cameraX = "1.3.4"
+ implementation("androidx.camera:camera-core:$cameraX")
+ implementation("androidx.camera:camera-camera2:$cameraX")
+ implementation("androidx.camera:camera-lifecycle:$cameraX")
+ implementation("androidx.camera:camera-view:$cameraX")
+ implementation("com.google.zxing:core:3.5.3")
+ testImplementation("junit:junit:4.13.2")
+ testImplementation("org.json:json:20240303") // android.jar stubs org.json in JVM tests
+}
+
+// Proves the release build in CI without a workflow change: CI runs `lint`, and lint now needs a release build that R8 has processed and
+// whose code no longer carries the debug logs (the Log calls are removed by the rules, so their tags and messages must not be in the dex).
+val verifyReleaseNoLogs by tasks.registering {
+ group = "verification"
+ description = "Builds the release APK and fails if a debug log tag or message is still in it."
+ dependsOn("assembleRelease")
+ val apkDir = layout.buildDirectory.dir("outputs/apk/release")
+ doLast {
+ val apks = apkDir.get().asFile.walkTopDown().filter { it.extension == "apk" }.toList()
+ check(apks.size == 1) { "expected one release APK, found ${apks.size}" }
+ val leftovers = listOf("CoucouOverlay", "CoucouLaunch", "CoucouDiscovery", "CoucouIsland", "island failed", "cannot browse", "ignored an early tap")
+ ZipFile(apks.single()).use { zip ->
+ for (entry in zip.entries().asSequence().filter { it.name.endsWith(".dex") }) {
+ val text = String(zip.getInputStream(entry).readBytes(), Charsets.ISO_8859_1)
+ for (word in leftovers) check(!text.contains(word)) { "'$word' is still in ${entry.name}: the debug logs were not stripped" }
+ }
+ }
+ }
+}
+tasks.matching { it.name == "lint" }.configureEach { dependsOn(verifyReleaseNoLogs) }
diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro
new file mode 100644
index 00000000..82a5efc5
--- /dev/null
+++ b/android/app/proguard-rules.pro
@@ -0,0 +1,20 @@
+# R8 rules for the release build (minify and shrink are on; see app/build.gradle.kts).
+#
+# Why there are almost none: the app uses no reflection, no serialization library and no JNI. Everything the system starts (activities,
+# services, receivers, the widget and the tile) is named in AndroidManifest.xml, which the build keeps by itself; Compose, CameraX,
+# AndroidX and the Kotlin runtime bring their own consumer rules; ZXing is plain Java; the protocol is read with org.json by hand.
+# What the app reads by name (settings keys, the protocol's field names, the sound table) is a string, not a class or member name.
+
+# No debug logs in a release build. The Log calls are removed with their arguments, so the tags and messages are not in the APK
+# (verifyReleaseNoLogs in build.gradle.kts checks that on every CI run). Nothing the app logs is a secret; this is for size and quiet.
+-assumenosideeffects class android.util.Log {
+ public static int v(...);
+ public static int d(...);
+ public static int i(...);
+ public static int w(...);
+ public static int e(...);
+}
+
+# A crash trace is still readable with the mapping file (app/build/outputs/mapping/release/mapping.txt; keep it with the build you ship).
+-keepattributes SourceFile,LineNumberTable
+-renamesourcefileattribute SourceFile
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..4b4a69b1
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <!-- Only the paired computer is contacted. No ads, no analytics, no billing. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <!-- Finding the computer again after a Wi-Fi change: a multicast lock held only while browsing the local network. -->
+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.USE_BIOMETRIC" />
+ <!-- Held for at most 15 seconds, only while the periodic alarm checks that the link to the computer is alive. -->
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+ <!-- Asked only when the user taps "Scan QR code" to read the pairing code; used on that screen only. -->
+ <uses-permission android:name="android.permission.CAMERA" />
+ <!-- A phone without a camera can still pair by pasting the link. -->
+ <uses-feature android:name="android.hardware.camera" android:required="false" />
+ <!-- Optional, asked only when the user turns on the pill that drops from the top of the screen. -->
+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
+
+ <application
+ android:name=".app.CoucouApp"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:allowBackup="false"
+ android:dataExtractionRules="@xml/data_extraction_rules"
+ android:fullBackupContent="@xml/backup_rules"
+ android:theme="@style/Theme.Coucou">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTop">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ <!-- Scanning the pairing QR code with the camera app opens coucou://pair?... here. -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="coucou" android:host="pair" />
+ </intent-filter>
+ </activity>
+
+ <!-- Not exported: only our own notification actions can start it (MainActivity must not trust intents from other apps). -->
+ <activity
+ android:name=".app.LaunchActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:noHistory="true"
+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />
+
+ <receiver android:name=".app.KeepAliveReceiver" android:exported="false" />
+
+ <service
+ android:name=".app.LinkService"
+ android:exported="false"
+ android:foregroundServiceType="specialUse">
+ <property
+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
+ android:value="Keeps a private, user-initiated connection to the user's own computer so agent approval requests arrive as notifications." />
+ </service>
+
+ <receiver android:name=".app.ActionReceiver" android:exported="false" />
+
+ <!-- The home-screen widget: a short summary, updated by the app when something changes (no timer). -->
+ <receiver android:name=".app.GlanceWidget" android:exported="true" android:label="@string/app_name">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ </intent-filter>
+ <meta-data android:name="android.appwidget.provider" android:resource="@xml/coucou_widget_info" />
+ </receiver>
+
+ <!-- The quick-settings tile: on while the computer is connected; a tap opens Coucou. -->
+ <service
+ android:name=".app.GlanceTile"
+ android:exported="true"
+ android:icon="@drawable/ic_stat_mochi"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
+ <intent-filter>
+ <action android:name="android.service.quicksettings.action.QS_TILE" />
+ </intent-filter>
+ </service>
+ </application>
+</manifest>
diff --git a/android/app/src/main/assets/licenses/Apache-2.0.txt b/android/app/src/main/assets/licenses/Apache-2.0.txt
new file mode 100644
index 00000000..5955d8ea
--- /dev/null
+++ b/android/app/src/main/assets/licenses/Apache-2.0.txt
@@ -0,0 +1,205 @@
+------------------------------
+Apache License
+------------------------------
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/android/app/src/main/assets/licenses/MIT.txt b/android/app/src/main/assets/licenses/MIT.txt
new file mode 100644
index 00000000..8efefc78
--- /dev/null
+++ b/android/app/src/main/assets/licenses/MIT.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Louis Raillé
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/android/app/src/main/assets/licenses/NOTICES.txt b/android/app/src/main/assets/licenses/NOTICES.txt
new file mode 100644
index 00000000..a30e755e
--- /dev/null
+++ b/android/app/src/main/assets/licenses/NOTICES.txt
@@ -0,0 +1,25 @@
+COUCOU FOR ANDROID: LICENCES AND NOTICES
+
+Coucou for Android, by Rhytam Biswas, is part of Coucou by Louis Raillé (https://github.com/Louis-CFM/coucou). It is free, has no ads and no analytics.
+
+1. The code of Coucou
+
+The source code of Coucou is Copyright (c) 2026 Louis Raillé and is released under the MIT License. The full text is below ("MIT License").
+
+2. The name, the character, the icon and the sounds
+
+The names "Coucou" and "Mochi", the Mochi character (its design, look, expressions and animations), the app icon and the sounds are Copyright (c) 2026 Louis Raillé. All rights reserved. They are NOT covered by the MIT License (see LICENSE-ASSETS.md in https://github.com/Louis-CFM/coucou). They are used in this app with the written permission of Louis Raillé, for this Android app only, and may not be reused elsewhere without his permission.
+
+3. ZXing
+
+The pairing QR code is read with ZXing Core 3.5.3 ("Zebra Crossing", https://github.com/zxing/zxing), Copyright ZXing authors. It is licensed under the Apache License, Version 2.0, the full text of which is below ("Apache License"). The library is used unmodified; it makes no network connection.
+
+4. AndroidX, Jetpack Compose, CameraX and Kotlin
+
+The user interface, the camera preview and the language runtime come from AndroidX (Jetpack Compose, Material 3, Activity, Lifecycle, CameraX), Copyright The Android Open Source Project, and the Kotlin standard library, Copyright JetBrains s.r.o. and Kotlin Programming Language contributors. They are licensed under the Apache License, Version 2.0, the full text of which is below. They are used unmodified.
+
+No warranty: the software is provided "as is", as the licences below say.
+
+------------------------------
+MIT License
+------------------------------
diff --git a/android/app/src/main/kotlin/com/coucou/android/Attribution.kt b/android/app/src/main/kotlin/com/coucou/android/Attribution.kt
new file mode 100644
index 00000000..51b5f0d8
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/Attribution.kt
@@ -0,0 +1,7 @@
+package com.coucou.android
+
+/** Strings required by the author's permission (see android/PERMISSION.md). */
+object Attribution {
+ const val REPO_URL = "https://github.com/Louis-CFM/coucou"
+ const val APP_NAME = "Coucou for Android"
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/MainActivity.kt b/android/app/src/main/kotlin/com/coucou/android/MainActivity.kt
new file mode 100644
index 00000000..3570b032
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/MainActivity.kt
@@ -0,0 +1,456 @@
+package com.coucou.android
+
+import android.Manifest
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.provider.Settings
+import android.os.Build
+import android.os.Bundle
+import android.util.Log
+import android.view.WindowManager
+import android.os.SystemClock
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.BackHandler
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.WindowInsetsSides
+import androidx.compose.foundation.layout.only
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.ime
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.safeDrawing
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.windowInsetsPadding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items as gridItems
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.foundation.lazy.rememberLazyListState
+import kotlinx.coroutines.launch
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.runtime.SideEffect
+import androidx.core.view.WindowCompat
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.app.AppModel
+import com.coucou.android.app.BiometricGate
+import com.coucou.android.app.CoucouApp
+import com.coucou.android.app.Mode
+import com.coucou.android.app.Notifications
+import com.coucou.android.core.ApprovalSheetPlan
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.Nav
+import com.coucou.android.core.Pills
+import com.coucou.android.core.Screen
+import com.coucou.android.core.SecureScreens
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.link.QuestionRequest
+import com.coucou.android.link.LinkState
+import com.coucou.android.link.PairingPayload
+import com.coucou.android.mochi.BotEmote
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+import com.coucou.android.ui.Panel
+import com.coucou.android.ui.c
+import com.coucou.android.ui.style
+import com.coucou.android.ui.tokens
+import com.coucou.android.core.TypeScale
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.ui.semantics.Role
+import com.coucou.android.ui.CoucouTheme
+import com.coucou.android.core.HomePanel
+import com.coucou.android.link.DiscoveryState
+import com.coucou.android.ui.AddressSheet
+import com.coucou.android.ui.BatteryCard
+import com.coucou.android.ui.DiagnosticsScreen
+import com.coucou.android.ui.LicencesScreen
+import com.coucou.android.ui.LinkHealthPanel
+import com.coucou.android.ui.AgentRows
+import com.coucou.android.ui.DiscoveryHint
+import com.coucou.android.ui.ApprovalSheet
+import com.coucou.android.ui.MessagePanel
+import com.coucou.android.ui.PairingScreen
+import com.coucou.android.ui.DiffSheet
+import com.coucou.android.ui.QuestionSheet
+import com.coucou.android.ui.ServicesPanel
+import com.coucou.android.ui.UsagePanel
+import com.coucou.android.ui.WardrobeScreen
+import com.coucou.android.ui.HeroCard
+import com.coucou.android.ui.RecentPanel
+import com.coucou.android.ui.BarClearance
+import com.coucou.android.ui.BottomBar
+import com.coucou.android.ui.PairConfirm
+import com.coucou.android.ui.ScanScreen
+import com.coucou.android.ui.SessionScreen
+import com.coucou.android.ui.ChatScreen
+import com.coucou.android.ui.MochiTouch
+import com.coucou.android.ui.HistoryScreen
+import com.coucou.android.ui.SettingsScreen
+import com.coucou.android.ui.StatusColors
+import com.coucou.android.ui.Gap
+import com.coucou.android.ui.Gutter
+import com.coucou.android.ui.ScreenTitle
+import com.coucou.android.ui.SectionTitle
+import com.coucou.android.ui.linkDotColor
+import com.coucou.android.ui.linkStatusText
+
+class MainActivity : ComponentActivity() {
+ private val model get() = (application as CoucouApp).model
+ private var screen by mutableStateOf(Screen.HOME)
+ /** The session whose details are open. */
+ private var detailPill by mutableStateOf<String?>(null)
+ /** The approval the user closed without deciding (the sheet stays down for it), and the session whose question is open. */
+ private var closedApproval by mutableStateOf<String?>(null)
+ private var questionPill by mutableStateOf<String?>(null)
+ private var confirming = false
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
+ }
+ model.resume()
+ setContent {
+ CoucouTheme {
+ // The app is dark only: the status bar icons are always light.
+ SideEffect { WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars = false }
+ Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
+ Box(Modifier.fillMaxSize().windowInsetsPadding(if (screen == Screen.HOME || screen == Screen.SCAN) WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom) else WindowInsets.safeDrawing)) {
+ val tabs = Nav.tabs()
+ val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0
+ val barVisible = Nav.barVisible(screen, keyboardOpen)
+ BackHandler(enabled = Nav.back(screen) != null) { Nav.back(screen)?.let { screen = it } }
+ // Chat keeps its message box above the bar; Home and Settings scroll under it (their own bottom padding).
+ Box(Modifier.fillMaxSize().padding(bottom = if (barVisible && screen == Screen.CHAT) BarClearance else 0.dp)) {
+ when (screen) {
+ Screen.SCAN -> ScanScreen(
+ onBack = { screen = Screen.HOME },
+ // True if it was a pairing code: the camera is released and the user is asked to confirm.
+ onText = { text -> model.requestPairing(text).also { if (it) screen = Screen.HOME } },
+ )
+ Screen.CHAT -> ChatScreen(model, onHome = { screen = Screen.HOME }, onSettings = { screen = Screen.SETTINGS })
+ Screen.SESSION -> SessionScreen(model, detailPill.orEmpty(), onBack = { screen = Screen.HOME })
+ Screen.GALLERY -> Gallery(onBack = { screen = Screen.SETTINGS })
+ Screen.SETTINGS -> SettingsScreen(
+ model, onHistory = { screen = Screen.HISTORY },
+ onGallery = { screen = Screen.GALLERY }, onWardrobe = { screen = Screen.WARDROBE }, onOverlay = ::setOverlay,
+ onDiagnostics = { screen = Screen.DIAGNOSTICS }, onLicences = { screen = Screen.LICENCES },
+ )
+ Screen.LICENCES -> LicencesScreen(onBack = { screen = Screen.SETTINGS })
+ Screen.WARDROBE -> WardrobeScreen(model, onBack = { screen = Screen.SETTINGS })
+ Screen.DIAGNOSTICS -> DiagnosticsScreen(model, onBack = { screen = Screen.SETTINGS })
+ Screen.HISTORY -> HistoryScreen(model, onBack = { screen = Screen.SETTINGS })
+ Screen.HOME -> if (model.mode == Mode.NONE) PairingScreen(model, onScan = { screen = Screen.SCAN }, onAbout = { screen = Screen.SETTINGS }) else Home(
+ model, onApprove = ::approve, onOverlay = ::setOverlay,
+ onSession = { detailPill = it; screen = Screen.SESSION },
+ onScan = { screen = Screen.SCAN }, onReview = { closedApproval = null }, onQuestion = { questionPill = it },
+ onHistory = { screen = Screen.HISTORY }, onDiagnostics = { screen = Screen.DIAGNOSTICS },
+ )
+ }
+ }
+ if (barVisible) {
+ BottomBar(
+ tabs, Nav.tabOf(screen), onSelect = { screen = Nav.screenOf(it) },
+ alert = model.approvals.isNotEmpty(), modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 16.dp),
+ )
+ }
+ // A request for permission rises over whatever is on screen until it is decided or closed.
+ val pending = ApprovalSheetPlan.next(model.approvals, closedApproval)
+ if (pending != null && screen != Screen.SCAN) ApprovalSheet(model, pending, onAllow = ::approve, onDismiss = { closedApproval = pending.fingerprint })
+ questionPill?.let { QuestionSheet(model, it, onDismiss = { questionPill = null }, onSend = ::sendAnswer) }
+ DiffSheet(model)
+ // Pairing, chat, an approval and a question never show in screenshots or in the recent-apps card.
+ val secure = SecureScreens.needed(
+ screen, pairing = model.mode == Mode.NONE, approvalSheetShown = pending != null && screen != Screen.SCAN,
+ questionSheetShown = questionPill != null, pairConfirmShown = model.pairRequest != null,
+ )
+ SideEffect {
+ if (secure) window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) else window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
+ }
+ // A scanned code or a link from the camera app: the user decides before anything is paired.
+ model.pairRequest?.let { PairConfirm(model, it) }
+ }
+ }
+ }
+ }
+ handle(intent)
+ }
+
+ override fun onStart() {
+ super.onStart()
+ model.inForeground = true
+ model.refreshOverlayPermission() // maybe granted meanwhile, from this app's switch or Android's settings
+ model.refreshBattery() // the battery setting may have been changed in Android's screen
+ }
+
+ override fun onStop() {
+ model.inForeground = false
+ super.onStop()
+ }
+
+ /**
+ * The pill over other apps needs a one-time system permission. The choice is saved first: even if
+ * Android recreates the app while the user is in Settings, it is remembered, and the pill works as
+ * soon as the permission is there.
+ */
+ private fun setOverlay(on: Boolean) {
+ model.useOverlay(on)
+ if (on && !model.overlayPermitted()) {
+ model.message = getString(R.string.msg_overlay_permission)
+ startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName")))
+ }
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ handle(intent)
+ }
+
+ /** A coucou://pair link (from the camera app or a browser) or a tap on an approval notification. */
+ private fun handle(i: Intent?) {
+ i ?: return
+ Log.d("CoucouLaunch", "MainActivity intent: action=${i.action} data=${i.data != null}")
+ i.data?.let { uri ->
+ if (uri.scheme == "coucou") {
+ // Opened from the camera app or a browser: never paired without the user's OK.
+ if (!model.requestPairing(uri.toString())) model.message = getString(R.string.msg_bad_link)
+ i.data = null // handled once: a rotation must not ask again
+ }
+ }
+ // Never read from the intent: this activity is exported, any app could send these extras. The request comes
+ // from LaunchActivity (ours, not exported) through the model, once.
+ val launch = model.launch.take() ?: return
+ val fp = launch.fingerprint
+ if (launch.allow) {
+ val request = model.approvals.firstOrNull { it.fingerprint == fp }
+ when {
+ request != null -> approve(request)
+ // The app was closed: the desktop offers the request again once the link is back.
+ model.linkState != LinkState.CONNECTED -> model.wantAllow = fp
+ else -> model.message = getString(R.string.msg_not_pending)
+ }
+ }
+ }
+
+ /**
+ * An answer to a question: only after the same screen-lock check as Allow. The lock prompt shows what is about to be
+ * sent (the labels picked); nothing about it is logged or stored.
+ */
+ private fun sendAnswer(request: QuestionRequest, picks: List<List<String>>) {
+ if (confirming) return
+ confirming = true
+ BiometricGate.confirm(
+ this, getString(R.string.question_confirm_title), picks.joinToString("; ") { it.joinToString(", ") }, getString(R.string.msg_need_lock),
+ onSuccess = {
+ confirming = false
+ questionPill = null
+ model.message = getString(if (model.answerQuestion(request.fingerprint, picks)) R.string.question_sent else R.string.question_not_sent)
+ },
+ onFail = { confirming = false; if (it.isNotBlank()) model.message = it },
+ )
+ }
+
+ /** Allow: only after the biometric / screen-lock check. */
+ private fun approve(r: ApprovalRequest) {
+ if (confirming) return // a second tap must not open a second prompt
+ if (!ApprovalSheetPlan.canAllowHere(r)) { model.message = getString(R.string.approval_on_computer); return }
+ confirming = true
+ BiometricGate.confirm(
+ this, getString(R.string.action_allow), "${r.tool}: ${r.command}", getString(R.string.msg_need_lock),
+ onSuccess = { confirming = false; model.decide(r.fingerprint, allow = true) },
+ onFail = { confirming = false; if (it.isNotBlank()) model.message = it },
+ )
+ }
+}
+
+@Composable
+private fun Home(
+ model: AppModel, onApprove: (ApprovalRequest) -> Unit, onOverlay: (Boolean) -> Unit, onSession: (String) -> Unit,
+ onScan: () -> Unit, onHistory: () -> Unit, onReview: () -> Unit, onQuestion: (String) -> Unit, onDiagnostics: () -> Unit,
+) {
+ val engines = remember { HashMap<String, MochiEngine>() }
+ val miniEngines = remember { HashMap<String, MochiEngine>() }
+ val touches = remember { HashMap<String, MochiTouch>() }
+ val clock = remember { { SystemClock.elapsedRealtimeNanos() / 1e6 } }
+ var selected by rememberSaveable { mutableStateOf<String?>(null) }
+ val listState = rememberLazyListState()
+ var addressOpen by rememberSaveable { mutableStateOf(false) }
+
+ // Allow tapped on a notification before the link was back: open the prompt once the request is here.
+ LaunchedEffect(model.approvals, model.wantAllow) {
+ val fp = model.wantAllow ?: return@LaunchedEffect
+ model.approvals.firstOrNull { it.fingerprint == fp }?.let {
+ model.wantAllow = null
+ onApprove(it)
+ }
+ }
+
+ // The PC's Home panel: the agent that matters in a big card, the others as pills.
+ val focus = HomePanel.focus(model.sessions, selected)
+ val key = focus?.pillId ?: HOME_KEY
+ val engine = engines.getOrPut(key) { MochiEngine(clock, sound = model.sounds) }
+ val touch = touches.getOrPut(key) { MochiTouch(engine, model.sounds) { model.sessions.firstOrNull { it.pillId == key }?.state ?: BotState.IDLE } }
+ val state = focus?.state ?: BotState.SLEEPING // no agent: a sleeping Mochi
+ if (engine.state != state && !touch.dizzy) engine.setState(state)
+
+ // The hero wears what the computer says, or what the user picked here (a new engine starts dressed, a change animates).
+ val dressed = remember { HashSet<MochiEngine>() }
+ model.dress().let { outfit -> if (dressed.add(engine)) engine.setOutfit(outfit, animated = false) else engine.setOutfit(outfit) }
+
+ // The hero's Mochi wears its agent's colour, like the small ones (never white by default).
+ engine.bodyColor = focus?.let { HomePanel.colorHex(it) }?.let { HomePanel.rgb(it) }
+
+ val pair = HomePanel.link(model.isPaired, model.mode == Mode.DEMO, hasApproval = model.approvals.isNotEmpty())
+ // Items, in order: the hero, [message], then the other agents, ask, recent.
+ val others = HomePanel.others(model.sessions, focus)
+ LazyColumn(
+ state = listState,
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = PaddingValues(bottom = BarClearance),
+ verticalArrangement = Arrangement.spacedBy(Gap),
+ ) {
+ item {
+ HeroCard(
+ focus, engine, touch.modifier, pair, HomeText.running(model.sessions),
+ linkDot = linkDotColor(model), linkText = linkStatusText(model),
+ onDetails = if (focus != null && HomePanel.hasDetails(focus)) ({ onSession(focus.pillId) }) else null,
+ onQuestion = if (focus != null && focus.state == BotState.QUESTION) ({ onQuestion(focus.pillId) }) else null,
+ canAnswer = focus != null && model.questionFor(focus.pillId) != null,
+ onLink = {
+ when (pair) {
+ HomePanel.Link.PAIR -> onScan() // not reachable on Home (no computer shows the pairing screen), harmless
+ HomePanel.Link.APPROVAL -> onReview()
+ HomePanel.Link.NONE -> {}
+ }
+ },
+ )
+ }
+ // The link had worked and ended: what happened and how long ago, instead of a silent state. And, only if it would help, the battery setting.
+ if (model.mode == Mode.PAIRED && model.linkState != LinkState.CONNECTED) {
+ item { Box(Modifier.padding(horizontal = Gutter)) { LinkHealthPanel(model, onDiagnostics) } }
+ }
+ if (model.batteryHintVisible) item { Box(Modifier.padding(horizontal = Gutter)) { BatteryCard(model) } }
+ // The saved address failed and a search found nothing: a calm hint with two ways out.
+ if (model.mode == Mode.PAIRED && model.linkState != LinkState.CONNECTED && model.discovery == DiscoveryState.NOT_FOUND) {
+ item { Box(Modifier.padding(horizontal = Gutter)) { DiscoveryHint(onPairAgain = onScan, onEnterAddress = { addressOpen = true }) } }
+ }
+ model.message?.let { msg ->
+ item { Box(Modifier.padding(horizontal = Gutter)) { MessagePanel(msg) { model.message = null } } }
+ }
+
+
+ if (others.isNotEmpty()) {
+ item {
+ Box(Modifier.padding(horizontal = Gutter)) {
+ AgentRows(
+ others,
+ engineFor = { s ->
+ miniEngines.getOrPut(s.pillId) {
+ MochiEngine(clock).apply {
+ isMini = true
+ bodyColor = HomePanel.colorHex(s)?.let { HomePanel.rgb(it) }
+ }
+ }.also {
+ it.bodyColor = HomePanel.colorHex(s)?.let { hex -> HomePanel.rgb(hex) }
+ if (it.state != s.state) it.setState(s.state)
+ }
+ },
+ onPick = { selected = it.pillId },
+ )
+ }
+ }
+ }
+
+ if (model.usage != null) item { Box(Modifier.padding(horizontal = Gutter)) { UsagePanel(model.usage) } }
+ if (model.services.isNotEmpty()) item { Box(Modifier.padding(horizontal = Gutter)) { ServicesPanel(model.services) } }
+ item { Box(Modifier.padding(horizontal = Gutter)) { RecentPanel(model.decisions, onHistory) } }
+
+ // Only when the switch is on but Android still refuses: the one thing Home must say about it.
+ if (model.overlayWished && !model.overlayPermission) item { Box(Modifier.padding(horizontal = Gutter)) { OverlayHint(onOverlay) } }
+ item { Spacer(Modifier.height(Gutter)) }
+ }
+ // After the list, so it draws over it.
+ if (addressOpen) AddressSheet(model) { addressOpen = false }
+}
+
+private const val HOME_KEY = "home"
+
+@Composable
+private fun OverlayHint(onOverlay: (Boolean) -> Unit) {
+ Panel {
+ Row(Modifier.padding(start = Gutter), verticalAlignment = Alignment.CenterVertically) {
+ Text(stringResource(R.string.overlay_missing), Modifier.weight(1f).padding(vertical = 12.dp), style = TypeScale.SECONDARY.style(tokens().textDim.c()))
+ Text(
+ stringResource(R.string.overlay_allow),
+ Modifier.heightIn(min = 48.dp).clickable(role = Role.Button) { onOverlay(true) }.padding(horizontal = 16.dp, vertical = 14.dp),
+ style = TypeScale.LABEL.style(tokens().text.c()), maxLines = 1,
+ )
+ }
+ }
+}
+
+/** Every state and emote, drawn live. Handy to check the port by eye. */
+@Composable
+private fun Gallery(onBack: () -> Unit) {
+ val clock = remember { { SystemClock.elapsedRealtimeNanos() / 1e6 } }
+ val states = remember { BotState.entries.map { s -> s to MochiEngine(clock).apply { setState(s, force = true) } } }
+ val emotes = remember { BotEmote.entries.map { e -> e to MochiEngine(clock).apply { setPermanentEmote(e) } } }
+ Column(Modifier.padding(horizontal = Gutter)) {
+ ScreenTitle(stringResource(R.string.gallery), onBack)
+ Spacer(Modifier.height(Gap))
+ LazyVerticalGrid(GridCells.Fixed(3), horizontalArrangement = Arrangement.spacedBy(Gap), verticalArrangement = Arrangement.spacedBy(Gap)) {
+ gridItems(states) { (s, e) -> GalleryCell(s.key, e) }
+ gridItems(emotes) { (m, e) -> GalleryCell(m.key, e) }
+ }
+ }
+}
+
+@Composable
+private fun GalleryCell(label: String, engine: MochiEngine) {
+ Box(Modifier.fillMaxWidth()) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ MochiView(engine, Modifier.fillMaxWidth().aspectRatio(1f))
+ Text(label, style = MaterialTheme.typography.labelSmall)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/AppModel.kt b/android/app/src/main/kotlin/com/coucou/android/app/AppModel.kt
new file mode 100644
index 00000000..f0529542
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/AppModel.kt
@@ -0,0 +1,853 @@
+package com.coucou.android.app
+
+import android.content.Context
+import android.os.Build
+import android.os.Handler
+import android.os.PowerManager
+import android.os.Looper
+import android.util.Log
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import com.coucou.android.R
+import com.coucou.android.core.ChatTab
+import com.coucou.android.core.ChatTabState
+import com.coucou.android.core.Decision
+import com.coucou.android.core.DecisionLog
+import com.coucou.android.core.KeyValueStore
+import com.coucou.android.core.IslandPlan
+import com.coucou.android.core.OverlayChoice
+import com.coucou.android.core.StatusPolicy
+import com.coucou.android.core.UserSettings
+import com.coucou.android.core.OverlayPolicy
+import com.coucou.android.core.WishStore
+import com.coucou.android.core.Pills
+import com.coucou.android.ui.IslandOverlay
+import com.coucou.android.link.Protocol
+import com.coucou.android.link.ChatModel
+import com.coucou.android.core.PairingScan
+import com.coucou.android.core.ScanDecision
+import com.coucou.android.core.ChatHistory
+import com.coucou.android.core.ChatModels
+import com.coucou.android.core.ChatSession
+import com.coucou.android.link.AddressFinder
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.link.QuestionRequest
+import com.coucou.android.link.Cancelable
+import com.coucou.android.link.Discovery
+import com.coucou.android.link.DiscoveryPolicy
+import com.coucou.android.link.DiscoveryState
+import com.coucou.android.link.PinnedProbe
+import com.coucou.android.link.DemoLink
+import com.coucou.android.link.Connector
+import com.coucou.android.link.DesktopLink
+import com.coucou.android.link.PinnedTls
+import com.coucou.android.link.LinkClient
+import com.coucou.android.link.LinkListener
+import com.coucou.android.link.LinkState
+import com.coucou.android.link.BatteryHint
+import com.coucou.android.link.DiagResult
+import com.coucou.android.link.DiagStep
+import com.coucou.android.link.Diagnostics
+import com.coucou.android.link.Found
+import com.coucou.android.link.LanDiagnostics
+import com.coucou.android.link.LinkHealth
+import com.coucou.android.link.LostReason
+import com.coucou.android.link.PairingPayload
+import com.coucou.android.link.ReconnectPolicy
+import com.coucou.android.link.Wake
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.sound.SoundPlayer
+import com.coucou.android.mochi.BotState
+
+enum class Mode { NONE, DEMO, PAIRED }
+
+/** The one place the UI, the service and the notification actions share. Created by [CoucouApp]. */
+class AppModel(private val context: Context) : LinkListener {
+ private val main = Handler(Looper.getMainLooper())
+ private val store = SecureStore(context)
+ val sounds = SoundPlayer(context)
+ val notifier = Notifications(context)
+
+ /** Set only by LaunchActivity (not exported), read by MainActivity: see [com.coucou.android.core.PendingLaunch]. */
+ val launch = com.coucou.android.core.PendingLaunch()
+
+ var mode by mutableStateOf(Mode.NONE); private set
+ var linkState by mutableStateOf(LinkState.DISCONNECTED); private set
+ var desktopName by mutableStateOf<String?>(null); private set
+ var sessions by mutableStateOf<List<SessionInfo>>(emptyList()); private set
+ var approvals by mutableStateOf<List<ApprovalRequest>>(emptyList()); private set
+ /** Questions Claude Code asks that this phone may answer (only with the `answers` capability); kept in memory, never written. */
+ var questions by mutableStateOf<List<QuestionRequest>>(emptyList()); private set
+ var message by mutableStateOf<String?>(null)
+
+ // ── Finding the computer again when its address changed (docs/ANDROID_LINK.md, "Finding the computer") ──
+ /** What the search for the computer is doing, for the status line and the hint. */
+ var discovery by mutableStateOf(DiscoveryState.IDLE); private set
+ /** The pairing the running link uses (with the address in force); the token stays in memory only as long as the link does. */
+ @Volatile private var currentPairing: PairingPayload? = null
+ private val probeExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "coucou-probe").apply { isDaemon = true } }
+ /** Which way the link reaches the computer now (null until connected), and why the relay failed, if it did. */
+ var route by mutableStateOf<com.coucou.android.link.Route?>(null); private set
+ var relayIssue by mutableStateOf(com.coucou.android.link.RelayIssue.NONE); private set
+ private val transport = com.coucou.android.link.TransportPolicy({ currentPairing?.relay != null && settings.useRelay })
+ @Volatile private var fallback: com.coucou.android.link.FallbackConnector? = null
+ @Volatile private var relayConnector: com.coucou.android.link.RelayConnector? = null
+
+ /** Whether the pairing in force includes a relay (shown in Settings > Away from home Wi-Fi). */
+ val hasRelay: Boolean get() = currentPairing?.relay != null
+ val relayHost: String? get() = currentPairing?.relay?.relayUrl()?.host
+
+ private val netWatch = NetworkWatch(context, { up -> main.post { onNetworkChanged(up) } }, { main.post { onWake(Wake.NEW_NETWORK) } })
+ private val finder = AddressFinder(
+ source = NsdDiscovery(context), probe = PinnedProbe,
+ pairing = { currentPairing }, allowed = { mayDiscover() },
+ onAddress = { host, port -> main.post { onAddressFound(host, port) } },
+ onState = { st -> main.post { discovery = st } },
+ scheduler = { delay, task -> val r = Runnable { task() }; main.postDelayed(r, delay); Cancelable { main.removeCallbacks(r) } },
+ runner = { task -> probeExecutor.execute { task() } },
+ )
+
+ private fun mayDiscover() = DiscoveryPolicy.mayDiscover(
+ paired = currentPairing != null, demo = mode == Mode.DEMO, wifiUp = netWatch.wifiUp, linkConnected = linkState == LinkState.CONNECTED,
+ )
+
+ private val prefs = context.getSharedPreferences("coucou_ui", Context.MODE_PRIVATE)
+ private val kv = object : KeyValueStore {
+ override fun getBoolean(key: String, default: Boolean) = prefs.getBoolean(key, default)
+ override fun getInt(key: String, default: Int) = prefs.getInt(key, default)
+ override fun getFloat(key: String, default: Float) = prefs.getFloat(key, default)
+ override fun getString(key: String, default: String) = prefs.getString(key, default) ?: default
+ override fun put(key: String, value: Any) {
+ prefs.edit().apply {
+ when (value) {
+ is Boolean -> putBoolean(key, value)
+ is Int -> putInt(key, value)
+ is Float -> putFloat(key, value)
+ is String -> putString(key, value)
+ }
+ }.apply()
+ }
+ }
+
+ /** What the user chose in Settings (sound, notices, quiet hours). */
+ var settings by mutableStateOf(UserSettings.load(kv)); private set
+
+ fun updateSettings(next: UserSettings) {
+ val relayChanged = next.useRelay != settings.useRelay
+ settings = next
+ UserSettings.save(kv, next)
+ applySound()
+ // Switching the relay on or off rebuilds the connection with the right routes.
+ if (relayChanged) currentPairing?.let { restartLink(it) }
+ }
+
+ private fun applySound() {
+ sounds.enabled = settings.soundOn
+ sounds.volume = settings.volume
+ }
+
+ init { applySound() }
+
+ /** What the computer says Mochi wears ("auto" or an outfit); the last one it told, kept for when it is away. */
+ var computerOutfit by mutableStateOf(com.coucou.android.mochi.outfit.Wardrobe.parse(kv.getString("computer_outfit", "")))
+ private set
+
+ /** The selection in force: the phone's own choice, or the computer's when the phone follows it. */
+ val outfitSelection: String
+ get() = com.coucou.android.mochi.outfit.Wardrobe.choose(settings.outfit, computerOutfit)
+
+ /** What Mochi wears today ("auto" resolved with the phone's calendar). */
+ fun dress(today: java.time.LocalDate = java.time.LocalDate.now()): com.coucou.android.mochi.outfit.Outfit =
+ com.coucou.android.mochi.outfit.Wardrobe.resolve(outfitSelection, today)
+
+ /** The phone's own list of decisions. Never sent anywhere. */
+ private val decisionLog = DecisionLog(kv)
+ var decisions by mutableStateOf(decisionLog.all()); private set
+
+ fun clearDecisions() {
+ decisionLog.clear()
+ decisions = emptyList()
+ }
+
+ fun recordDecision(d: Decision) {
+ decisionLog.add(d)
+ decisions = decisionLog.all()
+ }
+
+ // ── Chat through the computer (docs/ANDROID_LINK.md). The UI comes in the next step. ──────────
+
+ private val chatHistory = ChatHistory(ChatFile(java.io.File(context.filesDir, "chat-history.json")))
+ private val chatSession = ChatSession(chatHistory.load())
+
+ /** What the user reads: this phone's own copy, kept in a private file. */
+ var chatMessages by mutableStateOf(chatSession.messages); private set
+
+ /** An answer is being waited for. */
+ var chatBusy by mutableStateOf(false); private set
+
+ /** The computer offers chat to this phone right now (its switch is on and we are connected). */
+ var chatOffered by mutableStateOf(false); private set
+
+ /** The models the user allowed on the computer; the keys never leave it. */
+ var chatModels by mutableStateOf<List<ChatModel>>(emptyList()); private set
+
+ var chatModel by mutableStateOf<String?>(prefs.getString("chat_model", null)); private set
+
+ /** The computer offers session details (steps, last message, project folder, colour) to this phone. */
+ var detailsOffered by mutableStateOf(false); private set
+ /** The computer lists the files an agent changed and can send their lines (its switch is on). */
+ var diffsOffered by mutableStateOf(false); private set
+ /** The Claude and Codex plan usage the computer sent (its switch is on); null: nothing to show. */
+ var usage by mutableStateOf<com.coucou.android.link.UsageSnapshot?>(null); private set
+ /** The read-only service cards the user allowed on the computer; empty: none. */
+ var services by mutableStateOf<List<com.coucou.android.link.ServiceCard>>(emptyList()); private set
+
+ /** What the Chat tab shows: not paired, not reachable, chat off on the computer, no model allowed, or ready. */
+ val chatTabState: ChatTabState get() = ChatTab.state(
+ paired = mode == Mode.PAIRED, connected = linkState == LinkState.CONNECTED, offered = chatOffered, modelCount = chatModels.size,
+ )
+
+ /** Chat is usable: offered, at least one model allowed, connected. */
+ val chatAvailable: Boolean get() = chatOffered && chatModels.isNotEmpty() && linkState == LinkState.CONNECTED
+
+ private fun chatChanged(save: Boolean) {
+ chatMessages = chatSession.messages
+ chatBusy = chatSession.running != null
+ if (save) chatHistory.save(chatSession.messages)
+ }
+
+ fun chatSelect(id: String) {
+ if (chatModels.any { it.id == id }) {
+ chatModel = id
+ prefs.edit().putString("chat_model", id).apply()
+ }
+ }
+
+ /** Asks the computer again which models are allowed (when the Chat screen opens). */
+ fun chatRefreshModels() { link?.chatModels() }
+
+ /** Null when sent, else why not (for a message under the box). */
+ fun chatSend(text: String): ChatSession.Refusal? {
+ val sent = chatSession.send(text, chatModel, connected = chatAvailable)
+ return when (sent) {
+ is ChatSession.Sent.No -> sent.why
+ is ChatSession.Sent.Ok -> {
+ chatChanged(save = true)
+ if (link?.chatSend(sent.msg.id, sent.msg.model, sent.msg.text) != true) {
+ chatSession.onDisconnected()
+ chatChanged(save = true)
+ }
+ null
+ }
+ }
+ }
+
+ fun chatCancel() {
+ chatSession.cancel()?.let { link?.chatCancel(it) }
+ chatChanged(save = true)
+ }
+
+ /** Clear: forgets the history here and on the computer. */
+ fun chatClear() {
+ chatSession.cancel()?.let { link?.chatCancel(it) }
+ chatSession.clear()
+ chatHistory.clear()
+ link?.chatReset()
+ chatChanged(save = false)
+ }
+
+ private fun chatLinkLost() {
+ detailsOffered = false
+ chatOffered = false
+ chatModels = emptyList()
+ if (chatSession.running != null) {
+ chatSession.onDisconnected()
+ chatChanged(save = true)
+ }
+ }
+
+ private val choice = OverlayChoice(object : WishStore {
+ override fun read() = prefs.getBoolean("overlay", false)
+ // commit(): a tiny file, and it must survive the process being killed while the user is in Settings.
+ override fun write(on: Boolean) { prefs.edit().putBoolean("overlay", on).commit() }
+ })
+
+ /** The user's wish for the pill over other apps (off until they turn it on). Saved when they tap. */
+ var overlayWished by mutableStateOf(choice.wished); private set
+
+ /** The system permission "display over other apps", re-read when the app comes to the front. */
+ var overlayPermission by mutableStateOf(false); private set
+
+ /** The app is on screen: it shows everything itself, so the pill stays away. */
+ var inForeground = false
+ set(value) {
+ field = value
+ if (value) {
+ overlay.hide()
+ notifier.cancelAllStatus()
+ } else {
+ refreshIsland() // the user left the app: an agent at work shows on the island at once
+ }
+ }
+
+ private val overlay = IslandOverlay(
+ context, { android.os.SystemClock.elapsedRealtimeNanos() / 1e6 },
+ onAllow = { notifier.openAllow(it) },
+ onDeny = { decide(it, allow = false) },
+ onOpen = { notifier.openApp() },
+ )
+
+ fun overlayPermitted() = overlay.permitted()
+
+ /** What the switch shows: wished and allowed by the system. */
+ val overlayOn: Boolean get() = overlayWished && overlayPermission
+
+ fun refreshOverlayPermission() { overlayPermission = overlay.permitted() }
+
+ /** The user tapped the switch: remember the choice right now (see [OverlayChoice]). */
+ fun useOverlay(on: Boolean) {
+ choice.choose(on)
+ overlayWished = on
+ refreshOverlayPermission()
+ refreshIsland()
+ }
+
+ private fun islandAllowed(): Boolean {
+ val connected = mode != Mode.PAIRED || linkState == LinkState.CONNECTED
+ val why = OverlayPolicy.blocker(choice.wished, overlay.permitted(), inForeground)
+ ?: if (!connected) "not connected to a computer" else null
+ if (why != null) Log.d("CoucouOverlay", "no island: $why")
+ return why == null
+ }
+
+ /**
+ * What the island shows right now (an agent at work, a question, a request), from the current
+ * sessions and requests. When it may not show at all it is removed completely.
+ */
+ /** What the notification, the widget and the tile say right now. */
+ fun glance(): com.coucou.android.core.Glance = com.coucou.android.core.GlanceBuilder.build(
+ mode != Mode.NONE || isPaired, linkState, desktopName, sessions, approvals.size, this::agentName,
+ )
+
+ /** The small surfaces follow every change of sessions, requests and link; none of them runs a timer. */
+ private fun pushGlance() {
+ val g = glance()
+ notifier.updateOngoing(this, g)
+ GlanceWidget.update(context, g)
+ GlanceTile.requestUpdate(context)
+ }
+
+ private fun refreshIsland() {
+ pushGlance()
+ if (!islandAllowed()) {
+ overlay.hide()
+ return
+ }
+ overlay.setActive(IslandPlan.active(sessions, approvals, allowed = true, this::agentName))
+ }
+
+ /**
+ * Allow was tapped on a notification before the link was back (the app had been closed): the
+ * desktop offers the request again as soon as it reconnects, and the biometric prompt opens then.
+ */
+ var wantAllow by mutableStateOf<String?>(null)
+
+ private val expiry = HashMap<String, Runnable>()
+ private var link: DesktopLink? = null
+ private val lastState = HashMap<String, BotState>()
+
+ /** The name the user knows the agent by: the session's own name, else the pill catalog. */
+ fun agentName(pillId: String): String =
+ sessions.firstOrNull { it.pillId == pillId }?.agent?.takeIf { it.isNotBlank() } ?: Pills.byId(pillId)?.name ?: "An agent"
+
+ val isPaired get() = store.loadPairing() != null
+
+ /** Called at launch and by the service: reconnects to the stored desktop, if any. */
+ fun resume() {
+ if (mode == Mode.DEMO || link != null) return
+ val p = store.loadPairing() ?: return
+ connect(p)
+ }
+
+ /**
+ * A pairing link waiting for the user's OK: read from the QR code, or opened from the camera app. Held in
+ * memory only while the question is on screen; it is never logged and goes nowhere but into [pair].
+ */
+ var pairRequest by mutableStateOf<String?>(null); private set
+
+ /** True if [text] is a Coucou pairing link (the user is now asked to confirm); false for any other text. */
+ fun requestPairing(text: String?): Boolean {
+ val d = PairingScan.decide(text)
+ if (d !is ScanDecision.Pairing) return false
+ pairRequest = d.link
+ return true
+ }
+
+ fun confirmPairing() {
+ val link = pairRequest ?: return
+ pairRequest = null
+ pair(link)
+ }
+
+ fun cancelPairing() { pairRequest = null }
+
+ fun pair(text: String): Boolean {
+ val p = PairingPayload.parse(text)
+ if (p == null) { message = context.getString(R.string.msg_bad_link); return false }
+ stopLink()
+ store.savePairing(p)
+ connect(p)
+ return true
+ }
+
+ private fun connect(p: PairingPayload) {
+ mode = Mode.PAIRED
+ desktopName = p.desktopName.ifBlank { p.host }
+ currentPairing = p
+ link = newLink(p).also { it.start() }
+ netWatch.start()
+ screenWatch.start()
+ KeepAliveAlarm.arm(context)
+ LinkService.start(context)
+ }
+
+ /** The saved address is replaced; the token and the pinned certificate are the same. The link restarts at once. */
+ private fun useAddress(host: String, port: Int) {
+ val p = currentPairing ?: return
+ val q = Discovery.withAddress(p, host, port)
+ store.savePairing(q)
+ currentPairing = q
+ restartLink(q)
+ }
+
+ /** A link for this pairing: the direct connection, and the relay behind it when the pairing has one and the user allows it. */
+ private fun newLink(p: PairingPayload): LinkClient {
+ val lan = PinnedTls.connector(p)
+ val relay = p.relay
+ fallback?.stop()
+ val connector: Connector = if (relay != null && settings.useRelay) {
+ val rc = com.coucou.android.link.RelayConnector(relay)
+ relayConnector = rc
+ com.coucou.android.link.FallbackConnector(lan, rc, transport, onRoute = { r -> main.post { route = r } }).also { fallback = it }
+ } else {
+ relayConnector = null
+ fallback = null
+ route = null
+ lan
+ }
+ return LinkClient(p, Build.MODEL ?: "Android", this, connector = connector)
+ }
+
+ private fun restartLink(p: PairingPayload) {
+ link?.stop()
+ link = newLink(p).also { it.start() }
+ }
+
+ /** A computer matching the paired fingerprint answered with the pinned certificate (checked by a bare TLS handshake). */
+ private fun onAddressFound(host: String, port: Int) {
+ if (mode != Mode.PAIRED || currentPairing == null) return
+ Log.d("CoucouDiscovery", "address updated")
+ useAddress(host, port)
+ }
+
+ // ── Keeping the link alive while the phone sleeps (docs/ANDROID_LINK.md, "Keeping the link alive") ──
+
+ /** What happened to the link: when it was lost and why, and how often the screen had been off when it was. */
+ var health by mutableStateOf(LinkHealth(dropsWhileScreenOff = kv.getInt("link_drops_off", 0))); private set
+ /** The screen was off at some point since the link last came up. */
+ @Volatile private var screenWasOff = false
+ private val power = context.getSystemService(PowerManager::class.java)
+ private val screenWatch = ScreenWatch(context) { on -> main.post { if (on) onWake(Wake.SCREEN_ON) else screenWasOff = true } }
+ private var batteryTick by mutableStateOf(0)
+ var batterySnoozedAt by mutableStateOf(kv.getString("battery_snoozed_at", "").toLongOrNull()); private set
+
+ /** The screen turned on, a network appeared, or the alarm fired: look at the link now (rules in [ReconnectPolicy]). */
+ private fun onWake(event: Wake) {
+ val relay = currentPairing?.relay != null && settings.useRelay
+ when (ReconnectPolicy.decide(event, mode == Mode.PAIRED, linkState == LinkState.CONNECTED, netWatch.wifiUp, relay)) {
+ ReconnectPolicy.Action.RETRY_NOW -> link?.retryNow()
+ ReconnectPolicy.Action.CHECK_NOW -> link?.checkNow()
+ ReconnectPolicy.Action.NONE -> {}
+ }
+ }
+
+ /** The periodic alarm. If Android had stopped the app, this is also what brings the link back (the pairing is stored). */
+ fun keepAliveTick() {
+ if (mode == Mode.NONE) resume()
+ if (mode != Mode.PAIRED) return
+ onWake(Wake.ALARM)
+ KeepAliveAlarm.arm(context)
+ }
+
+ /** Suggest the battery setting only when the link ended on its own after the screen had been off and the app is still restricted. */
+ val batteryHintVisible: Boolean get() {
+ batteryTick // read so a change of the setting redraws Home
+ return BatteryHint.shouldShow(mode == Mode.PAIRED, health, power?.isIgnoringBatteryOptimizations(context.packageName) == true, batterySnoozedAt, System.currentTimeMillis())
+ }
+ val batterySteps: List<String> get() = BatteryHint.steps(BatteryHint.isSamsung(Build.MANUFACTURER))
+ /** The user may have changed the setting in Android's screen: look again when the app comes back. */
+ fun refreshBattery() { batteryTick++ }
+ fun snoozeBatteryHint() {
+ val now = System.currentTimeMillis()
+ kv.put("battery_snoozed_at", now.toString())
+ batterySnoozedAt = now
+ }
+
+ // ── "Can't connect?" ──
+ var diagResults by mutableStateOf<List<Pair<DiagStep, DiagResult>>>(emptyList()); private set
+ var diagRunning by mutableStateOf(false); private set
+
+ fun runDiagnostics() {
+ val p = currentPairing ?: return
+ if (diagRunning) return
+ diagRunning = true
+ diagResults = emptyList()
+ probeExecutor.execute {
+ val env = LanDiagnostics(
+ p, wifiUp = { netWatch.isWifiUp() }, onCellular = { netWatch.isCellular() }, discover = { browse(4_000) },
+ relayCheck = p.relay?.let { r -> { LanDiagnostics.relayReachable(r) } },
+ )
+ Diagnostics.run(env) { step, result -> main.post { diagResults = diagResults + (step to result) } }
+ main.post { diagRunning = false }
+ }
+ }
+
+ /** Listens for the computer's announcement for [ms] on a separate browser, so the link's own search is not disturbed. */
+ private fun browse(ms: Long): List<Found> {
+ val seen = java.util.concurrent.CopyOnWriteArrayList<Found>()
+ val source = NsdDiscovery(context)
+ source.start { seen.add(it) }
+ try { Thread.sleep(ms) } finally { source.stop() }
+ return seen.toList()
+ }
+
+ /** The text the user can copy: the checks and what they found, with no code, fingerprint, name or full address. */
+ fun diagnosticsReport(): String {
+ val p = currentPairing
+ val version = runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() ?: "?"
+ val via = when {
+ linkState != LinkState.CONNECTED -> "not connected"
+ route == com.coucou.android.link.Route.RELAY -> "the relay"
+ else -> "the direct link"
+ }
+ return Diagnostics.report(version, Build.VERSION.RELEASE, "${Build.MANUFACTURER} ${Build.MODEL}", diagResults, p?.let { Diagnostics.maskHost(it.host) } ?: "none", via)
+ }
+
+ private fun onNetworkChanged(wifiUp: Boolean) {
+ if (mode != Mode.PAIRED) return
+ if (!wifiUp) { finder.stop(); return } // no Wi-Fi: nothing to scan
+ fallback?.networkChanged() // on the relay: is the computer on this network? Then move back to the direct link
+ link?.retryNow() // do not wait out the backoff on a new network
+ if (mayDiscover()) finder.networkChanged()
+ }
+
+ /**
+ * "Enter address manually": a host or host:port typed by the user. The pairing, the token and the pinned
+ * certificate are unchanged, so a wrong or hostile address still cannot get past the certificate check.
+ */
+ fun setAddress(text: String): Boolean {
+ val (host, port) = Discovery.parseAddress(text) ?: return false
+ if (currentPairing == null) return false
+ useAddress(host, port)
+ return true
+ }
+
+ fun startDemo() {
+ stopLink()
+ mode = Mode.DEMO
+ link = DemoLink(this).also { it.start() }
+ }
+
+ /** Forgets the desktop: closes the link and deletes the stored secret. */
+ fun unpair() {
+ stopLink()
+ store.clearPairing()
+ LinkService.stop(context)
+ }
+
+ fun stopDemo() = stopLink()
+
+ private fun stopLink() {
+ closeDiff()
+ usage = null
+ services = emptyList()
+ fallback?.stop()
+ fallback = null
+ relayConnector = null
+ route = null
+ relayIssue = com.coucou.android.link.RelayIssue.NONE
+ finder.stop()
+ netWatch.stop()
+ screenWatch.stop()
+ KeepAliveAlarm.cancel(context)
+ health = health.recovered()
+ currentPairing = null
+ link?.stop()
+ link = null
+ mode = Mode.NONE
+ linkState = LinkState.DISCONNECTED
+ desktopName = null
+ sessions = emptyList()
+ dropApprovals()
+ chatLinkLost()
+ wantAllow = null
+ lastState.clear()
+ notifier.cancelAllStatus()
+ }
+
+ /** True if the decision was sent (or applied to the demo). Allow is gated by the biometric prompt in the UI. */
+ fun decide(fingerprint: String, allow: Boolean): Boolean {
+ val request = approvals.firstOrNull { it.fingerprint == fingerprint }
+ if (allow && request != null && !com.coucou.android.core.ApprovalSheetPlan.canAllowHere(request)) {
+ // Whatever asked (a stale notification, a test): a command that was cut is never allowed from here. It stays pending.
+ message = context.getString(R.string.approval_on_computer)
+ return false
+ }
+ val ok = link?.decide(fingerprint, allow) ?: false
+ if (ok && request != null) {
+ // The phone's own history never keeps the command: a label and at most the program's name.
+ recordDecision(Decision(agentName(request.pillId), request.tool, com.coucou.android.core.SafeText.requestLabel(request.tool, request.command), allow, System.currentTimeMillis()))
+ }
+ if (!ok) {
+ message = context.getString(R.string.msg_not_pending)
+ removeApproval(fingerprint) // it cannot be answered any more: no card or pill that lingers
+ }
+ return ok
+ }
+
+ /** Every card goes: the desktop offers a request again if it is still pending once we reconnect. */
+ private fun dropApprovals() {
+ questions.forEach { expiry.remove(it.fingerprint)?.let { r -> main.removeCallbacks(r) } }
+ questions = emptyList()
+ overlay.hide()
+ expiry.values.forEach { main.removeCallbacks(it) }
+ expiry.clear()
+ approvals.forEach { notifier.cancelApproval(it.fingerprint) }
+ approvals = emptyList()
+ refreshIsland()
+ }
+
+ private fun removeApproval(fingerprint: String) {
+ expiry.remove(fingerprint)?.let { main.removeCallbacks(it) }
+ approvals = approvals.filter { it.fingerprint != fingerprint }
+ notifier.cancelApproval(fingerprint)
+ refreshIsland()
+ }
+
+ // ── LinkListener (link thread) ───────────────────────────────────────────
+
+ override fun onState(state: LinkState) {
+ main.post {
+ linkState = state
+ relayIssue = relayConnector?.issue ?: com.coucou.android.link.RelayIssue.NONE
+ if (state == LinkState.CONNECTED) {
+ health = health.recovered()
+ screenWasOff = power?.isInteractive == false // the screen is off right now: this link starts its life asleep
+ }
+ if (state == LinkState.CONNECTED) finder.connected() // found it (or never lost it): stop looking
+ // A card for a request we can no longer answer would only produce "no longer pending".
+ if (state != LinkState.CONNECTED && mode == Mode.PAIRED) dropApprovals()
+ if (state != LinkState.CONNECTED) chatLinkLost()
+ refreshIsland()
+ }
+ }
+
+ override fun onWelcome(desktopName: String, os: String) {
+ main.post { if (mode != Mode.DEMO && desktopName.isNotBlank()) this.desktopName = desktopName }
+ }
+
+ override fun onCaps(caps: Set<String>) {
+ main.post {
+ chatOffered = Protocol.CAP_CHAT in caps
+ detailsOffered = Protocol.CAP_DETAILS in caps
+ diffsOffered = Protocol.CAP_DIFFS in caps
+ if (Protocol.CAP_USAGE !in caps) usage = null
+ if (Protocol.CAP_SERVICES !in caps) services = emptyList()
+ }
+ }
+
+ override fun onUsage(usage: com.coucou.android.link.UsageSnapshot) {
+ main.post { this.usage = usage.takeIf { it.claude != null || it.codex != null } }
+ }
+
+ override fun onServices(cards: List<com.coucou.android.link.ServiceCard>) {
+ main.post { services = cards }
+ }
+
+ override fun onPrefs(outfit: String) {
+ main.post { applyComputerOutfit(outfit) }
+ }
+
+ fun applyComputerOutfit(outfit: String) {
+ val v = com.coucou.android.mochi.outfit.Wardrobe.parse(outfit)
+ computerOutfit = v
+ kv.put("computer_outfit", v)
+ }
+
+ override fun onChatModels(models: List<ChatModel>) {
+ main.post {
+ chatModels = models
+ chatModel = ChatModels.pick(models, chatModel)
+ }
+ }
+
+ override fun onChatDelta(id: String, text: String) {
+ main.post { chatSession.onDelta(id, text); chatChanged(save = false) }
+ }
+
+ override fun onChatDone(id: String, text: String?) {
+ main.post { chatSession.onDone(id, text); chatChanged(save = true) }
+ }
+
+ override fun onChatError(id: String, reason: String, message: String) {
+ main.post { chatSession.onError(id, reason); chatChanged(save = true) }
+ }
+
+ override fun onSessions(sessions: List<SessionInfo>) {
+ main.post {
+ this.sessions = sessions
+ val minute = java.time.LocalTime.now().let { it.hour * 60 + it.minute }
+ for (s in sessions) {
+ val prev = lastState.put(s.pillId, s.state)
+ val name = agentName(s.pillId)
+ val sound = com.coucou.android.mochi.MochiConst.STATE_SOUND[s.state]
+ if (sound != null && StatusPolicy.stateSoundWanted(prev, s.state, settings)) sounds.play(sound)
+ val a = StatusPolicy.announce(prev, s.state, settings, minute, inForeground)
+ if (a.sound && sound != null) sounds.play(sound)
+ if (a.notify) notifier.showStatus(s.pillId, name, s.state, s.statusText)
+ IslandPlan.flash(prev, s, settings, minute, islandAllowed(), this::agentName)?.let { overlay.flash(it) }
+ // The agent moved on: the notice about the last state is stale.
+ if (prev != s.state && s.state !in NEWSWORTHY) notifier.cancelStatus(s.pillId)
+ }
+ lastState.keys.retainAll(sessions.map { it.pillId }.toSet())
+ refreshIsland()
+ }
+ }
+
+ override fun onApproval(request: ApprovalRequest) {
+ main.post {
+ approvals = approvals.filter { it.fingerprint != request.fingerprint } + request
+ // One announcement only: the island if it can show, else the heads-up notification.
+ refreshIsland()
+ notifier.showApproval(request, agentName(request.pillId), OverlayPolicy.approvalAlert(overlay.isShowingRequest()))
+ // Offered for 120 s from now, by this phone's clock (the notification times out then too).
+ expiry.remove(request.fingerprint)?.let { main.removeCallbacks(it) }
+ val gone = Runnable { removeApproval(request.fingerprint) }
+ expiry[request.fingerprint] = gone
+ main.postDelayed(gone, Protocol.APPROVAL_TTL_MS)
+ }
+ }
+
+ override fun onQuestion(request: QuestionRequest) {
+ main.post {
+ questions = questions.filter { it.fingerprint != request.fingerprint } + request
+ // Offered for 120 s from now, like an approval; the computer drops it at 115 s.
+ expiry.remove(request.fingerprint)?.let { main.removeCallbacks(it) }
+ val gone = Runnable { removeQuestion(request.fingerprint) }
+ expiry[request.fingerprint] = gone
+ main.postDelayed(gone, Protocol.APPROVAL_TTL_MS)
+ }
+ }
+
+ private fun removeQuestion(fingerprint: String) {
+ expiry.remove(fingerprint)?.let { main.removeCallbacks(it) }
+ questions = questions.filter { it.fingerprint != fingerprint }
+ }
+
+ /** The question of this agent, if one waits for the phone's answer. */
+ fun questionFor(pillId: String): QuestionRequest? = questions.firstOrNull { it.pillId == pillId }
+
+ /**
+ * Sends the picks; the lock check has already happened in the UI (BiometricGate). True if it was sent. What was
+ * picked is not logged, not stored and not put in the history.
+ */
+ fun answerQuestion(fingerprint: String, picks: List<List<String>>): Boolean {
+ val sent = link?.answer(fingerprint, picks) ?: false
+ if (sent) removeQuestion(fingerprint)
+ return sent
+ }
+
+ // ── A file's change (cap `diffs`) ──────────────────────────────────────────────────
+
+ private val diffAssembler = com.coucou.android.core.DiffAssembler()
+ private val diffTimeout = Runnable {
+ (diffState as? com.coucou.android.core.DiffState.Loading)?.let { diffState = com.coucou.android.core.DiffState.Failed(it.name) }
+ diffAssembler.cancel()
+ }
+
+ /** What the file-change sheet shows; Idle closes it. The lines are held only while it is open. */
+ var diffState by mutableStateOf<com.coucou.android.core.DiffState>(com.coucou.android.core.DiffState.Idle); private set
+
+ /** Opens the sheet for a file of a session's list and asks the computer for its lines. */
+ fun openDiff(pillId: String, file: com.coucou.android.link.FileChange) {
+ diffState = com.coucou.android.core.DiffState.Loading(pillId, file.id, file.name)
+ diffAssembler.expect(pillId, file.id)
+ main.removeCallbacks(diffTimeout)
+ if (link?.getDiff(pillId, file.id) == true) main.postDelayed(diffTimeout, DIFF_WAIT_MS)
+ else diffState = com.coucou.android.core.DiffState.Failed(file.name)
+ }
+
+ /** Closes the sheet and forgets the lines. */
+ fun closeDiff() {
+ main.removeCallbacks(diffTimeout)
+ diffAssembler.cancel()
+ diffState = com.coucou.android.core.DiffState.Idle
+ }
+
+ override fun onDiff(part: com.coucou.android.link.ServerMsg.Diff) {
+ main.post {
+ val done = diffAssembler.accept(part) ?: return@post
+ main.removeCallbacks(diffTimeout)
+ if (diffState is com.coucou.android.core.DiffState.Loading) diffState = com.coucou.android.core.DiffState.Ready(done)
+ }
+ }
+
+ override fun onApprovalResolved(fingerprint: String) {
+ main.post {
+ removeQuestion(fingerprint)
+ removeApproval(fingerprint)
+ if (wantAllow == fingerprint) wantAllow = null
+ }
+ }
+
+ /** The computer replaced the relay's access key: this phone follows it (kept encrypted) and reconnects with it. */
+ override fun onRelayAccess(access: String) {
+ main.post {
+ val p = currentPairing ?: return@post
+ val r = p.relay ?: return@post
+ if (r.access == access) return@post
+ val q = p.copy(relay = r.copy(access = access))
+ store.savePairing(q)
+ currentPairing = q
+ restartLink(q)
+ }
+ }
+
+ /** A link that had worked ended on its own: remembered with its reason, so Home can say what happened. */
+ override fun onLinkLost(reason: LostReason) {
+ main.post {
+ health = health.lost(System.currentTimeMillis(), reason, screenWasOff)
+ kv.put("link_drops_off", health.dropsWhileScreenOff)
+ }
+ }
+
+ override fun onConnectFailed(consecutive: Int) {
+ main.post { health = health.failedAttempt(consecutive) }
+ // The saved address failed: now (and only now) look for the computer on the network.
+ if (consecutive >= DiscoveryPolicy.FAILURES_BEFORE_DISCOVERY) main.post { if (mayDiscover()) finder.request() }
+ }
+
+ override fun onError(code: String, message: String) {
+ main.post {
+ this.message = if (code == "auth") context.getString(R.string.msg_rejected)
+ else "${context.getString(R.string.msg_link_error)}: $message"
+ }
+ }
+
+ private companion object {
+ /** How long the sheet waits for the lines of a file before saying it could not load them. */
+ const val DIFF_WAIT_MS = 10_000L
+ val NEWSWORTHY = setOf(BotState.QUESTION, BotState.ERROR, BotState.FINISHED, BotState.RATELIMIT)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/BiometricGate.kt b/android/app/src/main/kotlin/com/coucou/android/app/BiometricGate.kt
new file mode 100644
index 00000000..faa85508
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/BiometricGate.kt
@@ -0,0 +1,37 @@
+package com.coucou.android.app
+
+import android.app.Activity
+import android.hardware.biometrics.BiometricManager
+import android.hardware.biometrics.BiometricPrompt
+import android.os.CancellationSignal
+
+/**
+ * "Allow" from the phone needs the user's face, fingerprint or screen lock, like Face ID on the
+ * iPhone. With no screen lock set up, Allow is refused: Deny always works.
+ */
+object BiometricGate {
+ private const val AUTH = BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL
+
+ fun available(activity: Activity): Boolean =
+ activity.getSystemService(BiometricManager::class.java).canAuthenticate(AUTH) == BiometricManager.BIOMETRIC_SUCCESS
+
+ fun confirm(activity: Activity, title: String, subtitle: String, noLockMessage: String, onSuccess: () -> Unit, onFail: (String) -> Unit) {
+ if (!available(activity)) { onFail(noLockMessage); return }
+ BiometricPrompt.Builder(activity)
+ .setTitle(title)
+ .setSubtitle(subtitle)
+ .setAllowedAuthenticators(AUTH)
+ .build()
+ .authenticate(
+ CancellationSignal(), activity.mainExecutor,
+ object : BiometricPrompt.AuthenticationCallback() {
+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = onSuccess()
+ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
+ val cancelled = errorCode == BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED ||
+ errorCode == BiometricPrompt.BIOMETRIC_ERROR_CANCELED
+ onFail(if (cancelled) "" else errString.toString()) // empty: the user backed out, say nothing
+ }
+ },
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/ChatFile.kt b/android/app/src/main/kotlin/com/coucou/android/app/ChatFile.kt
new file mode 100644
index 00000000..46932ae0
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/ChatFile.kt
@@ -0,0 +1,24 @@
+package com.coucou.android.app
+
+import com.coucou.android.core.TextFile
+import java.io.File
+
+/**
+ * The chat history file, in the app's private storage (not backed up: allowBackup is off). Written
+ * to a temporary file first so a crash never leaves half a history.
+ */
+class ChatFile(private val file: File) : TextFile {
+ override fun read(): String? = try { if (file.isFile) file.readText() else null } catch (_: Exception) { null }
+
+ override fun write(text: String) {
+ try {
+ val tmp = File(file.parentFile, file.name + ".tmp")
+ tmp.writeText(text)
+ if (!tmp.renameTo(file)) { file.writeText(text); tmp.delete() }
+ } catch (_: Exception) {
+ // A history that cannot be saved is not worth stopping the chat for.
+ }
+ }
+
+ override fun delete() { runCatching { file.delete() } }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/CoucouApp.kt b/android/app/src/main/kotlin/com/coucou/android/app/CoucouApp.kt
new file mode 100644
index 00000000..e1ee7763
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/CoucouApp.kt
@@ -0,0 +1,7 @@
+package com.coucou.android.app
+
+import android.app.Application
+
+class CoucouApp : Application() {
+ val model: AppModel by lazy { AppModel(this) }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/GlanceTile.kt b/android/app/src/main/kotlin/com/coucou/android/app/GlanceTile.kt
new file mode 100644
index 00000000..6c866581
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/GlanceTile.kt
@@ -0,0 +1,49 @@
+package com.coucou.android.app
+
+import android.annotation.SuppressLint
+import android.app.PendingIntent
+import android.content.ComponentName
+import android.content.Intent
+import android.os.Build
+import android.service.quicksettings.Tile
+import android.service.quicksettings.TileService
+import com.coucou.android.MainActivity
+import com.coucou.android.core.Glance
+
+/**
+ * The quick-settings tile: on while the computer is connected, its second line is the headline of [Glance]. A tap
+ * opens Coucou (it never approves or changes anything). The system calls [onStartListening] when the shade opens, so
+ * it needs no timer; [requestUpdate] asks it to refresh when the picture changes while the shade is open.
+ */
+class GlanceTile : TileService() {
+ override fun onStartListening() = paint(this)
+
+ // Below Android 14 only the Intent form exists; lint flags the call although it is behind the version check.
+ @SuppressLint("StartActivityAndCollapseDeprecated")
+ override fun onClick() {
+ val open = Intent(this, MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ if (Build.VERSION.SDK_INT >= 34) {
+ startActivityAndCollapse(PendingIntent.getActivity(this, 0, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
+ } else {
+ @Suppress("DEPRECATION")
+ startActivityAndCollapse(open)
+ }
+ }
+
+ companion object {
+ /** Asks the system to refresh the tile if it is on screen (it ignores this when the tile is not added). */
+ fun requestUpdate(context: android.content.Context) {
+ runCatching { requestListeningState(context, ComponentName(context, GlanceTile::class.java)) }
+ }
+
+ private fun paint(tile: TileService) {
+ val t = tile.qsTile ?: return
+ val g: Glance = (tile.applicationContext as CoucouApp).model.glance()
+ t.label = "Coucou"
+ t.subtitle = g.headline
+ t.state = if (g.connected) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
+ t.updateTile()
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/GlanceWidget.kt b/android/app/src/main/kotlin/com/coucou/android/app/GlanceWidget.kt
new file mode 100644
index 00000000..dce827c9
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/GlanceWidget.kt
@@ -0,0 +1,53 @@
+package com.coucou.android.app
+
+import android.app.PendingIntent
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProvider
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.widget.RemoteViews
+import com.coucou.android.MainActivity
+import com.coucou.android.R
+import com.coucou.android.core.Glance
+
+/**
+ * The home-screen widget: the same short summary as the notification and the tile ([Glance]), drawn with plain
+ * RemoteViews. It never updates on a timer (updatePeriodMillis = 0): the app pushes a new picture when something
+ * changes, so it costs nothing while nothing happens. A tap opens Coucou.
+ */
+class GlanceWidget : AppWidgetProvider() {
+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
+ val model = (context.applicationContext as CoucouApp).model
+ val views = views(context, model.glance())
+ for (id in ids) runCatching { manager.updateAppWidget(id, views) }
+ }
+
+ companion object {
+ /** Pushes [glance] to every widget of this app on the home screen (none: nothing happens). */
+ fun update(context: Context, glance: Glance) {
+ runCatching {
+ val manager = AppWidgetManager.getInstance(context)
+ val ids = manager.getAppWidgetIds(ComponentName(context, GlanceWidget::class.java))
+ if (ids.isEmpty()) return
+ val views = views(context, glance)
+ for (id in ids) manager.updateAppWidget(id, views)
+ }
+ }
+
+ private fun views(context: Context, g: Glance): RemoteViews {
+ val v = RemoteViews(context.packageName, R.layout.widget_glance)
+ v.setTextViewText(R.id.widget_headline, g.headline)
+ v.setTextViewText(R.id.widget_detail, g.detail)
+ v.setTextColor(R.id.widget_dot, g.tone.argb)
+ v.setTextViewText(R.id.widget_lines, g.lines.joinToString("\n") { "${it.agent}: ${it.text}" })
+ val open = Intent(context, MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ v.setOnClickPendingIntent(
+ R.id.widget_root,
+ PendingIntent.getActivity(context, 0, open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE),
+ )
+ return v
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/KeepAlive.kt b/android/app/src/main/kotlin/com/coucou/android/app/KeepAlive.kt
new file mode 100644
index 00000000..e3b26e83
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/KeepAlive.kt
@@ -0,0 +1,52 @@
+package com.coucou.android.app
+
+import android.app.AlarmManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.os.PowerManager
+import android.os.SystemClock
+import com.coucou.android.link.KeepAlivePolicy
+
+/**
+ * The heartbeat that works while the phone sleeps. Timers inside the app stop with the CPU, so a ping every 20 seconds cannot run in
+ * Doze; an alarm can (`setAndAllowWhileIdle`: no special permission; Android runs it at most about every nine minutes in Doze and
+ * may delay it to a maintenance window). Each time it fires the link is asked for a pong (reconnect if none) and the next alarm is set.
+ */
+object KeepAliveAlarm {
+ private const val ACTION = "com.coucou.android.KEEP_ALIVE"
+
+ private fun pending(context: Context): PendingIntent =
+ PendingIntent.getBroadcast(
+ context, 1, Intent(context, KeepAliveReceiver::class.java).setAction(ACTION),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+
+ fun arm(context: Context) {
+ val app = context.applicationContext
+ val am = app.getSystemService(AlarmManager::class.java) ?: return
+ runCatching {
+ am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + KeepAlivePolicy.INTERVAL_MS, pending(app))
+ }
+ }
+
+ fun cancel(context: Context) {
+ val app = context.applicationContext
+ runCatching { app.getSystemService(AlarmManager::class.java)?.cancel(pending(app)) }
+ }
+}
+
+/** Not exported: only our own alarm can start it. */
+class KeepAliveReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ // The phone may be going back to sleep the moment this returns, and the question to the computer and its answer need the CPU
+ // for a few seconds. A wake lock with a timeout releases itself; it is never held longer than that, and never held between checks.
+ runCatching {
+ context.getSystemService(PowerManager::class.java)
+ ?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "coucou:keepalive")
+ ?.apply { setReferenceCounted(false); acquire(KeepAlivePolicy.WAKE_LOCK_MS) }
+ }
+ (context.applicationContext as CoucouApp).model.keepAliveTick()
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/LaunchActivity.kt b/android/app/src/main/kotlin/com/coucou/android/app/LaunchActivity.kt
new file mode 100644
index 00000000..57c29f01
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/LaunchActivity.kt
@@ -0,0 +1,23 @@
+package com.coucou.android.app
+
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+import com.coucou.android.MainActivity
+
+/**
+ * Where our own notification actions and the island's Allow land. It is not exported, so no other app can start it;
+ * it passes the request to the app inside the process ([PendingLaunch]) and opens MainActivity with a plain intent.
+ */
+class LaunchActivity : Activity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val model = (application as CoucouApp).model
+ model.launch.request(intent.getStringExtra(Notifications.EXTRA_FP), intent.getBooleanExtra(Notifications.EXTRA_ALLOW, false))
+ startActivity(
+ Intent(this, MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP),
+ )
+ finish()
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/LinkService.kt b/android/app/src/main/kotlin/com/coucou/android/app/LinkService.kt
new file mode 100644
index 00000000..1bb5222c
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/LinkService.kt
@@ -0,0 +1,38 @@
+package com.coucou.android.app
+
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+
+/**
+ * Keeps the desktop link alive while the app is in the background, so approvals arrive as
+ * notifications. Only runs while a desktop is paired; stops when the user unpairs.
+ */
+class LinkService : Service() {
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val model = (application as CoucouApp).model
+ val notification = model.notifier.ongoing(model)
+ // The specialUse type exists from Android 14; older versions reject an unknown type.
+ if (Build.VERSION.SDK_INT >= 34) {
+ startForeground(Notifications.ONGOING_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
+ } else {
+ startForeground(Notifications.ONGOING_ID, notification)
+ }
+ model.resume()
+ return START_STICKY
+ }
+
+ companion object {
+ fun start(context: Context) {
+ runCatching { context.startForegroundService(Intent(context, LinkService::class.java)) }
+ }
+ fun stop(context: Context) {
+ context.stopService(Intent(context, LinkService::class.java))
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/NetworkWatch.kt b/android/app/src/main/kotlin/com/coucou/android/app/NetworkWatch.kt
new file mode 100644
index 00000000..884c7f45
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/NetworkWatch.kt
@@ -0,0 +1,58 @@
+package com.coucou.android.app
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+
+/**
+ * Tells the model when the network changes (a new Wi-Fi, a hotspot) and whether a Wi-Fi or cable is up at all.
+ * Registered only while a computer is paired; the system calls back on a change, nothing polls.
+ */
+class NetworkWatch(
+ context: Context,
+ private val onChange: (wifiUp: Boolean) -> Unit,
+ /** A network became the default one (Wi-Fi joined, Wi-Fi to mobile data): the link may be on the old one and half dead. */
+ private val onNewNetwork: () -> Unit = {},
+) {
+ private val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java)
+ private var callback: ConnectivityManager.NetworkCallback? = null
+
+ @Volatile var wifiUp: Boolean = isWifiUp()
+ private set
+
+ fun isWifiUp(): Boolean {
+ val n = cm.activeNetwork ?: return false
+ val c = cm.getNetworkCapabilities(n) ?: return false
+ return c.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || c.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
+ }
+
+ fun isCellular(): Boolean {
+ val n = cm.activeNetwork ?: return false
+ return cm.getNetworkCapabilities(n)?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true
+ }
+
+ @Synchronized
+ fun start() {
+ if (callback != null) return
+ val cb = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) { changed(); onNewNetwork() }
+ override fun onLost(network: Network) { changed() }
+ override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) { changed() }
+ }
+ callback = cb
+ runCatching { cm.registerDefaultNetworkCallback(cb) }
+ }
+
+ @Synchronized
+ fun stop() {
+ callback?.let { runCatching { cm.unregisterNetworkCallback(it) } }
+ callback = null
+ }
+
+ private fun changed() {
+ val up = isWifiUp()
+ wifiUp = up
+ onChange(up)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/Notifications.kt b/android/app/src/main/kotlin/com/coucou/android/app/Notifications.kt
new file mode 100644
index 00000000..2b2415df
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/Notifications.kt
@@ -0,0 +1,232 @@
+package com.coucou.android.app
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.ContentResolver
+import android.content.Context
+import android.content.Intent
+import android.media.AudioAttributes
+import android.net.Uri
+import android.util.Log
+import com.coucou.android.MainActivity
+import com.coucou.android.R
+import com.coucou.android.core.ApprovalSheetPlan
+import com.coucou.android.core.Glance
+import com.coucou.android.core.GlanceTone
+import com.coucou.android.core.OverlayPolicy
+import com.coucou.android.core.SafeText
+import com.coucou.android.core.ToolLabels
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.mochi.BotState
+
+/**
+ * Notifications: one quiet ongoing notification for the link, and a loud one per approval.
+ * Deny acts straight from the notification. Allow always opens the app for the biometric
+ * check first, and the command is hidden on the lock screen.
+ */
+class Notifications(private val context: Context) {
+ private val nm = context.getSystemService(NotificationManager::class.java)
+
+ init {
+ nm.deleteNotificationChannel("approvals")
+ nm.deleteNotificationChannel("approvals_v2")
+ nm.createNotificationChannel(
+ NotificationChannel(CH_LINK, "Connection", NotificationManager.IMPORTANCE_LOW).apply {
+ description = "Shows that Coucou is connected to your computer"
+ setShowBadge(false)
+ },
+ )
+ nm.createNotificationChannel(
+ NotificationChannel(CH_UPDATES, "Updates", NotificationManager.IMPORTANCE_LOW).apply {
+ description = "An agent finished, failed or has a question"
+ setShowBadge(false)
+ },
+ )
+ // The same request while the pill is on screen: in the shade only, no heads-up and no sound,
+ // so the pill and the notification never overlap at the top of the screen.
+ nm.createNotificationChannel(
+ NotificationChannel(CH_APPROVAL_QUIET, "Approvals (quiet)", NotificationManager.IMPORTANCE_LOW).apply {
+ description = "A waiting request, kept in the shade while the pill shows it"
+ setShowBadge(false)
+ },
+ )
+ nm.createNotificationChannel(
+ NotificationChannel(CH_APPROVAL, "Approvals", NotificationManager.IMPORTANCE_HIGH).apply {
+ description = "An agent is waiting for your permission"
+ // A short buzz, so a request is felt even when the notification volume is 0 (a channel cannot change
+ // later, which is why this one has a new id).
+ enableVibration(true)
+ vibrationPattern = longArrayOf(0, 500, 150, 500)
+ // Mochi's own approval sound, bundled in res/raw.
+ setSound(
+ Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${context.packageName}/${R.raw.approval}"),
+ AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build(),
+ )
+ },
+ )
+ }
+
+ private fun open(fp: String?, allow: Boolean, code: Int): PendingIntent {
+ // A request goes through LaunchActivity (not exported); a plain open needs no extras and goes straight to the app.
+ val i = Intent(context, if (fp != null) LaunchActivity::class.java else MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ .apply { if (fp != null) { putExtra(EXTRA_FP, fp); putExtra(EXTRA_ALLOW, allow) } }
+ return PendingIntent.getActivity(context, code, i, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ }
+
+ /**
+ * The quiet notification that keeps the link alive: the headline of [Glance] as its title, the detail under it and,
+ * when expanded, one line per agent ("Claude Code: Working"). Only states, never a command or a path. On a locked
+ * screen it shows the plain "Connected" line, like the other notifications of the app.
+ */
+ fun ongoing(model: AppModel?): Notification = ongoing(model?.glance())
+
+ private fun ongoing(g: Glance?): Notification {
+ val title = g?.headline ?: context.getString(R.string.status_connecting)
+ val detail = g?.detail.orEmpty()
+ val b = Notification.Builder(context, CH_LINK)
+ .setSmallIcon(R.drawable.ic_stat_mochi)
+ .setContentTitle(title)
+ .setContentText(detail)
+ .setColor(g?.tone?.argb ?: GlanceTone.CALM.argb)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setShowWhen(false)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPublicVersion(
+ Notification.Builder(context, CH_LINK).setSmallIcon(R.drawable.ic_stat_mochi)
+ .setContentTitle(context.getString(R.string.app_name))
+ .setContentText(if (g?.connected == true) context.getString(R.string.status_connected) else context.getString(R.string.status_not_connected))
+ .build(),
+ )
+ .setContentIntent(open(null, false, 0))
+ if (g != null && g.lines.isNotEmpty()) {
+ b.setStyle(Notification.BigTextStyle().bigText(g.lines.joinToString("\n") { "${it.agent}: ${it.text}" }).setSummaryText(detail))
+ }
+ return b.build()
+ }
+
+ fun updateOngoing(model: AppModel, g: Glance = model.glance()) {
+ if (model.mode == Mode.PAIRED) runCatching { nm.notify(ONGOING_ID, ongoing(g)) }
+ }
+
+ fun showApproval(r: ApprovalRequest, agentName: String, alert: OverlayPolicy.ApprovalAlert = OverlayPolicy.ApprovalAlert.HEADS_UP) {
+ val channel = if (alert == OverlayPolicy.ApprovalAlert.QUIET) CH_APPROVAL_QUIET else CH_APPROVAL
+ Log.d("CoucouOverlay", "approval notification: $alert")
+ val id = idFor(r.fingerprint)
+ val deny = PendingIntent.getBroadcast(
+ context, id, Intent(context, ActionReceiver::class.java).setAction(ACTION_DENY).putExtra(EXTRA_FP, r.fingerprint),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
+ )
+ val publicVersion = Notification.Builder(context, channel)
+ .setSmallIcon(R.drawable.ic_stat_mochi).setContentTitle(context.getString(R.string.approval_title)).setContentText(context.getString(R.string.notif_unlock)).build()
+ val n = Notification.Builder(context, channel)
+ .setSmallIcon(R.drawable.ic_stat_mochi)
+ .setContentTitle(agentName)
+ .setSubText(context.getString(R.string.approval_title))
+ // A label and at most the program's name: the exact command is on the approval sheet, behind a tap.
+ .setContentText(SafeText.requestLabel(r.tool, r.command))
+ .setCategory(Notification.CATEGORY_ALARM)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPublicVersion(publicVersion)
+ .setAutoCancel(true)
+ .setTimeoutAfter(com.coucou.android.link.Protocol.APPROVAL_TTL_MS)
+ .setContentIntent(open(r.fingerprint, false, id))
+ .addAction(Notification.Action.Builder(null, context.getString(R.string.action_deny), deny).build())
+ .apply {
+ // A command the phone cannot show in full is answered on the computer: no Allow here.
+ if (ApprovalSheetPlan.canAllowHere(r)) addAction(Notification.Action.Builder(null, context.getString(R.string.action_allow), open(r.fingerprint, true, id + 1)).build())
+ }
+ .build()
+ runCatching { nm.notify(id, n) } // POST_NOTIFICATIONS may be denied: the in-app card still works
+ if (alert == OverlayPolicy.ApprovalAlert.HEADS_UP) wakeScreen()
+ }
+
+ /**
+ * A request on a sleeping phone lights the screen for a few seconds, so the lock screen shows the notification
+ * ("Unlock to see the request"). The phone stays locked; nothing about the command is shown.
+ */
+ @Suppress("DEPRECATION")
+ private fun wakeScreen() = runCatching {
+ val pm = context.getSystemService(android.os.PowerManager::class.java)
+ if (pm.isInteractive) return@runCatching
+ pm.newWakeLock(android.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK or android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP, "coucou:approval")
+ .acquire(WAKE_MS)
+ }
+
+ fun cancelApproval(fp: String) = nm.cancel(idFor(fp))
+
+ /** An agent finished, failed, hit a limit or asks something. Quiet: Mochi's own sound and the pill are the alerts. */
+ fun showStatus(pillId: String, agentName: String, state: BotState, statusText: String) {
+ val what = context.getString(
+ when (state) {
+ BotState.ERROR -> R.string.notif_error
+ BotState.QUESTION -> R.string.notif_question
+ BotState.RATELIMIT -> R.string.notif_ratelimit
+ else -> R.string.notif_finished
+ },
+ )
+ val n = Notification.Builder(context, CH_UPDATES)
+ .setSmallIcon(R.drawable.ic_stat_mochi)
+ .setContentTitle(agentName)
+ .setContentText(what)
+ .setSubText(ToolLabels.label(statusText).takeIf { it.isNotBlank() })
+ .setCategory(Notification.CATEGORY_STATUS)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPublicVersion(
+ Notification.Builder(context, CH_UPDATES).setSmallIcon(R.drawable.ic_stat_mochi)
+ .setContentTitle(context.getString(R.string.app_name)).setContentText(what).build(),
+ )
+ .setAutoCancel(true)
+ .setContentIntent(open(null, false, 0))
+ .build()
+ runCatching { nm.notify(STATUS_TAG, statusId(pillId), n) }
+ }
+
+ fun cancelStatus(pillId: String) = runCatching { nm.cancel(STATUS_TAG, statusId(pillId)) }
+
+ /** Coucou is on screen: the notices are redundant. */
+ fun cancelAllStatus() {
+ runCatching { nm.activeNotifications.filter { it.tag == STATUS_TAG }.forEach { nm.cancel(it.tag, it.id) } }
+ }
+
+ private fun statusId(pillId: String) = pillId.hashCode() and 0x3fffffff
+
+ /** Opens the app on the biometric prompt for this request (the same as tapping Allow in the notification). */
+ fun openAllow(fp: String) {
+ Log.d("CoucouLaunch", "open the app on Allow (tap on the pill)")
+ runCatching { open(fp, true, idFor(fp) + 1).send() }
+ }
+
+ fun openApp() {
+ Log.d("CoucouLaunch", "open the app (tap on the pill)")
+ runCatching { open(null, false, 0).send() }
+ }
+
+ companion object {
+ const val CH_LINK = "link"
+ private const val WAKE_MS = 6_000L
+ const val CH_APPROVAL = "approvals_v3"
+ const val CH_APPROVAL_QUIET = "approvals_quiet"
+ const val CH_UPDATES = "updates"
+ private const val STATUS_TAG = "status"
+ const val ONGOING_ID = 1
+ const val ACTION_DENY = "com.coucou.android.DENY"
+ const val EXTRA_FP = "fingerprint"
+ const val EXTRA_ALLOW = "allow"
+ /** Even ids for the request, +1 for its Allow action; never collides with ONGOING_ID. */
+ fun idFor(fp: String) = (fp.hashCode() and 0x3fffffff) * 2 + 2
+ }
+}
+
+/** Handles the Deny button. Denying needs no biometric check: it can only make things safer. */
+class ActionReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != Notifications.ACTION_DENY) return
+ val fp = intent.getStringExtra(Notifications.EXTRA_FP) ?: return
+ (context.applicationContext as CoucouApp).model.decide(fp, allow = false)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/NsdDiscovery.kt b/android/app/src/main/kotlin/com/coucou/android/app/NsdDiscovery.kt
new file mode 100644
index 00000000..764baebd
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/NsdDiscovery.kt
@@ -0,0 +1,106 @@
+package com.coucou.android.app
+
+import android.content.Context
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import android.net.wifi.WifiManager
+import android.os.Build
+import android.util.Log
+import com.coucou.android.link.Discovery
+import com.coucou.android.link.DiscoverySource
+import com.coucou.android.link.Found
+import java.net.Inet4Address
+
+/**
+ * Browses for `_coucou._tcp` with the framework's NsdManager (no library). A multicast lock is held only while
+ * browsing and released the moment it stops. Services are resolved one at a time (NsdManager allows one resolve at a time);
+ * what comes back is only what the computer announced: its name, an IPv4 address, the port and the short fingerprint id.
+ * The caller decides if it is the paired computer, and checks the certificate; nothing here is trusted.
+ */
+class NsdDiscovery(context: Context) : DiscoverySource {
+ private val app = context.applicationContext
+ private val nsd = app.getSystemService(NsdManager::class.java)
+ private val wifi = app.getSystemService(WifiManager::class.java)
+ private var lock: WifiManager.MulticastLock? = null
+ private var listener: NsdManager.DiscoveryListener? = null
+ private var onFound: ((Found) -> Unit)? = null
+ private val queue = ArrayDeque<NsdServiceInfo>()
+ private var resolving = false
+
+ @Synchronized
+ override fun start(onFound: (Found) -> Unit) {
+ stop()
+ this.onFound = onFound
+ lock = runCatching {
+ wifi?.createMulticastLock("coucou-discovery")?.apply { setReferenceCounted(false); acquire() }
+ }.getOrNull()
+ val l = object : NsdManager.DiscoveryListener {
+ override fun onDiscoveryStarted(serviceType: String) { Log.d(TAG, "browsing") }
+ override fun onServiceFound(info: NsdServiceInfo) { enqueue(info) }
+ override fun onServiceLost(info: NsdServiceInfo) {}
+ override fun onDiscoveryStopped(serviceType: String) { Log.d(TAG, "browsing stopped") }
+ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { Log.w(TAG, "browse failed: $errorCode"); stop() }
+ override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { Log.w(TAG, "stop failed: $errorCode") }
+ }
+ listener = l
+ try {
+ nsd.discoverServices(Discovery.SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, l)
+ } catch (e: Exception) {
+ Log.w(TAG, "cannot browse: ${e.javaClass.simpleName}")
+ stop()
+ }
+ }
+
+ @Synchronized
+ override fun stop() {
+ listener?.let { runCatching { nsd.stopServiceDiscovery(it) } }
+ listener = null
+ onFound = null
+ queue.clear()
+ resolving = false
+ runCatching { lock?.takeIf { it.isHeld }?.release() }
+ lock = null
+ }
+
+ @Synchronized
+ private fun enqueue(info: NsdServiceInfo) {
+ if (listener == null) return
+ queue.addLast(info)
+ next()
+ }
+
+ @Synchronized
+ @Suppress("DEPRECATION") // resolveService is deprecated from API 34; it still works and keeps one code path for API 30+
+ private fun next() {
+ if (resolving) return
+ val info = queue.removeFirstOrNull() ?: return
+ resolving = true
+ try {
+ nsd.resolveService(info, object : NsdManager.ResolveListener {
+ override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) { done() }
+ override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
+ toFound(serviceInfo)?.let { f -> synchronized(this@NsdDiscovery) { onFound }?.invoke(f) }
+ done()
+ }
+ })
+ } catch (_: Exception) {
+ done()
+ }
+ }
+
+ @Synchronized
+ private fun done() {
+ resolving = false
+ next()
+ }
+
+ @Suppress("DEPRECATION")
+ private fun toFound(info: NsdServiceInfo): Found? {
+ val host = (if (Build.VERSION.SDK_INT >= 34) info.hostAddresses.filterIsInstance<Inet4Address>().firstOrNull() else info.host as? Inet4Address)
+ ?.hostAddress ?: return null
+ fun attr(k: String) = info.attributes[k]?.toString(Charsets.UTF_8)
+ return Found(info.serviceName.orEmpty(), host, info.port, attr("fp"), attr("v"))
+ }
+
+ private companion object { const val TAG = "CoucouDiscovery" }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/ScreenWatch.kt b/android/app/src/main/kotlin/com/coucou/android/app/ScreenWatch.kt
new file mode 100644
index 00000000..4d493f79
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/ScreenWatch.kt
@@ -0,0 +1,42 @@
+package com.coucou.android.app
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import androidx.core.content.ContextCompat
+
+/**
+ * Tells the model when the screen turns on (or the phone is unlocked) and off. Registered only while a computer is paired; these are
+ * system broadcasts that Android delivers to a running app, so nothing polls and nothing runs while the screen stays as it is.
+ */
+class ScreenWatch(context: Context, private val onChange: (on: Boolean) -> Unit) {
+ private val app = context.applicationContext
+ private var receiver: BroadcastReceiver? = null
+
+ @Synchronized
+ fun start() {
+ if (receiver != null) return
+ val r = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ when (intent.action) {
+ Intent.ACTION_SCREEN_OFF -> onChange(false)
+ Intent.ACTION_SCREEN_ON, Intent.ACTION_USER_PRESENT -> onChange(true)
+ }
+ }
+ }
+ receiver = r
+ val filter = IntentFilter().apply {
+ addAction(Intent.ACTION_SCREEN_ON)
+ addAction(Intent.ACTION_SCREEN_OFF)
+ addAction(Intent.ACTION_USER_PRESENT)
+ }
+ runCatching { ContextCompat.registerReceiver(app, r, filter, ContextCompat.RECEIVER_NOT_EXPORTED) }
+ }
+
+ @Synchronized
+ fun stop() {
+ receiver?.let { runCatching { app.unregisterReceiver(it) } }
+ receiver = null
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/app/SecureStore.kt b/android/app/src/main/kotlin/com/coucou/android/app/SecureStore.kt
new file mode 100644
index 00000000..08fc018d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/app/SecureStore.kt
@@ -0,0 +1,65 @@
+package com.coucou.android.app
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.Base64
+import com.coucou.android.link.PairingPayload
+import com.coucou.android.link.PairingCodec
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * Keeps the pairing (which holds the secret token) encrypted with an AES-GCM key that never
+ * leaves the Android Keystore. Backups are off (allowBackup=false), so it stays on this device.
+ */
+class SecureStore(context: Context) {
+ private val prefs = context.getSharedPreferences("coucou_link", Context.MODE_PRIVATE)
+
+ private fun key(): SecretKey {
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ (ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
+ return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
+ init(
+ KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256)
+ .build(),
+ )
+ }.generateKey()
+ }
+
+ fun savePairing(p: PairingPayload) {
+ // K and the relay's access key are inside the same Keystore-encrypted blob as the token: never in clear on the disk.
+ val plain = PairingCodec.encode(p)
+ val c = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) }
+ val ct = c.doFinal(plain.toByteArray(Charsets.UTF_8))
+ prefs.edit().putString(PREF, Base64.encodeToString(c.iv + ct, Base64.NO_WRAP)).apply()
+ }
+
+ fun loadPairing(): PairingPayload? {
+ val blob = prefs.getString(PREF, null) ?: return null
+ return try {
+ val raw = Base64.decode(blob, Base64.NO_WRAP)
+ val c = Cipher.getInstance("AES/GCM/NoPadding").apply {
+ init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, raw, 0, IV_BYTES))
+ }
+ PairingCodec.decode(String(c.doFinal(raw, IV_BYTES, raw.size - IV_BYTES), Charsets.UTF_8)) ?: error("unreadable pairing")
+ } catch (_: Exception) {
+ clearPairing() // unreadable (key lost, corrupted): start clean instead of crashing
+ null
+ }
+ }
+
+ fun clearPairing() = prefs.edit().remove(PREF).apply()
+
+ private companion object {
+ const val ALIAS = "coucou_pairing_key"
+ const val PREF = "pairing"
+ const val IV_BYTES = 12
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Anim.kt b/android/app/src/main/kotlin/com/coucou/android/core/Anim.kt
new file mode 100644
index 00000000..398efd99
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Anim.kt
@@ -0,0 +1,20 @@
+package com.coucou.android.core
+
+import kotlin.math.pow
+
+/** Port of windows/src/core/anim.ts (Ease mirrors BotEngine.swift `enum Ease`). */
+typealias EaseFn = (Double) -> Double
+
+object Ease {
+ val out: EaseFn = { t -> 1 - (1 - t).pow(3) }
+ val inOut: EaseFn = { t -> if (t < 0.5) 4 * t * t * t else 1 - (-2 * t + 2).pow(3) / 2 }
+ val back: EaseFn = { t ->
+ val c1 = 1.7
+ val c3 = c1 + 1
+ 1 + c3 * (t - 1).pow(3) + c1 * (t - 1).pow(2)
+ }
+ val lin: EaseFn = { t -> t }
+ val easeIn: EaseFn = { t -> t * t * t }
+}
+
+fun lerp(a: Double, b: Double, t: Double): Double = a + (b - a) * t
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ApprovalSheetPlan.kt b/android/app/src/main/kotlin/com/coucou/android/core/ApprovalSheetPlan.kt
new file mode 100644
index 00000000..3f595c62
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/ApprovalSheetPlan.kt
@@ -0,0 +1,29 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.ApprovalRequest
+
+/**
+ * What the approval sheet shows and when. Pure, so each rule is a unit test.
+ * The sheet rises over any screen while a request waits, until the user closes it; it comes back for
+ * the next request, or from the "Review request" button on Home.
+ */
+object ApprovalSheetPlan {
+ /** Taps in the first moments are ignored: the sheet must not catch a tap meant for what was under it. Same as the island's. */
+ const val GUARD_MS = 600L
+
+ /** The command box scrolls past this height instead of cutting the text: the whole command that was sent is always readable. */
+ const val COMMAND_BOX_MAX_DP = 220
+
+ /**
+ * Allow from the phone is offered only when the whole command is on the phone. When the computer cut it (a flag it sends with the
+ * request), the phone could show only the start of what would run, so the request is answered on the computer. Deny is always offered.
+ */
+ fun canAllowHere(r: ApprovalRequest): Boolean = !r.truncated
+
+ /** The request to show: the first one the user has not closed, or null. */
+ fun next(approvals: List<ApprovalRequest>, closed: String?): ApprovalRequest? =
+ approvals.firstOrNull { it.fingerprint != closed }
+
+ /** "Wants to run a command": what kind of action it is, never the command itself. */
+ fun action(tool: String): String = ToolLabels.action(tool)
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ChatHistory.kt b/android/app/src/main/kotlin/com/coucou/android/core/ChatHistory.kt
new file mode 100644
index 00000000..574d12ff
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/ChatHistory.kt
@@ -0,0 +1,65 @@
+package com.coucou.android.core
+
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+
+/** One small text file; the app backs it with a private file, tests with memory. */
+interface TextFile {
+ fun read(): String?
+ fun write(text: String)
+ fun delete()
+}
+
+/**
+ * The conversation as kept on the phone: a private file, never sent anywhere, with a Clear button.
+ * Reading a damaged or unknown file gives an empty history rather than an error, and an answer
+ * that was still arriving when the app closed is shown as interrupted.
+ */
+class ChatHistory(private val file: TextFile) {
+ fun load(): List<ChatMessage> = decode(file.read())
+
+ fun save(messages: List<ChatMessage>) {
+ if (messages.isEmpty()) file.delete() else file.write(encode(messages))
+ }
+
+ fun clear() = file.delete()
+
+ companion object {
+ private const val VERSION = 1
+
+ fun encode(messages: List<ChatMessage>): String {
+ val a = JSONArray()
+ for (m in messages.takeLast(ChatSession.MAX_MESSAGES)) {
+ val o = JSONObject().put("id", m.id).put("role", m.role.name.lowercase()).put("text", m.text)
+ .put("status", m.status.name.lowercase())
+ m.reason?.let { o.put("reason", it) }
+ a.put(o)
+ }
+ return JSONObject().put("v", VERSION).put("messages", a).toString()
+ }
+
+ fun decode(text: String?): List<ChatMessage> {
+ if (text.isNullOrBlank()) return emptyList()
+ return try {
+ val o = JSONObject(text)
+ if (o.optInt("v", 0) != VERSION) return emptyList()
+ val a = o.getJSONArray("messages")
+ (0 until a.length()).mapNotNull { message(a.optJSONObject(it)) }.takeLast(ChatSession.MAX_MESSAGES)
+ } catch (_: JSONException) {
+ emptyList()
+ }
+ }
+
+ private fun message(o: JSONObject?): ChatMessage? {
+ o ?: return null
+ val id = o.optString("id", "")
+ val role = ChatRole.entries.firstOrNull { it.name.equals(o.optString("role"), ignoreCase = true) } ?: return null
+ if (id.isBlank()) return null
+ var status = ChatStatus.entries.firstOrNull { it.name.equals(o.optString("status"), ignoreCase = true) } ?: ChatStatus.DONE
+ var reason = o.optString("reason", "").ifEmpty { null }
+ if (status == ChatStatus.STREAMING) { status = ChatStatus.FAILED; reason = "interrupted" }
+ return ChatMessage(id, role, o.optString("text", "").take(ChatSession.MAX_TEXT), status, reason)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ChatSession.kt b/android/app/src/main/kotlin/com/coucou/android/core/ChatSession.kt
new file mode 100644
index 00000000..3a120682
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/ChatSession.kt
@@ -0,0 +1,133 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.ChatModel
+import com.coucou.android.link.ClientMsg
+import com.coucou.android.link.Protocol
+import com.coucou.android.link.Wire
+
+enum class ChatRole { USER, ASSISTANT }
+
+enum class ChatStatus {
+ DONE,
+ /** The answer is still arriving. */
+ STREAMING,
+ /** It stopped before the end; [ChatMessage.reason] says why and the text is what arrived. */
+ FAILED,
+}
+
+data class ChatMessage(
+ val id: String,
+ val role: ChatRole,
+ val text: String,
+ val status: ChatStatus = ChatStatus.DONE,
+ /** A fixed code from the computer (rate, busy, auth...) or one of ours (canceled, connection, interrupted). */
+ val reason: String? = null,
+)
+
+/**
+ * The phone's side of one conversation with the computer's AI providers (docs/ANDROID_LINK.md, Chat):
+ * what is on screen, which answer is being waited for, and what each message from the computer does.
+ * Pure Kotlin, no clock and no Android, so every rule is unit-tested. The computer keeps its own
+ * copy of the conversation in memory; this one is what the user reads.
+ */
+class ChatSession(
+ initial: List<ChatMessage> = emptyList(),
+ private val newId: () -> String = ChatIds::random,
+) {
+ var messages: List<ChatMessage> = initial.takeLast(MAX_MESSAGES); private set
+
+ /** The request id of the answer being waited for; one at a time. */
+ var running: String? = null; private set
+
+ enum class Refusal { EMPTY, TOO_LONG, NO_MODEL, BUSY, OFFLINE }
+
+ sealed interface Sent {
+ data class Ok(val msg: ClientMsg.ChatSend) : Sent
+ data class No(val why: Refusal) : Sent
+ }
+
+ /** Starts a question. Nothing changes unless it is sent. */
+ fun send(text: String, model: String?, connected: Boolean): Sent {
+ val clean = text.trim()
+ return when {
+ clean.isEmpty() -> Sent.No(Refusal.EMPTY)
+ clean.length > Protocol.CHAT_MAX_TEXT -> Sent.No(Refusal.TOO_LONG)
+ model.isNullOrBlank() -> Sent.No(Refusal.NO_MODEL)
+ running != null -> Sent.No(Refusal.BUSY)
+ !connected -> Sent.No(Refusal.OFFLINE)
+ else -> {
+ val id = newId()
+ require(Wire.isChatId(id)) { "bad chat id" }
+ running = id
+ messages = (messages + ChatMessage("u-$id", ChatRole.USER, clean) +
+ ChatMessage(id, ChatRole.ASSISTANT, "", ChatStatus.STREAMING)).takeLast(MAX_MESSAGES)
+ Sent.Ok(ClientMsg.ChatSend(id, model, clean))
+ }
+ }
+ }
+
+ /** Text of the answer being written; anything else (a late piece after Cancel) is ignored. */
+ fun onDelta(id: String, text: String) {
+ if (id != running) return
+ change(id) { it.copy(text = (it.text + text).take(MAX_TEXT), status = ChatStatus.STREAMING) }
+ }
+
+ /** The end of the answer; [full] replaces what was streamed when the computer had to correct it. */
+ fun onDone(id: String, full: String?) {
+ if (id != running) return
+ change(id) { it.copy(text = (full ?: it.text).take(MAX_TEXT), status = ChatStatus.DONE, reason = null) }
+ running = null
+ }
+
+ fun onError(id: String, reason: String) {
+ if (id != running) return
+ fail(id, reason)
+ }
+
+ /** The user pressed Cancel: stop waiting at once. Returns the id to tell the computer about, or null. */
+ fun cancel(): String? {
+ val id = running ?: return null
+ fail(id, "canceled")
+ return id
+ }
+
+ /** The link dropped: an answer on its way will not arrive. */
+ fun onDisconnected() {
+ running?.let { fail(it, "connection") }
+ }
+
+ /** New chat / Clear. */
+ fun clear() {
+ messages = emptyList()
+ running = null
+ }
+
+ private fun fail(id: String, reason: String) {
+ change(id) { it.copy(status = ChatStatus.FAILED, reason = reason) }
+ running = null
+ }
+
+ private fun change(id: String, f: (ChatMessage) -> ChatMessage) {
+ messages = messages.map { if (it.id == id && it.role == ChatRole.ASSISTANT) f(it) else it }
+ }
+
+ companion object {
+ const val MAX_MESSAGES = 200
+ /** The computer never sends more than this for one answer. */
+ const val MAX_TEXT = 40_000
+ }
+}
+
+object ChatIds {
+ private val rnd = java.security.SecureRandom()
+ private const val ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"
+
+ /** 12 random characters; the id only has to be unique within a conversation. */
+ fun random(): String = "c" + (1..12).map { ALPHABET[rnd.nextInt(ALPHABET.length)] }.joinToString("")
+}
+
+object ChatModels {
+ /** The model to use once the list arrives: the saved one if still allowed, else the first. */
+ fun pick(models: List<ChatModel>, saved: String?): String? =
+ models.firstOrNull { it.id == saved }?.id ?: models.firstOrNull()?.id
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ChatTab.kt b/android/app/src/main/kotlin/com/coucou/android/core/ChatTab.kt
new file mode 100644
index 00000000..66022860
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/ChatTab.kt
@@ -0,0 +1,49 @@
+package com.coucou.android.core
+
+/** What the always-visible Chat tab shows. */
+enum class ChatTabState { NOT_PAIRED, NOT_CONNECTED, CHAT_OFF, NO_MODELS, READY }
+
+object ChatTab {
+ /**
+ * In order of what the user can do about it: no computer paired, the computer not reachable, the computer not offering
+ * chat (its switch is off), offering it with no model allowed, or ready.
+ */
+ fun state(paired: Boolean, connected: Boolean, offered: Boolean, modelCount: Int): ChatTabState = when {
+ !paired -> ChatTabState.NOT_PAIRED
+ !connected -> ChatTabState.NOT_CONNECTED
+ !offered -> ChatTabState.CHAT_OFF
+ modelCount <= 0 -> ChatTabState.NO_MODELS
+ else -> ChatTabState.READY
+ }
+
+ /** Where the empty state's button leads: pairing (Home shows it when nothing is paired) or Settings. Null: no button, the hint is the answer. */
+ fun action(state: ChatTabState): Screen? = when (state) {
+ ChatTabState.NOT_PAIRED -> Screen.HOME
+ ChatTabState.NOT_CONNECTED -> Screen.SETTINGS
+ else -> null
+ }
+}
+
+/**
+ * Does the bottom bar fit at a given font size? Each item gets a third of the bar; a label needs roughly 0.6 em per
+ * character plus the item's side padding. A rough rule, but it catches "Settings" at 2.0x on a narrow phone, and the Compose code
+ * also keeps every label on one line.
+ */
+object BarFit {
+ const val BAR_SIDE_MARGIN_DP = 24
+ const val BAR_PADDING_DP = 6
+ const val ITEM_GAP_DP = 4
+ const val ITEM_SIDE_PADDING_DP = 4
+ const val LABEL_SP = 12
+ private const val EM_PER_CHAR = 0.6
+
+ fun itemWidthDp(screenWidthDp: Int, items: Int): Double =
+ (screenWidthDp - 2.0 * BAR_SIDE_MARGIN_DP - 2.0 * BAR_PADDING_DP - ITEM_GAP_DP * (items - 1)) / items
+
+ fun labelWidthDp(label: String, fontScale: Double): Double = label.length * LABEL_SP * fontScale * EM_PER_CHAR + 2.0 * ITEM_SIDE_PADDING_DP
+
+ fun fits(screenWidthDp: Int, labels: List<String>, fontScale: Double): Boolean {
+ val w = itemWidthDp(screenWidthDp, labels.size)
+ return labels.all { labelWidthDp(it, fontScale) <= w }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/DiffAssembler.kt b/android/app/src/main/kotlin/com/coucou/android/core/DiffAssembler.kt
new file mode 100644
index 00000000..53c34222
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/DiffAssembler.kt
@@ -0,0 +1,62 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.DiffRow
+import com.coucou.android.link.Protocol
+import com.coucou.android.link.ServerMsg
+
+/** A file's change, whole: what the sheet shows. Held in memory only while the sheet is open. */
+data class FileDiffView(
+ val pillId: String, val fileId: Long, val name: String, val added: Int, val removed: Int,
+ val tooLarge: Boolean, val gone: Boolean, val truncated: Boolean, val rows: List<DiffRow>,
+)
+
+/** What the sheet is doing. */
+sealed interface DiffState {
+ data object Idle : DiffState
+ data class Loading(val pillId: String, val fileId: Long, val name: String) : DiffState
+ data class Ready(val diff: FileDiffView) : DiffState
+ /** The computer did not answer in time, or the link is down. */
+ data class Failed(val name: String) : DiffState
+}
+
+/**
+ * Puts the parts of a diff back together. Only the diff that was asked for is kept; a part that is not
+ * the next one, from another file, or beyond the computer's limits, is dropped. Never stored.
+ */
+class DiffAssembler {
+ private var pillId: String? = null
+ private var fileId: Long = -1
+ private var parts = 0
+ private val received = ArrayList<ServerMsg.Diff>()
+
+ /** The diff being waited for; anything else that arrives is dropped. */
+ fun expect(pillId: String, fileId: Long) {
+ this.pillId = pillId
+ this.fileId = fileId
+ parts = 0
+ received.clear()
+ }
+
+ fun cancel() { pillId = null; received.clear(); parts = 0 }
+
+ /** The whole diff once its last part is in, else null. */
+ fun accept(m: ServerMsg.Diff): FileDiffView? {
+ if (m.pillId != pillId || m.fileId != fileId) return null
+ if (m.part == 0) {
+ received.clear()
+ parts = m.parts
+ } else if (m.parts != parts || m.part != received.size) {
+ return null // out of order or from another answer: wait for a fresh first part
+ }
+ received.add(m)
+ if (received.size < parts) return null
+ val rows = received.flatMap { it.lines }.take(Protocol.MAX_DIFF_LINES)
+ val first = received.first()
+ val view = FileDiffView(
+ m.pillId, m.fileId, first.name, first.added, first.removed, first.tooLarge, first.gone,
+ first.truncated || received.sumOf { it.lines.size } > Protocol.MAX_DIFF_LINES, rows,
+ )
+ cancel()
+ return view
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Glance.kt b/android/app/src/main/kotlin/com/coucou/android/core/Glance.kt
new file mode 100644
index 00000000..db020362
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Glance.kt
@@ -0,0 +1,111 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.LinkState
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+
+/** One agent in a glance: its name and one plain line. No command, no path, no answer text. */
+data class GlanceLine(val agent: String, val text: String, val state: BotState)
+
+/** How loud a glance is: picks the dot colour of the widget, the tile state and the notification accent. */
+enum class GlanceTone(val argb: Int) {
+ CALM(0xFF8E8E93.toInt()),
+ OK(0xFF34C759.toInt()),
+ BUSY(0xFF0A84FF.toInt()),
+ ATTENTION(0xFFFF9F0A.toInt()),
+ TROUBLE(0xFFFF453A.toInt()),
+}
+
+/**
+ * What the small surfaces show without opening the app: the ongoing notification, the home-screen widget and the
+ * quick-settings tile. One pure summary so the three always say the same thing. Only agent names and the plain-language
+ * lines of [HomeText] go in: never a command, a path, a file name or a final answer, because a widget or a tile can be
+ * seen without unlocking the phone.
+ */
+data class Glance(
+ val headline: String,
+ val detail: String,
+ val tone: GlanceTone,
+ val connected: Boolean,
+ val lines: List<GlanceLine>,
+ /** Requests and questions waiting for the user. */
+ val waiting: Int,
+)
+
+object GlanceBuilder {
+ const val MAX_LINES = 4
+ private val BUSY = setOf(BotState.WORKING, BotState.THINKING, BotState.SEARCHING)
+ private val TROUBLE = setOf(BotState.ERROR, BotState.RATELIMIT, BotState.DIZZY)
+
+ /** Most urgent first; the same order as the Home list. */
+ private val ORDER = listOf(
+ BotState.APPROVAL, BotState.QUESTION, BotState.ERROR, BotState.RATELIMIT, BotState.DIZZY,
+ BotState.WORKING, BotState.SEARCHING, BotState.THINKING, BotState.FINISHED, BotState.SLEEPING, BotState.IDLE,
+ )
+
+ fun build(
+ paired: Boolean,
+ link: LinkState,
+ desktop: String?,
+ sessions: List<SessionInfo>,
+ approvals: Int,
+ nameOf: (String) -> String,
+ ): Glance {
+ if (!paired) return Glance("Not paired", "Open Coucou to connect to your computer", GlanceTone.CALM, false, emptyList(), 0)
+ if (link != LinkState.CONNECTED) {
+ val connecting = link == LinkState.CONNECTING
+ return Glance(
+ if (connecting) "Connecting…" else "Not connected",
+ if (connecting) "Reaching your computer" else "Coucou cannot reach your computer",
+ GlanceTone.CALM, false, emptyList(), 0,
+ )
+ }
+ val ranked = sessions.sortedBy { ORDER.indexOf(it.state).let { i -> if (i < 0) ORDER.size else i } }
+ val lines = ranked.take(MAX_LINES).map { GlanceLine(nameOf(it.pillId), lineOf(it), it.state) }
+ val questions = sessions.count { it.state == BotState.QUESTION }
+ val waiting = approvals + questions
+ val busy = sessions.count { it.state in BUSY }
+ val trouble = sessions.count { it.state in TROUBLE }
+ val where = desktop?.takeIf { it.isNotBlank() }
+ return when {
+ approvals > 0 -> Glance(
+ "Waiting for you",
+ if (approvals == 1) "1 request to approve" else "$approvals requests to approve",
+ GlanceTone.ATTENTION, true, lines, waiting,
+ )
+ questions > 0 -> Glance(
+ "Waiting for your answer",
+ if (questions == 1) "1 question from an agent" else "$questions questions from agents",
+ GlanceTone.ATTENTION, true, lines, waiting,
+ )
+ trouble > 0 -> Glance(
+ "An agent needs a look",
+ if (trouble == 1) "1 agent stopped" else "$trouble agents stopped",
+ GlanceTone.TROUBLE, true, lines, 0,
+ )
+ busy > 0 -> Glance(
+ if (busy == 1) "${nameOf(ranked.first { it.state in BUSY }.pillId)} is working" else "$busy agents are working",
+ where?.let { "On $it" } ?: "Working",
+ GlanceTone.BUSY, true, lines, 0,
+ )
+ sessions.any { it.state == BotState.FINISHED } -> Glance(
+ "All done", where?.let { "On $it" } ?: "Finished", GlanceTone.OK, true, lines, 0,
+ )
+ else -> Glance("Connected", where?.let { "To $it" } ?: "Nothing is running", GlanceTone.OK, true, lines, 0)
+ }
+ }
+
+ /** The plain line of a session: its state in a few words, never its step text or answer (those stay in the app). */
+ private fun lineOf(s: SessionInfo): String = when (s.state) {
+ BotState.APPROVAL -> "Waiting for your approval"
+ BotState.QUESTION -> "Has a question"
+ BotState.ERROR -> "Stopped on an error"
+ BotState.RATELIMIT -> "Hit a limit"
+ BotState.DIZZY -> "Needs a look"
+ BotState.FINISHED -> "Finished"
+ BotState.SLEEPING, BotState.IDLE -> "Idle"
+ BotState.THINKING -> "Thinking"
+ BotState.SEARCHING -> "Searching"
+ else -> "Working" // never the step text: it can hold a file name or a command
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/HomePanel.kt b/android/app/src/main/kotlin/com/coucou/android/core/HomePanel.kt
new file mode 100644
index 00000000..6eb3c975
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/HomePanel.kt
@@ -0,0 +1,54 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.Rgb
+
+/**
+ * What the Home screen shows, like the PC's Home panel: one agent card for the agent that matters
+ * most (or the one the user tapped), and a grid of the others. Pure, so it is unit-tested.
+ */
+object HomePanel {
+ private val URGENCY = listOf(
+ BotState.APPROVAL, BotState.QUESTION, BotState.ERROR, BotState.RATELIMIT, BotState.DIZZY,
+ BotState.WORKING, BotState.SEARCHING, BotState.THINKING, BotState.FINISHED, BotState.SLEEPING, BotState.IDLE,
+ )
+
+ /** The tapped agent if it is still there, else the one that needs the user most (the first on a tie). */
+ fun focus(sessions: List<SessionInfo>, selectedPillId: String?): SessionInfo? =
+ sessions.firstOrNull { it.pillId == selectedPillId }
+ ?: sessions.minByOrNull { URGENCY.indexOf(it.state).let { i -> if (i < 0) URGENCY.size else i } }
+
+ /** The others, in the order the desktop sent them. */
+ fun others(sessions: List<SessionInfo>, focus: SessionInfo?): List<SessionInfo> =
+ sessions.filter { it.pillId != focus?.pillId }
+
+ /**
+ * The one link on the agent card: answer a waiting request first, else pair when there is no
+ * computer yet, else nothing (Settings has its own button at the top).
+ */
+ enum class Link { NONE, APPROVAL, PAIR }
+
+ fun link(paired: Boolean, demo: Boolean, hasApproval: Boolean): Link = when {
+ hasApproval -> Link.APPROVAL
+ !paired && !demo -> Link.PAIR
+ else -> Link.NONE
+ }
+
+ /** There is something to open: steps, a last message or a project name (only with the "details" capability). */
+ fun hasDetails(s: SessionInfo): Boolean = s.steps.isNotEmpty() || !s.finalLine.isNullOrBlank() || s.project != null || s.files.isNotEmpty()
+
+ /** The colour of an agent: the one the user gave its pill on the computer, else the catalog's. */
+ fun colorHex(s: SessionInfo): String? = s.color ?: Pills.byId(s.pillId)?.colorHex
+
+ /** Newest first, as the detail screen lists them. */
+ fun stepsNewestFirst(s: SessionInfo): List<String> = s.steps.asReversed()
+
+ /** "#8AB4F8" to a colour for a mini Mochi's body; a malformed value gives null (the default body). */
+ fun rgb(hex: String): Rgb? {
+ val h = hex.trim().removePrefix("#")
+ if (h.length != 6) return null
+ val v = h.toIntOrNull(16) ?: return null
+ return Rgb(((v shr 16) and 0xFF) / 255.0, ((v shr 8) and 0xFF) / 255.0, (v and 0xFF) / 255.0)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/HomeText.kt b/android/app/src/main/kotlin/com/coucou/android/core/HomeText.kt
new file mode 100644
index 00000000..7ddf3734
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/HomeText.kt
@@ -0,0 +1,28 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+
+/** The words on Home: one plain line per agent, what you decided lately, how many are busy. Pure, so it is unit-tested. */
+object HomeText {
+ private val BUSY = setOf(BotState.WORKING, BotState.THINKING, BotState.SEARCHING)
+
+ /**
+ * The sentence under an agent's name: its last message once it has finished, otherwise what it is
+ * doing in plain words ([ToolLabels]). Null when there is nothing to say; the screen then shows the state's name.
+ */
+ fun line(s: SessionInfo): String? {
+ if (s.state == BotState.FINISHED) s.finalLine?.let { SafeText.prose(it) }?.takeIf { it.isNotEmpty() && it != "…" }?.let { return it }
+ return ToolLabels.label(s.statusText).takeIf { it.isNotEmpty() }
+ }
+
+ /** "Allowed: edit files" or "Denied: run a command", for the Recent list. */
+ fun recent(allowed: Boolean, tool: String): String = (if (allowed) "Allowed: " else "Denied: ") + ToolLabels.action(tool)
+
+ /** "You allowed Claude Code to run a command": a decision in a sentence, with no command and no path. */
+ fun decision(allowed: Boolean, agent: String, tool: String): String =
+ "You ${if (allowed) "allowed" else "denied"} ${agent.ifBlank { "an agent" }} to ${ToolLabels.action(tool)}"
+
+ /** How many agents are busy (working, thinking or searching), for "2 running". */
+ fun running(sessions: List<SessionInfo>): Int = sessions.count { it.state in BUSY }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/IconSpec.kt b/android/app/src/main/kotlin/com/coucou/android/core/IconSpec.kt
new file mode 100644
index 00000000..f7436337
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/IconSpec.kt
@@ -0,0 +1,58 @@
+package com.coucou.android.core
+
+/**
+ * The app's icons as geometry on a 24 x 24 grid, stroked 1.9 wide with round ends and joins (the same
+ * drawing style as the PC's `views/icons.ts`). No icon library: ui/DesignIcons.kt draws these.
+ * Pure data, so a test can check every point is on the grid and every icon has a drawing.
+ */
+sealed interface IconShape {
+ /** Straight segments through [points] (x1, y1, x2, y2, ...). */
+ data class Poly(val points: List<Double>) : IconShape
+ data class Circle(val cx: Double, val cy: Double, val r: Double) : IconShape
+ data class RoundRect(val x: Double, val y: Double, val w: Double, val h: Double, val r: Double) : IconShape
+ /** An arc of the circle at ([cx], [cy]): [start] and [sweep] in degrees, clockwise from three o'clock. */
+ data class Arc(val cx: Double, val cy: Double, val r: Double, val start: Double, val sweep: Double) : IconShape
+}
+
+enum class IconKind { HOME, CHAT, SLIDERS, BACK, SEND, LOCK, SCAN, CHEVRON, CHECK, CLOSE }
+
+object IconSpec {
+ const val GRID = 24.0
+ const val STROKE = 1.9
+
+ private fun poly(vararg p: Double) = IconShape.Poly(p.toList())
+
+ fun shapes(kind: IconKind): List<IconShape> = when (kind) {
+ IconKind.HOME -> listOf(poly(4.0, 11.5, 12.0, 5.0, 20.0, 11.5), poly(6.0, 10.5, 6.0, 19.0, 18.0, 19.0, 18.0, 10.5))
+ IconKind.CHAT -> listOf(IconShape.RoundRect(3.5, 5.5, 17.0, 12.0, 2.0), poly(11.0, 17.5, 7.0, 20.5, 7.0, 17.5))
+ // Three horizontal rails with two knobs: "adjust", never a sun or a gear.
+ IconKind.SLIDERS -> listOf(
+ poly(4.0, 7.0, 13.0, 7.0), poly(17.0, 7.0, 20.0, 7.0), poly(4.0, 17.0, 7.0, 17.0), poly(11.0, 17.0, 20.0, 17.0),
+ IconShape.Circle(15.0, 7.0, 2.0), IconShape.Circle(9.0, 17.0, 2.0),
+ )
+ IconKind.BACK -> listOf(poly(14.5, 6.0, 8.5, 12.0, 14.5, 18.0))
+ IconKind.SEND -> listOf(poly(12.0, 19.0, 12.0, 6.0), poly(6.5, 11.5, 12.0, 6.0, 17.5, 11.5))
+ IconKind.LOCK -> listOf(
+ IconShape.RoundRect(5.5, 10.5, 13.0, 9.0, 2.5), poly(8.5, 10.5, 8.5, 8.0), poly(15.5, 10.5, 15.5, 8.0),
+ IconShape.Arc(12.0, 8.0, 3.5, 180.0, 180.0),
+ )
+ IconKind.SCAN -> listOf(
+ poly(4.0, 8.0, 4.0, 6.0, 6.0, 4.0, 8.0, 4.0), poly(16.0, 4.0, 18.0, 4.0, 20.0, 6.0, 20.0, 8.0),
+ poly(20.0, 16.0, 20.0, 18.0, 18.0, 20.0, 16.0, 20.0), poly(8.0, 20.0, 6.0, 20.0, 4.0, 18.0, 4.0, 16.0),
+ poly(8.0, 12.0, 16.0, 12.0),
+ )
+ IconKind.CHEVRON -> listOf(poly(9.5, 6.0, 15.5, 12.0, 9.5, 18.0))
+ IconKind.CHECK -> listOf(poly(5.5, 12.5, 9.7, 16.7, 18.5, 7.5))
+ IconKind.CLOSE -> listOf(poly(7.0, 7.0, 17.0, 17.0), poly(17.0, 7.0, 7.0, 17.0))
+ }
+
+ /** Every x and y the icon uses, including the extent of circles, rectangles and arcs. */
+ fun extent(kind: IconKind): List<Double> = shapes(kind).flatMap {
+ when (it) {
+ is IconShape.Poly -> it.points
+ is IconShape.Circle -> listOf(it.cx - it.r, it.cx + it.r, it.cy - it.r, it.cy + it.r)
+ is IconShape.RoundRect -> listOf(it.x, it.x + it.w, it.y, it.y + it.h)
+ is IconShape.Arc -> listOf(it.cx - it.r, it.cx + it.r, it.cy - it.r, it.cy + it.r)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/IslandGeometry.kt b/android/app/src/main/kotlin/com/coucou/android/core/IslandGeometry.kt
new file mode 100644
index 00000000..5386b470
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/IslandGeometry.kt
@@ -0,0 +1,67 @@
+package com.coucou.android.core
+
+import kotlin.math.max
+import kotlin.math.min
+
+/** A rectangle in pixels (the display cutout's bounding box at the top of the screen). */
+data class PxRect(val left: Int, val top: Int, val right: Int, val bottom: Int) {
+ val centerX: Int get() = (left + right) / 2
+ val width: Int get() = right - left
+}
+
+/** Where the island sits and how big it is, in pixels. */
+data class IslandBox(
+ /** Horizontal offset of the island's centre from the screen's centre (negative = left). */
+ val centerOffsetX: Int,
+ /** Space at the top that the camera cut-out or status bar takes: content starts below it. */
+ val topInset: Int,
+ /** Width of the island when it is hidden in the notch. */
+ val notchWidth: Int,
+ val workingW: Int, val workingH: Int,
+ val cardW: Int, val cardH: Int,
+ val approvalW: Int, val approvalH: Int,
+ val cornerSmall: Int, val cornerLarge: Int,
+)
+
+/**
+ * The island is centred on the camera cut-out (a centred waterdrop on the Galaxy A12s), its black
+ * merges with the hole, and its content starts under it. With no cut-out it hangs from the
+ * status bar, centred on the screen. Sizes follow the PC (working strip, card, request card).
+ */
+object IslandGeometry {
+ const val MARGIN_DP = 12
+ /** The concave flare on each side where the island meets the top edge of the screen (the PC's `#island::before/after`). */
+ const val EAR_DP = 14
+ const val MAX_W_DP = 340
+ const val WORKING_W_DP = 240 // narrow: it should look like it grows out of the camera hole
+ const val MIN_NOTCH_DP = 44
+ const val HOLE_PAD_DP = 10
+
+ fun place(screenW: Int, density: Float, cutoutTop: PxRect?, statusBarH: Int): IslandBox {
+ fun dp(v: Int) = (v * density).toInt()
+ // The flares sit outside the island's width, so they come off the room it may use.
+ val maxW = min(screenW - 2 * dp(MARGIN_DP) - 2 * dp(EAR_DP), dp(MAX_W_DP))
+ val cut = cutoutTop?.takeIf { it.width > 0 && it.bottom > 0 }
+ val top = max(cut?.bottom ?: statusBarH, 0)
+ // Keep the island on screen even when the cut-out is off-centre.
+ val rawOffset = cut?.let { it.centerX - screenW / 2 } ?: 0
+ val room = max(screenW / 2 - maxW / 2, 0)
+ val offset = rawOffset.coerceIn(-room, room)
+ // Hidden, the island is just a little wider than the camera hole, so it appears to grow out of it.
+ val notch = min(max((cut?.width ?: 0) + dp(HOLE_PAD_DP), dp(MIN_NOTCH_DP)), maxW)
+ return IslandBox(
+ centerOffsetX = offset, topInset = top, notchWidth = notch,
+ workingW = min(dp(WORKING_W_DP), maxW), workingH = top + dp(52),
+ cardW = maxW, cardH = top + dp(96),
+ approvalW = maxW, approvalH = top + dp(168),
+ cornerSmall = dp(14), cornerLarge = dp(22),
+ )
+ }
+
+ /** Size for a kind of content. */
+ fun sizeFor(box: IslandBox, kind: IslandSpec.Kind): Pair<Int, Int> = when (kind) {
+ IslandSpec.Kind.WORKING -> box.workingW to box.workingH
+ IslandSpec.Kind.APPROVAL -> box.approvalW to box.approvalH
+ else -> box.cardW to box.cardH
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/IslandMotion.kt b/android/app/src/main/kotlin/com/coucou/android/core/IslandMotion.kt
new file mode 100644
index 00000000..7e382b81
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/IslandMotion.kt
@@ -0,0 +1,120 @@
+package com.coucou.android.core
+
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.ceil
+import kotlin.math.max
+
+/**
+ * The island's motion, a port of windows/src/core/anim.ts so the phone moves like the PC:
+ * growing is a spring (response 0.5 s, damping 0.72), shrinking and retracting is a 340 ms
+ * timed curve cubic-bezier(.45, 0, .2, 1) with no overshoot. No Android dependency.
+ */
+fun cubicBezier(x1: Double, y1: Double, x2: Double, y2: Double): EaseFn {
+ fun cx(t: Double) = (1 - t) * (1 - t) * 3 * t * x1 + 3 * (1 - t) * t * t * x2 + t * t * t
+ fun cy(t: Double) = (1 - t) * (1 - t) * 3 * t * y1 + 3 * (1 - t) * t * t * y2 + t * t * t
+ return { x ->
+ var lo = 0.0
+ var hi = 1.0
+ var t = x
+ repeat(12) {
+ if (cx(t) < x) lo = t else hi = t
+ t = (lo + hi) / 2
+ }
+ cy(t)
+ }
+}
+
+val closeCurve: EaseFn = cubicBezier(0.45, 0.0, 0.2, 1.0)
+
+class Spring(var value: Double, response: Double = 0.5, damping: Double = 0.72) {
+ var target = value
+ var velocity = 0.0
+ private var omega = 2 * PI / response
+ private var zeta = damping
+
+ fun configure(response: Double, damping: Double) {
+ omega = 2 * PI / response
+ zeta = damping
+ }
+
+ val settled: Boolean get() = abs(target - value) < 0.01 && abs(velocity) < 0.05
+
+ /** Sub-stepped at 1/240 s so a dropped frame never destabilises it. */
+ fun step(dt: Double) {
+ val steps = max(1, ceil(dt / (1.0 / 240)).toInt())
+ val h = dt / steps
+ repeat(steps) {
+ val acc = omega * omega * (target - value) - 2 * zeta * omega * velocity
+ velocity += acc * h
+ value += velocity * h
+ }
+ }
+}
+
+/** A value driven by a spring when it grows and by the close curve when it shrinks (IslandContainer). */
+class Tracked(initial: Double) {
+ private val spring = Spring(initial)
+ private var curveFrom = 0.0
+ private var curveTo = 0.0
+ private var curveStartMs = 0.0
+ private var curveDurMs = 0.0
+ private enum class Mode { SPRING, CURVE, IDLE }
+ private var mode = Mode.IDLE
+
+ val value: Double get() = spring.value
+ val animating: Boolean get() = mode != Mode.IDLE
+
+ fun jump(v: Double) {
+ spring.value = v
+ spring.target = v
+ spring.velocity = 0.0
+ mode = Mode.IDLE
+ }
+
+ fun springTo(v: Double, response: Double = 0.5, damping: Double = 0.72) {
+ spring.configure(response, damping)
+ spring.target = v
+ mode = Mode.SPRING
+ }
+
+ fun curveTowards(v: Double, nowMs: Double, durationMs: Double = CLOSE_MS) {
+ curveFrom = spring.value
+ curveTo = v
+ curveStartMs = nowMs
+ curveDurMs = durationMs
+ spring.target = v
+ spring.velocity = 0.0
+ mode = Mode.CURVE
+ }
+
+ /** Grow with the spring, shrink with the curve (what the PC does on every size change). */
+ fun goTo(v: Double, nowMs: Double) {
+ if (v < value) curveTowards(v, nowMs) else springTo(v)
+ }
+
+ fun step(dtSeconds: Double, nowMs: Double) {
+ when (mode) {
+ Mode.SPRING -> {
+ spring.step(dtSeconds)
+ if (spring.settled) {
+ spring.value = spring.target
+ spring.velocity = 0.0
+ mode = Mode.IDLE
+ }
+ }
+ Mode.CURVE -> {
+ val p = ((nowMs - curveStartMs) / curveDurMs).coerceIn(0.0, 1.0)
+ // The bisection leaves a hair of error at the ends: land exactly on the target.
+ spring.value = if (p >= 1) curveTo else lerp(curveFrom, curveTo, closeCurve(p))
+ if (p >= 1) {
+ spring.velocity = 0.0
+ mode = Mode.IDLE
+ }
+ }
+ Mode.IDLE -> {}
+ }
+ }
+
+ companion object { const val CLOSE_MS = 340.0 }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/IslandPlan.kt b/android/app/src/main/kotlin/com/coucou/android/core/IslandPlan.kt
new file mode 100644
index 00000000..168d022a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/IslandPlan.kt
@@ -0,0 +1,66 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+
+/**
+ * Which session the island is about, and whether it may show at all. Pure: the same inputs always
+ * give the same answer, so every rule is unit-tested.
+ */
+object IslandPlan {
+ /** The switch, the system permission and Coucou not being on screen. */
+ fun allowed(overlayOn: Boolean, permitted: Boolean, appInForeground: Boolean) =
+ OverlayPolicy.shouldShow(overlayOn, permitted, appInForeground)
+
+ private val WORKING = setOf(BotState.WORKING, BotState.THINKING, BotState.SEARCHING)
+
+ /**
+ * What is going on right now: a permission request (its text is the kind of action, never the command), a question, or an agent at work. Null when
+ * the island may not show or nothing needs it. [approvals] come first; [name] gives the agent's name.
+ */
+ fun active(
+ sessions: List<SessionInfo>,
+ approvals: List<ApprovalRequest>,
+ allowed: Boolean,
+ name: (String) -> String,
+ ): IslandSpec? {
+ if (!allowed) return null
+ approvals.firstOrNull()?.let {
+ return IslandSpec(IslandSpec.Kind.APPROVAL, it.pillId, name(it.pillId), BotState.APPROVAL, ToolLabels.action(it.tool), it.fingerprint, ApprovalSheetPlan.canAllowHere(it))
+ }
+ val question = sessions.firstOrNull { it.state == BotState.QUESTION }
+ if (question != null) return spec(IslandSpec.Kind.QUESTION, question, name)
+ val working = sessions.firstOrNull { it.state in WORKING }
+ if (working != null) return spec(IslandSpec.Kind.WORKING, working, name)
+ return null
+ }
+
+ /**
+ * A finished, failed or rate-limited agent: only on a change into that state (never the first
+ * picture after connecting), only if the user wants those notices, and not during quiet hours.
+ * The same rule as [StatusPolicy.announce]: the pill part.
+ */
+ fun flash(
+ previous: BotState?,
+ session: SessionInfo,
+ settings: UserSettings,
+ minuteOfDay: Int,
+ allowed: Boolean,
+ name: (String) -> String,
+ ): IslandSpec? {
+ if (!allowed) return null
+ val kind = when (session.state) {
+ BotState.FINISHED -> IslandSpec.Kind.FINISHED
+ BotState.ERROR -> IslandSpec.Kind.ERROR
+ BotState.RATELIMIT -> IslandSpec.Kind.RATELIMIT
+ else -> return null
+ }
+ val a = StatusPolicy.announce(previous, session.state, settings, minuteOfDay, appInForeground = false)
+ if (!a.pill) return null
+ return spec(kind, session, name)
+ }
+
+ private fun spec(kind: IslandSpec.Kind, s: SessionInfo, name: (String) -> String) =
+ IslandSpec(kind, s.pillId, name(s.pillId), s.state, ToolLabels.label(s.statusText))
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/IslandTimeline.kt b/android/app/src/main/kotlin/com/coucou/android/core/IslandTimeline.kt
new file mode 100644
index 00000000..91df76cd
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/IslandTimeline.kt
@@ -0,0 +1,107 @@
+package com.coucou.android.core
+
+import com.coucou.android.mochi.BotState
+
+/** What the island shows. [pillId] is the session it is about (or the request's pill). */
+data class IslandSpec(
+ val kind: Kind,
+ val pillId: String,
+ val agent: String,
+ val state: BotState,
+ val text: String,
+ /** The request this is about (approvals only): what Allow and Deny act on. */
+ val fingerprint: String? = null,
+ /** False for a request whose command could not be shown in full: the island offers Deny only. */
+ val canAllow: Boolean = true,
+) {
+ enum class Kind { WORKING, QUESTION, APPROVAL, FINISHED, ERROR, RATELIMIT }
+
+ /** Working, a question and a permission request stay until something changes. */
+ val persistent: Boolean get() = kind == Kind.WORKING || kind == Kind.QUESTION || kind == Kind.APPROVAL
+}
+
+/**
+ * When the island is open and when it goes back up into the notch, with an injectable clock.
+ *
+ * - [setActive]: what is going on right now (working, a question, a request). It needs no deadline.
+ * - [flash]: a finished, failed or rate-limited event. Held [HOLD_MS] (10 s, as the user asked), then
+ * the island retracts. A newer event restarts the hold.
+ * - The island re-opens when something starts while it is retracting; a content change (working to
+ * finished) never retracts it.
+ * - [nextDeadline] is the only time anything must wake up: while hidden it is null, so nothing runs.
+ */
+class IslandTimeline(private val clockMs: () -> Double) {
+ enum class Phase { HIDDEN, OPEN, RETRACTING }
+
+ var phase = Phase.HIDDEN
+ private set
+
+ private var active: IslandSpec? = null
+ private var flash: IslandSpec? = null
+ private var flashUntil = 0.0
+ private var retractUntil = 0.0
+
+ /** What to draw now (kept while retracting, so the island shrinks around its last content). */
+ var current: IslandSpec? = null
+ private set
+
+ fun setActive(spec: IslandSpec?) {
+ active = spec
+ refresh()
+ }
+
+ fun flash(spec: IslandSpec) {
+ flash = spec
+ flashUntil = clockMs() + HOLD_MS
+ refresh()
+ }
+
+ /** Close at once (Coucou came to the front, the switch went off, the link dropped). */
+ fun dismiss() {
+ active = null
+ flash = null
+ current = null
+ phase = Phase.HIDDEN
+ }
+
+ /** Call when [nextDeadline] has passed. */
+ fun tick() = refresh()
+
+ /** The island has finished moving up: its window can go. */
+ fun retractFinished() {
+ if (phase == Phase.RETRACTING) {
+ phase = Phase.HIDDEN
+ current = null
+ }
+ }
+
+ /** Absolute clock time of the next change, or null when nothing is scheduled (hidden, or persistent content). */
+ fun nextDeadline(): Double? = when (phase) {
+ Phase.HIDDEN -> null
+ Phase.RETRACTING -> retractUntil
+ Phase.OPEN -> if (active == null && flash != null) flashUntil else null
+ }
+
+ private fun refresh() {
+ val now = clockMs()
+ if (flash != null && now >= flashUntil) flash = null
+ val shown = active ?: flash
+ when {
+ shown != null -> {
+ current = shown
+ phase = Phase.OPEN
+ }
+ phase == Phase.OPEN -> {
+ // Nothing left to show: go back up. The content stays for the animation.
+ phase = Phase.RETRACTING
+ retractUntil = now + RETRACT_MS
+ }
+ phase == Phase.RETRACTING && now >= retractUntil -> retractFinished()
+ }
+ }
+
+ companion object {
+ const val HOLD_MS = 10_000.0
+ const val RETRACT_MS = Tracked.CLOSE_MS
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Licences.kt b/android/app/src/main/kotlin/com/coucou/android/core/Licences.kt
new file mode 100644
index 00000000..21681120
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Licences.kt
@@ -0,0 +1,14 @@
+package com.coucou.android.core
+
+/**
+ * The licence texts the app shows (Settings > About > Licences). They are files under assets/licenses so the exact words ship in the app:
+ * NOTICES (who owns what, and the libraries), then the MIT text of Coucou's code, then the Apache 2.0 text.
+ */
+object Licences {
+ /** In the order they are shown. */
+ val FILES = listOf("NOTICES.txt", "MIT.txt", "Apache-2.0.txt")
+
+ /** The text cut into blocks at blank lines, so a long licence is a list the screen can scroll without laying it all out at once. */
+ fun paragraphs(text: String): List<String> =
+ text.replace("\r\n", "\n").split(Regex("\n\\s*\n")).map { it.trim('\n') }.filter { it.isNotBlank() }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/MarkdownLite.kt b/android/app/src/main/kotlin/com/coucou/android/core/MarkdownLite.kt
new file mode 100644
index 00000000..dcf135c0
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/MarkdownLite.kt
@@ -0,0 +1,86 @@
+package com.coucou.android.core
+
+/** A run of text with the few styles a chat answer needs. */
+data class MdSpan(val text: String, val bold: Boolean = false, val code: Boolean = false)
+
+sealed interface MdBlock {
+ data class Para(val spans: List<MdSpan>) : MdBlock
+ data class Bullet(val spans: List<MdSpan>) : MdBlock
+ data class Code(val text: String) : MdBlock
+}
+
+/**
+ * The light Markdown the computer's chat asks the models for: short paragraphs, bullet lists, **bold**,
+ * `inline code` and fenced code blocks. Anything else (links, images, HTML, tables) stays plain text, so an
+ * answer can never make the app open or load something. Safe on half an answer: a fence or a marker that has
+ * not closed yet is shown as it is until the rest arrives.
+ */
+object MarkdownLite {
+ fun parse(text: String): List<MdBlock> {
+ val blocks = mutableListOf<MdBlock>()
+ val para = mutableListOf<String>()
+ fun flush() {
+ if (para.isNotEmpty()) blocks.add(MdBlock.Para(inline(para.joinToString("\n")))); para.clear()
+ }
+ val lines = text.replace("\r\n", "\n").split("\n")
+ var i = 0
+ while (i < lines.size) {
+ val line = lines[i]
+ val trimmed = line.trimStart()
+ when {
+ trimmed.startsWith("```") -> {
+ flush()
+ val code = mutableListOf<String>()
+ i++
+ // An unfinished fence (the answer is still arriving) runs to the end.
+ while (i < lines.size && !lines[i].trimStart().startsWith("```")) code.add(lines[i++])
+ blocks.add(MdBlock.Code(code.joinToString("\n")))
+ }
+ line.isBlank() -> flush()
+ isBullet(trimmed) -> { flush(); blocks.add(MdBlock.Bullet(inline(trimmed.substring(2).trimStart()))) }
+ trimmed.startsWith("#") && trimmed.dropWhile { it == '#' }.startsWith(" ") -> {
+ // A heading is a bold line: the chat window is small, so no big titles.
+ flush(); blocks.add(MdBlock.Para(listOf(MdSpan(trimmed.dropWhile { it == '#' }.trim(), bold = true))))
+ }
+ else -> para.add(line)
+ }
+ i++
+ }
+ flush()
+ return blocks
+ }
+
+ private fun isBullet(t: String) = t.length > 2 && (t[0] == '-' || t[0] == '*' || t[0] == '•') && t[1] == ' '
+
+ /** **bold** and `code`; a marker with no partner is left as the characters it is. */
+ fun inline(text: String): List<MdSpan> {
+ val out = mutableListOf<MdSpan>()
+ val plain = StringBuilder()
+ fun emitPlain() { if (plain.isNotEmpty()) out.add(MdSpan(plain.toString())); plain.clear() }
+ var i = 0
+ while (i < text.length) {
+ if (text.startsWith("**", i)) {
+ val end = text.indexOf("**", i + 2)
+ if (end > i + 2) { emitPlain(); out.add(MdSpan(text.substring(i + 2, end), bold = true)); i = end + 2; continue }
+ }
+ if (text[i] == '`') {
+ val end = text.indexOf('`', i + 1)
+ if (end > i + 1) { emitPlain(); out.add(MdSpan(text.substring(i + 1, end), code = true)); i = end + 1; continue }
+ }
+ plain.append(text[i]); i++
+ }
+ emitPlain()
+ return out
+ }
+}
+
+/** The codes the computer (or this app) gives for an answer that did not complete. */
+object ChatReasons {
+ val KNOWN = listOf(
+ "off", "not_allowed", "busy", "rate", "too_long", "empty", "no_key", "unreachable", "auth", "provider",
+ "canceled", "internal", "connection", "interrupted",
+ )
+
+ /** A code this version does not know is shown as a general problem. */
+ fun key(code: String?): String = if (code != null && code in KNOWN) code else "internal"
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Navigation.kt b/android/app/src/main/kotlin/com/coucou/android/core/Navigation.kt
new file mode 100644
index 00000000..a6dea777
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Navigation.kt
@@ -0,0 +1,42 @@
+package com.coucou.android.core
+
+/** The three places the bottom bar leads to. */
+enum class Tab { HOME, CHAT, SETTINGS }
+
+/** Every screen of the app. Tabs are the roots; the rest are one level down. */
+enum class Screen { HOME, CHAT, SETTINGS, HISTORY, GALLERY, WARDROBE, DIAGNOSTICS, LICENCES, SESSION, SCAN }
+
+/**
+ * Where the user is and where Back goes. Pure, so every rule is a unit test:
+ * - the bar always has Home, Chat and Settings (Chat shows why it cannot chat yet when that is the case);
+ * - the bar shows on the three tab roots, and hides on every page below them and while the keyboard is open;
+ * - Back goes up one level; on Home it is the system's (leave the app).
+ */
+object Nav {
+ /** Home, Chat and Settings, always: Chat explains itself when the computer does not offer it. */
+ fun tabs(): List<Tab> = listOf(Tab.HOME, Tab.CHAT, Tab.SETTINGS)
+
+ fun screenOf(tab: Tab): Screen = when (tab) {
+ Tab.HOME -> Screen.HOME
+ Tab.CHAT -> Screen.CHAT
+ Tab.SETTINGS -> Screen.SETTINGS
+ }
+
+ /** The tab a screen belongs to, so the bar can highlight it; null for full-screen tasks. */
+ fun tabOf(screen: Screen): Tab? = when (screen) {
+ Screen.HOME -> Tab.HOME
+ Screen.CHAT -> Tab.CHAT
+ Screen.SETTINGS, Screen.HISTORY, Screen.GALLERY, Screen.WARDROBE, Screen.DIAGNOSTICS, Screen.LICENCES -> Tab.SETTINGS
+ Screen.SESSION, Screen.SCAN -> null
+ }
+
+ fun barVisible(screen: Screen, keyboardOpen: Boolean): Boolean =
+ !keyboardOpen && screen in setOf(Screen.HOME, Screen.CHAT, Screen.SETTINGS)
+
+ /** One level up, or null when Back should leave the app. */
+ fun back(screen: Screen): Screen? = when (screen) {
+ Screen.HOME -> null
+ Screen.CHAT, Screen.SETTINGS, Screen.SESSION, Screen.SCAN -> Screen.HOME
+ Screen.HISTORY, Screen.GALLERY, Screen.WARDROBE, Screen.DIAGNOSTICS, Screen.LICENCES -> Screen.SETTINGS
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/OverlayPolicy.kt b/android/app/src/main/kotlin/com/coucou/android/core/OverlayPolicy.kt
new file mode 100644
index 00000000..8a90fde4
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/OverlayPolicy.kt
@@ -0,0 +1,59 @@
+package com.coucou.android.core
+
+
+/**
+ * When the small pill drops from the top of the screen, like the notch on the computer: it stays
+ * out of sight, wakes when an agent finishes, fails, asks something or is rate limited, shows for a
+ * moment, then slides away. A permission request is not here: it has its own card that stays until
+ * it is answered.
+ */
+object OverlayPolicy {
+ /** The pill is for when you are in another app; inside Coucou the screen already shows it. */
+ fun shouldShow(enabled: Boolean, permitted: Boolean, appInForeground: Boolean): Boolean =
+ blocker(enabled, permitted, appInForeground) == null
+
+ /**
+ * A tap in the first moments is most likely meant for the app underneath (the pill slides in over
+ * it) or lands by accident. Buttons and the body of the pill ignore it.
+ */
+ const val TAP_GUARD_MS = 600.0
+
+ fun tapAccepted(shownAtMs: Double, nowMs: Double): Boolean = nowMs - shownAtMs >= TAP_GUARD_MS
+
+ /**
+ * How a permission request is announced. When the pill is on screen it is the one thing that
+ * appears; the notification still goes to the shade, quietly, as the fallback. Otherwise the
+ * notification is what tells the user (heads-up and sound).
+ */
+ enum class ApprovalAlert { HEADS_UP, QUIET }
+
+ fun approvalAlert(pillShown: Boolean): ApprovalAlert = if (pillShown) ApprovalAlert.QUIET else ApprovalAlert.HEADS_UP
+
+ /** Why the pill stays away (for the log), or null when it may show. */
+ fun blocker(enabled: Boolean, permitted: Boolean, appInForeground: Boolean): String? = when {
+ !enabled -> "switch is off"
+ !permitted -> "'display over other apps' is not allowed"
+ appInForeground -> "the app is on screen"
+ else -> null
+ }
+}
+
+/** Where the user's wish is kept (SharedPreferences in the app, a plain object in tests). */
+interface WishStore {
+ fun read(): Boolean
+ fun write(on: Boolean)
+}
+
+/**
+ * The switch "Show Mochi over other apps". The wish is saved the moment the user taps, before the
+ * system permission screen opens: if Android recreates the activity or the process while the user is
+ * in Settings, nothing is lost. The permission is asked live each time, so granting it later from
+ * Android's own settings makes the pill work without another tap.
+ */
+class OverlayChoice(private val store: WishStore) {
+ val wished: Boolean get() = store.read()
+ fun choose(on: Boolean) = store.write(on)
+
+ /** What the switch shows, and whether the pill may exist. */
+ fun active(permitted: Boolean): Boolean = wished && permitted
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/PairingScan.kt b/android/app/src/main/kotlin/com/coucou/android/core/PairingScan.kt
new file mode 100644
index 00000000..8fd0704a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/PairingScan.kt
@@ -0,0 +1,50 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.PairingPayload
+
+/** What to do with text that came out of the camera. */
+sealed interface ScanDecision {
+ /** A well-formed Coucou pairing link: ask the user to confirm, then pair like a pasted link. */
+ data class Pairing(val link: String) : ScanDecision
+
+ /** Anything else (a website, a Wi-Fi code, a shop's QR): ignored, with a short hint. */
+ data object NotPairing : ScanDecision
+}
+
+object PairingScan {
+ /**
+ * Uses the very parser that pasting uses, so a scanned code and a pasted link are accepted and refused
+ * for the same reasons. The text is returned untouched (apart from trimming) and never logged.
+ */
+ fun decide(text: String?): ScanDecision {
+ val t = text?.trim().orEmpty()
+ if (t.isEmpty() || t.length > MAX_LINK) return ScanDecision.NotPairing
+ return if (PairingPayload.parse(t) != null) ScanDecision.Pairing(t) else ScanDecision.NotPairing
+ }
+
+ /** A real pairing link is a few hundred characters (up to about 900 with the relay fields and a long, accented name); anything far longer is not one. */
+ const val MAX_LINK = 2_048
+}
+
+/** Where the camera permission stands, for the scan screen. */
+object ScanPermission {
+ enum class State {
+ /** The camera may be used. */
+ GRANTED,
+ /** Show the one-line reason and the "Allow camera" button. */
+ ASK,
+ /** Refused for good: Android will not ask again, so point to its settings or to pasting. */
+ BLOCKED,
+ }
+
+ /**
+ * [askedBefore]: we have shown Android's prompt at least once. [canExplain]: Android says the prompt can
+ * still be shown (it was refused once, not for good).
+ */
+ fun state(granted: Boolean, askedBefore: Boolean, canExplain: Boolean): State = when {
+ granted -> State.GRANTED
+ !askedBefore -> State.ASK
+ canExplain -> State.ASK
+ else -> State.BLOCKED
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Palette.kt b/android/app/src/main/kotlin/com/coucou/android/core/Palette.kt
new file mode 100644
index 00000000..9dca1de5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Palette.kt
@@ -0,0 +1,38 @@
+package com.coucou.android.core
+
+import kotlin.math.pow
+
+/**
+ * The app's colours as plain 0xAARRGGBB numbers, so a test can check that text stays readable on
+ * its background (Theme.kt turns them into Compose colours). The app is dark only.
+ */
+data class Palette(
+ val background: Long, val card: Long, val line: Long,
+ val text: Long, val textDim: Long, val accent: Long, val onAccent: Long, val error: Long,
+) {
+ companion object {
+ val DARK = Palette(
+ background = 0xFF0E0F12, card = 0xFF16171B, line = 0xFF26282E,
+ text = 0xFFF3F4F6, textDim = 0xFFA1A6B0, accent = 0xFF8AB4FF, onAccent = 0xFF0E0F12, error = 0xFFFF8A80,
+ )
+
+ private fun lin(c: Int): Double {
+ val v = c / 255.0
+ return if (v <= 0.03928) v / 12.92 else ((v + 0.055) / 1.055).pow(2.4)
+ }
+
+ private fun luminance(argb: Long): Double {
+ val r = ((argb shr 16) and 0xFF).toInt()
+ val g = ((argb shr 8) and 0xFF).toInt()
+ val b = (argb and 0xFF).toInt()
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
+ }
+
+ /** WCAG contrast ratio, 1 (none) to 21 (black on white). */
+ fun contrast(a: Long, b: Long): Double {
+ val la = luminance(a)
+ val lb = luminance(b)
+ return (maxOf(la, lb) + 0.05) / (minOf(la, lb) + 0.05)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/PendingLaunch.kt b/android/app/src/main/kotlin/com/coucou/android/core/PendingLaunch.kt
new file mode 100644
index 00000000..d5048327
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/PendingLaunch.kt
@@ -0,0 +1,40 @@
+package com.coucou.android.core
+
+/**
+ * "Open the app on Allow for this request", handed from our own notification tap to the main screen inside the
+ * process. MainActivity is exported (it is the launcher and takes coucou:// links), so it must never trust extras on
+ * the intent it is started with: another app could send the same ones and pop the Allow prompt. Only the non-exported
+ * LaunchActivity, started by our own PendingIntents, calls [request]; MainActivity only calls [take].
+ */
+class PendingLaunch(private val clock: () -> Long = System::currentTimeMillis) {
+ data class Request(val fingerprint: String, val allow: Boolean)
+
+ private var fingerprint: String? = null
+ private var allow = false
+ private var at = 0L
+
+ @Synchronized
+ fun request(fp: String?, allow: Boolean) {
+ val clean = fp?.takeIf { it.isNotBlank() && it.length <= MAX_FP }
+ this.fingerprint = clean
+ this.allow = allow && clean != null
+ this.at = clock()
+ }
+
+ /** The request once, if it is fresh; null for everything else (nothing asked, already taken, too old). */
+ @Synchronized
+ fun take(): Request? {
+ val fp = fingerprint ?: return null
+ val fresh = clock() - at <= TTL_MS
+ val a = allow
+ fingerprint = null
+ allow = false
+ return if (fresh) Request(fp, a) else null
+ }
+
+ companion object {
+ /** The tap and the screen are in the same second; a longer wait means something else is going on. */
+ const val TTL_MS = 15_000L
+ const val MAX_FP = 128
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Pills.kt b/android/app/src/main/kotlin/com/coucou/android/core/Pills.kt
new file mode 100644
index 00000000..f4f50bef
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Pills.kt
@@ -0,0 +1,48 @@
+package com.coucou.android.core
+
+/**
+ * Pill catalog, a mirror of windows/src/core/pills.ts (itself PillCatalog.swift).
+ * IDs, names, colours and categories are contract values and never change once shipped.
+ * Apple Music is left out: it has no Android equivalent (support "no" on the desktop ports).
+ */
+enum class PillCategory { WORKSPACE, AGENT, AI, SERVICE }
+
+data class PillDefinition(
+ val id: String,
+ val name: String,
+ val colorHex: String,
+ val category: PillCategory,
+)
+
+object Pills {
+ const val DEFAULT_MAIN_PILL = "integration_claude"
+
+ val catalog: List<PillDefinition> = listOf(
+ PillDefinition("integration_claude", "VS Code", "#F5F6F8", PillCategory.WORKSPACE),
+ PillDefinition("agent_cursor", "Cursor", "#C0C4CC", PillCategory.WORKSPACE),
+ PillDefinition("agent_antigravity", "Antigravity", "#E879F9", PillCategory.WORKSPACE),
+ PillDefinition("agent_codex", "Codex", "#2DD4BF", PillCategory.WORKSPACE),
+ PillDefinition("agent_gemini", "Gemini CLI", "#8AB4F8", PillCategory.AGENT),
+ PillDefinition("agent_copilot", "Copilot CLI", "#818CF8", PillCategory.AGENT),
+ PillDefinition("agent_muse", "Muse Code", "#38BDF8", PillCategory.AGENT),
+ PillDefinition("agent_opencode", "OpenCode", "#4ADE80", PillCategory.AGENT),
+ PillDefinition("agent_amp", "Amp", "#F59E0B", PillCategory.AGENT),
+ PillDefinition("agent_hermes", "Hermes", "#C084FC", PillCategory.AGENT),
+ PillDefinition("agent_claude-desktop", "Claude Desktop", "#D97757", PillCategory.AGENT),
+ PillDefinition("ai_anthropic", "Anthropic", "#E07950", PillCategory.AI),
+ PillDefinition("ai_google", "Google AI", "#4285F4", PillCategory.AI),
+ PillDefinition("ai_openai", "OpenAI", "#10A37F", PillCategory.AI),
+ PillDefinition("ai_ollama", "Ollama", "#FACC15", PillCategory.AI),
+ PillDefinition("ai_lmstudio", "LM Studio", "#A3E635", PillCategory.AI),
+ PillDefinition("integration_resend", "Resend", "#22C55E", PillCategory.SERVICE),
+ PillDefinition("integration_n8n", "n8n", "#F29B38", PillCategory.SERVICE),
+ PillDefinition("integration_vercel", "Vercel", "#7C5CFF", PillCategory.SERVICE),
+ PillDefinition("integration_github", "GitHub", "#F4505E", PillCategory.SERVICE),
+ PillDefinition("integration_notion", "Notion", "#8C8C8C", PillCategory.SERVICE),
+ PillDefinition("integration_calcom", "Cal.com", "#C9956A", PillCategory.SERVICE),
+ PillDefinition("integration_stripe", "Stripe", "#0570DE", PillCategory.SERVICE),
+ PillDefinition("integration_spotify", "Spotify", "#1DB954", PillCategory.SERVICE),
+ )
+
+ fun byId(id: String): PillDefinition? = catalog.firstOrNull { it.id == id }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/PlanText.kt b/android/app/src/main/kotlin/com/coucou/android/core/PlanText.kt
new file mode 100644
index 00000000..6acf21b5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/PlanText.kt
@@ -0,0 +1,46 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.PlanWindow
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.TextStyle
+import java.util.Locale
+
+/**
+ * How the plan usage reads on the phone, the same rules as the PC's pills (windows/src/core/plan.ts): a window
+ * whose reset time has passed counts as 0, green under 50 %, orange up to 80 %, red above. Pure, so it is tested.
+ */
+object PlanText {
+ enum class Level { LOW, MEDIUM, HIGH }
+
+ /** What to show for a window: 0 once its reset time has passed. */
+ fun effectivePct(w: PlanWindow, nowMs: Long): Int = if (w.resetsAtMs <= nowMs) 0 else w.pct
+
+ fun level(pct: Int): Level = when {
+ pct < 50 -> Level.LOW
+ pct < 80 -> Level.MEDIUM
+ else -> Level.HIGH
+ }
+
+ /** "in 1 h 20", "in 5 min", or "Resetting…" for a five-hour window. */
+ fun resetsIn(w: PlanWindow, nowMs: Long): Reset {
+ val secs = (w.resetsAtMs - nowMs) / 1000
+ if (secs <= 0) return Reset.Now
+ val hours = (secs / 3600).toInt()
+ val mins = ((secs % 3600) / 60).toInt()
+ return if (hours > 0) Reset.InHoursMinutes(hours, mins) else Reset.InMinutes(mins)
+ }
+
+ sealed interface Reset {
+ data object Now : Reset
+ data class InHoursMinutes(val h: Int, val m: Int) : Reset
+ data class InMinutes(val m: Int) : Reset
+ }
+
+ /** "Mon 9:00" for the week's window, in the phone's own time zone. */
+ fun weekday(w: PlanWindow, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): String {
+ val t = Instant.ofEpochMilli(w.resetsAtMs).atZone(zone)
+ val day = t.dayOfWeek.getDisplayName(TextStyle.SHORT, locale)
+ return "$day ${t.hour}:%02d".format(t.minute)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/QuestionFlow.kt b/android/app/src/main/kotlin/com/coucou/android/core/QuestionFlow.kt
new file mode 100644
index 00000000..46055b5c
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/QuestionFlow.kt
@@ -0,0 +1,71 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.AskedQuestion
+import com.coucou.android.link.Protocol
+
+/** Where the user is in answering a question from Claude Code: which question, and what is picked for each. */
+data class QuestionState(val index: Int, val picks: List<List<String>>)
+
+/**
+ * The rules of answering (docs/ANDROID_LINK.md, "Answering Claude Code's questions"), pure so each is a unit test. The
+ * labels are the computer's exact ones; nothing the user types ever goes into an answer, only a tap on an option.
+ */
+object QuestionFlow {
+ fun start(questions: List<AskedQuestion>) = QuestionState(0, questions.map { emptyList() })
+
+ private fun current(q: List<AskedQuestion>, s: QuestionState) = q[s.index.coerceIn(0, q.lastIndex)]
+
+ /** A tap on an option: replaces the pick of a single choice, adds or removes one of a multiple choice. An unknown label does nothing. */
+ fun toggle(questions: List<AskedQuestion>, s: QuestionState, label: String): QuestionState {
+ if (questions.isEmpty() || s.picks.size != questions.size) return s
+ val i = s.index.coerceIn(0, questions.lastIndex)
+ val q = questions[i]
+ if (q.options.none { it.label == label }) return s
+ val now = s.picks[i]
+ val next = when {
+ !q.multiSelect -> listOf(label)
+ label in now -> now - label
+ else -> now + label
+ }
+ return s.copy(picks = s.picks.toMutableList().also { it[i] = ordered(q, next) })
+ }
+
+ /** In the order the options are listed, whatever the order of the taps. */
+ private fun ordered(q: AskedQuestion, picked: List<String>) = q.options.map { it.label }.filter { it in picked }
+
+ fun isLast(questions: List<AskedQuestion>, s: QuestionState) = s.index >= questions.lastIndex
+
+ /** The current question has an answer (at least one pick). */
+ fun canAdvance(questions: List<AskedQuestion>, s: QuestionState): Boolean =
+ questions.isNotEmpty() && s.picks.size == questions.size && s.picks[s.index.coerceIn(0, questions.lastIndex)].isNotEmpty()
+
+ fun next(questions: List<AskedQuestion>, s: QuestionState): QuestionState =
+ if (canAdvance(questions, s) && !isLast(questions, s)) s.copy(index = s.index + 1) else s
+
+ fun back(s: QuestionState): QuestionState = if (s.index > 0) s.copy(index = s.index - 1) else s
+
+ /** Every question answered as the computer will accept it: one label for a single choice, one or more for a multiple choice. */
+ fun complete(questions: List<AskedQuestion>, s: QuestionState): Boolean =
+ questions.isNotEmpty() && s.picks.size == questions.size &&
+ questions.indices.all { i ->
+ val p = s.picks[i]
+ val q = questions[i]
+ p.isNotEmpty() && p.size <= q.options.size && (q.multiSelect || p.size == 1) &&
+ p.all { l -> q.options.any { it.label == l } } && p.distinct().size == p.size
+ }
+
+ /** What goes to the computer, or null if something is missing. */
+ fun picks(questions: List<AskedQuestion>, s: QuestionState): List<List<String>>? =
+ if (complete(questions, s)) s.picks else null
+
+ /** For the lock prompt: the answers in a line ("Postgres; Typos, Facets"). The labels are the agent's own words. */
+ fun summary(questions: List<AskedQuestion>, s: QuestionState): String =
+ s.picks.take(questions.size).joinToString("; ") { it.joinToString(", ") }
+
+ /** The computer stops accepting an answer after 115 s; the phone stops offering it at 120 s, like an approval. */
+ fun expired(createdAtMs: Long, nowMs: Long): Boolean = nowMs - createdAtMs > Protocol.APPROVAL_TTL_MS
+
+ /** "Question 2 of 3", or null for a single question. */
+ fun position(questions: List<AskedQuestion>, s: QuestionState): Pair<Int, Int>? =
+ if (questions.size > 1) (s.index + 1) to questions.size else null
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/RelayStatus.kt b/android/app/src/main/kotlin/com/coucou/android/core/RelayStatus.kt
new file mode 100644
index 00000000..3243a1b2
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/RelayStatus.kt
@@ -0,0 +1,24 @@
+package com.coucou.android.core
+
+import com.coucou.android.link.RelayIssue
+import com.coucou.android.link.Route
+
+/** What the "Away from home Wi-Fi" card says. One kind per sentence; the screen maps it to a string. */
+enum class RelayLineKind { NO_RELAY_IN_PAIRING, SWITCHED_OFF, DIRECT, VIA_RELAY, WAITING, ACCESS_REFUSED, ROOM_TAKEN, RATE_LIMITED, UNREACHABLE, COMPUTER_AWAY }
+
+object RelayStatus {
+ fun kind(hasRelay: Boolean, useRelay: Boolean, connected: Boolean, route: Route?, issue: RelayIssue): RelayLineKind = when {
+ !hasRelay -> RelayLineKind.NO_RELAY_IN_PAIRING
+ !useRelay -> RelayLineKind.SWITCHED_OFF
+ connected && route == Route.RELAY -> RelayLineKind.VIA_RELAY
+ connected -> RelayLineKind.DIRECT
+ else -> when (issue) {
+ RelayIssue.ACCESS_REFUSED -> RelayLineKind.ACCESS_REFUSED
+ RelayIssue.ROOM_TAKEN -> RelayLineKind.ROOM_TAKEN
+ RelayIssue.RATE_LIMITED -> RelayLineKind.RATE_LIMITED
+ RelayIssue.UNREACHABLE -> RelayLineKind.UNREACHABLE
+ RelayIssue.COMPUTER_AWAY -> RelayLineKind.COMPUTER_AWAY
+ RelayIssue.NONE -> RelayLineKind.WAITING
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/SafeText.kt b/android/app/src/main/kotlin/com/coucou/android/core/SafeText.kt
new file mode 100644
index 00000000..c4df90c2
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/SafeText.kt
@@ -0,0 +1,62 @@
+package com.coucou.android.core
+
+/**
+ * What may be shown about a command or a step on a surface that can be seen without a deliberate tap (Home, the
+ * island, notifications, cards, the lock screen): a short label and at most the program's name. Never an argument, a
+ * flag, an environment variable, a path, a URL or anything that could hold a secret. The full command exists only on
+ * the approval sheet behind "Show exact command" and in the lock prompt that follows a deliberate tap on Allow.
+ */
+object SafeText {
+ const val PROGRAM_MAX = 20
+
+ private val PROGRAM_CHARS = Regex("[A-Za-z0-9._+-]+")
+ private val ENV_ASSIGNMENT = Regex("[A-Za-z_][A-Za-z0-9_]*=.*")
+
+ /**
+ * The first word of a command, if it is a plain program name: leading NAME=value words are skipped, a path is
+ * reduced to its file name, flags and anything with unusual characters give null, at most [PROGRAM_MAX] characters.
+ */
+ fun program(command: String?): String? {
+ val words = command.orEmpty().trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
+ var i = 0
+ while (i < words.size && ENV_ASSIGNMENT.matches(words[i])) i++ // FOO=bar TOKEN=x npm test: the variables are never shown
+ var word = words.getOrNull(i) ?: return null
+ word = word.trim('"', '\'', '`', '(', ')', '{', '}')
+ if (word.isEmpty() || word.startsWith("-") || word.contains("://") || word.contains('@') || word.contains('=')) return null
+ word = word.substringAfterLast('/').substringAfterLast('\\') // "no paths": only the file name
+ if (word.isEmpty() || word.startsWith("-") || !PROGRAM_CHARS.matches(word)) return null
+ return word.take(PROGRAM_MAX)
+ }
+
+ private val SHELLS = setOf("bash", "shell", "runshellcommand", "execcommand", "exec", "sh", "terminal", "powershell", "cmd")
+
+ private fun isShell(tool: String) = tool.lowercase().filter { it.isLetterOrDigit() } in SHELLS
+
+ /** "Running a command · npm" for a shell tool, "Editing files" for the others: the label of a request. */
+ fun requestLabel(tool: String, command: String?): String {
+ val label = ToolLabels.label(tool).ifEmpty { "Working" }
+ val program = if (isShell(tool)) program(command) else null
+ return if (program != null) "$label · $program" else label
+ }
+
+ /**
+ * Prose the agent wrote (its last message) for a surface that is not behind a tap: every word that looks like a
+ * path, a URL, an address with a user name, a NAME=value pair or a long token is replaced with an ellipsis.
+ */
+ fun prose(text: String): String {
+ val kept = text.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.map { word ->
+ val core = word.trim('.', ',', ';', ':', '!', '?', '"', '\'', '(', ')', '[', ']')
+ when {
+ core.contains('/') || core.contains('\\') || core.contains("://") || core.contains('@') -> "…"
+ core.contains('=') -> "…"
+ core.length > 32 -> "…"
+ Regex("[A-Za-z]:\\\\.*").matches(core) -> "…"
+ else -> word
+ }
+ }
+ // "… … …" says nothing: collapse runs of ellipses.
+ val out = ArrayList<String>()
+ for (w in kept) if (!(w == "…" && out.lastOrNull() == "…")) out.add(w)
+ return out.joinToString(" ")
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/SecureScreens.kt b/android/app/src/main/kotlin/com/coucou/android/core/SecureScreens.kt
new file mode 100644
index 00000000..4e0d7d74
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/SecureScreens.kt
@@ -0,0 +1,19 @@
+package com.coucou.android.core
+
+/**
+ * Which screens hide from screenshots, screen recording and the recent-apps card (FLAG_SECURE): the ones that show the
+ * pairing code or link, the chat with the user's AI, and a request for permission or a question from an agent.
+ * Pure, so the list is a unit test; MainActivity sets or clears the flag from it as the screen changes.
+ */
+object SecureScreens {
+ fun needed(
+ screen: Screen,
+ /** Not paired yet: Home is the pairing screen (link, scan, paste). */
+ pairing: Boolean,
+ approvalSheetShown: Boolean,
+ questionSheetShown: Boolean,
+ /** "Pair with this computer?" after a scan or a link. */
+ pairConfirmShown: Boolean,
+ ): Boolean = screen == Screen.CHAT || screen == Screen.SCAN || (screen == Screen.HOME && pairing) ||
+ approvalSheetShown || questionSheetShown || pairConfirmShown
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/Tokens.kt b/android/app/src/main/kotlin/com/coucou/android/core/Tokens.kt
new file mode 100644
index 00000000..bdd0c04d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/Tokens.kt
@@ -0,0 +1,104 @@
+package com.coucou.android.core
+
+/**
+ * The design tokens as plain numbers, so a test can check contrast and the scale without Compose. The app is dark only.
+ *
+ * Louis Raillé's Mochi, its state colours and the pill colours are not here and are not changed.
+ */
+data class Tokens(
+ /** The screen. */
+ val bg: Long,
+ /** Island panels and cards. */
+ val panel: Long,
+ /** Rows inside a panel, chips, the selected tab. */
+ val panel2: Long,
+ /** The thin border of a panel. */
+ val line: Long,
+ val text: Long,
+ val textDim: Long,
+ /** Hints and placeholders: large text and icons only. */
+ val textFaint: Long,
+ /** The one main action: a pill, as on the PC. */
+ val primaryButton: Long, val onPrimaryButton: Long,
+ /** Every other pill, as a solid colour on [panel]. */
+ val secondaryButton: Long,
+ val danger: Long,
+ /** The "connected" dot and the on switch. */
+ val online: Long,
+ /** Alpha of the coloured glow at the bottom of a panel (0..1). */
+ val washAlpha: Double,
+) {
+ companion object {
+ val DARK = Tokens(
+ bg = 0xFF000000, panel = 0xFF141518, panel2 = 0xFF1D1F23, line = 0xFF26282D,
+ text = 0xFFF5F6F8, textDim = 0xFF9398A1, textFaint = 0xFF6E737C,
+ primaryButton = 0xFFF5F6F8, onPrimaryButton = 0xFF0B0C0E, secondaryButton = 0xFF292A2D,
+ danger = 0xFFFF8D97, online = 0xFF34D399, washAlpha = 0.5,
+ )
+ }
+}
+
+/** The black surfaces: the hero panel on Home and the island over other apps. */
+object IslandSurface {
+ const val BLACK = 0xFF000000L
+ const val PANEL = 0xFF141518L
+ const val HERO = 0xFF0E0F12L
+ const val TEXT = 0xFFF5F6F8L
+ const val TEXT_DIM = 0xFF9398A1L
+ /** Pill buttons on these always-dark surfaces. */
+ const val BUTTON = 0xFF2A2B2EL
+ const val ON_PRIMARY = 0xFF0B0C0EL
+}
+
+/**
+ * The link dot colours: each is visible (3:1 or better) on black and on the dark panels.
+ */
+object StatusPalette {
+ const val ONLINE = 0xFF0F9F6EL
+ const val BUSY = 0xFFB45309L
+ const val OFFLINE = 0xFF6B7280L
+}
+
+/** The spacing scale (dp): every gap, padding and gutter is one of these. */
+object Spacing {
+ val SCALE = listOf(4, 8, 12, 16, 24, 32)
+ const val GUTTER = 16
+ const val GAP = 12
+ const val INSIDE = 16
+ /** The smallest thing a finger must be able to hit, in dp. */
+ const val MIN_TOUCH = 48
+}
+
+/** Corner radii (dp). Pills and chips are fully round. */
+object Radii {
+ const val PANEL = 20
+ const val SHEET = 28
+ const val ISLAND_EXPANDED = 22
+ const val ISLAND_COMPACT = 14
+ const val HERO_BOTTOM = 30
+}
+
+/** One step of the type scale: sizes are sp, so the user's font size setting applies. */
+data class TypeStep(val name: String, val sizeSp: Int, val lineSp: Int, val weight: Int)
+
+object TypeScale {
+ val DISPLAY = TypeStep("display", 28, 34, 700)
+ val TITLE = TypeStep("title", 20, 26, 700)
+ val HEADLINE = TypeStep("headline", 16, 22, 600)
+ val BODY = TypeStep("body", 15, 22, 400)
+ val SECONDARY = TypeStep("secondary", 13, 18, 400)
+ val LABEL = TypeStep("label", 12, 16, 600)
+ /** Only for the exact command and code in chat. */
+ val MONO = TypeStep("mono", 12, 18, 400)
+ val ALL = listOf(DISPLAY, TITLE, HEADLINE, BODY, SECONDARY, LABEL, MONO)
+}
+
+/** Motion constants shared with the PC (see core/IslandMotion.kt for the springs). */
+object MotionSpec {
+ const val RETRACT_MS = 340
+ /** With "remove animations" on, a spring or a slide becomes this fade. */
+ const val REDUCED_MS = 120
+
+ /** Android's "Remove animations" (and developer "animator duration scale: off") sets the scale to 0. */
+ fun isReduced(animatorDurationScale: Float): Boolean = animatorDurationScale <= 0f
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/ToolLabels.kt b/android/app/src/main/kotlin/com/coucou/android/core/ToolLabels.kt
new file mode 100644
index 00000000..b03d1c64
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/ToolLabels.kt
@@ -0,0 +1,95 @@
+package com.coucou.android.core
+
+/**
+ * What the agent is doing, in words a person reads. The desktop sends the last step as the agent
+ * reported it, often a raw tool name ("ask_question", "Bash", "Read"). Known tools get a plain
+ * sentence; an unknown one is only cleaned (no underscores, first letter capital); free text such
+ * as "Running npm test" is left alone. Used by the Home card and the island, so both say the same.
+ */
+object ToolLabels {
+ private val KNOWN = mapOf(
+ "askuserquestion" to "Asking a question",
+ "askquestion" to "Asking a question",
+ "bash" to "Running a command",
+ "shell" to "Running a command",
+ "runshellcommand" to "Running a command",
+ "execcommand" to "Running a command",
+ "read" to "Reading files",
+ "readfile" to "Reading files",
+ "readmanyfiles" to "Reading files",
+ "edit" to "Editing files",
+ "multiedit" to "Editing files",
+ "write" to "Editing files",
+ "writefile" to "Editing files",
+ "notebookedit" to "Editing files",
+ "applypatch" to "Editing files",
+ "grep" to "Searching files",
+ "glob" to "Searching files",
+ "ls" to "Looking at files",
+ "websearch" to "Searching the web",
+ "googlewebsearch" to "Searching the web",
+ "webfetch" to "Reading a web page",
+ "task" to "Running a sub-agent",
+ "todowrite" to "Planning",
+ "exitplanmode" to "Planning",
+ )
+
+ /** The same tools as an action after "wants to" or "Allowed:": "run a command", "edit files". */
+ private val ACTIONS = mapOf(
+ "askuserquestion" to "ask a question", "askquestion" to "ask a question",
+ "bash" to "run a command", "shell" to "run a command", "runshellcommand" to "run a command", "execcommand" to "run a command",
+ "read" to "read files", "readfile" to "read files", "readmanyfiles" to "read files",
+ "edit" to "edit files", "multiedit" to "edit files", "write" to "edit files", "writefile" to "edit files",
+ "notebookedit" to "edit files", "applypatch" to "edit files",
+ "grep" to "search files", "glob" to "search files", "ls" to "look at files",
+ "websearch" to "search the web", "googlewebsearch" to "search the web", "webfetch" to "read a web page",
+ "task" to "run a sub-agent",
+ )
+
+ /** What a request is for, as an action ("run a command"); an unknown tool is cleaned and lower-cased. */
+ fun action(tool: String): String {
+ val name = tool.trim()
+ if (name.isEmpty()) return "do something"
+ return ACTIONS[key(name)] ?: clean(name).lowercase()
+ }
+
+ private const val SEP = " · "
+
+ /** "ask_question" and "AskQuestion" both reduce to "askquestion". */
+ private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
+
+ private fun looksLikeAName(s: String) = s.isNotEmpty() && s.all { it.isLetterOrDigit() || it == '_' || it == '-' || it == '.' || it == ':' }
+
+ /**
+ * The words for a step on a surface that is seen without a tap. The tool is named in plain words; of a shell
+ * command only the program's name follows ([SafeText.program]); the file, the arguments and any free text the
+ * agent wrote are never shown here. Free text that is not a tool name gives "" so the screen falls back to the
+ * state's own word.
+ */
+ fun label(raw: String): String {
+ val text = raw.trim().removeSuffix("·").trim()
+ if (text.isEmpty()) return ""
+ // "Bash · npm test": the tool is named, the rest is what it does (and stays out of sight).
+ val at = text.indexOf(SEP)
+ val head = if (at > 0) text.substring(0, at).trim() else text
+ val rest = if (at > 0) text.substring(at + SEP.length).trim() else ""
+ if (!looksLikeAName(head)) return ""
+ // An unknown word shows only if it can be a tool's name: a key or a token pasted in its place never does.
+ if (KNOWN[key(head)] == null && !plausibleToolName(head)) return ""
+ val tool = KNOWN[key(head)] ?: clean(head)
+ val program = if (rest.isNotEmpty()) SafeText.requestLabel(head, rest).substringAfter(SEP, "") else ""
+ return if (program.isNotEmpty()) "$tool$SEP$program" else tool
+ }
+
+ private val DIGIT_RUN = Regex("[0-9]{3,}")
+
+ private fun plausibleToolName(s: String): Boolean =
+ s.length <= 40 && !DIGIT_RUN.containsMatchIn(s) && (s.length <= 24 || s.any { it == '_' || it == '-' || it == '.' || it == ':' })
+
+ private val SEPARATORS = Regex("[_\\-.:]+")
+ private val CAMEL = Regex("(?<=[a-z0-9])(?=[A-Z])")
+
+ /** "mcp__github__list_issues" to "Mcp github list issues"; "FooBar" to "Foo bar". */
+ fun clean(name: String): String =
+ name.replace(SEPARATORS, " ").replace(CAMEL, " ").trim().lowercase().replaceFirstChar { it.uppercaseChar() }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/core/UserSettings.kt b/android/app/src/main/kotlin/com/coucou/android/core/UserSettings.kt
new file mode 100644
index 00000000..bea3e393
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/core/UserSettings.kt
@@ -0,0 +1,181 @@
+package com.coucou.android.core
+
+import com.coucou.android.mochi.BotState
+import java.time.Instant
+import java.time.LocalDate
+import java.time.ZoneId
+
+/** Where settings are kept (SharedPreferences in the app, a plain map in tests). */
+interface KeyValueStore {
+ fun getBoolean(key: String, default: Boolean): Boolean
+ fun getInt(key: String, default: Int): Int
+ fun getFloat(key: String, default: Float): Float
+ fun getString(key: String, default: String): String
+ fun put(key: String, value: Any)
+}
+
+/** Quiet hours: minutes since midnight. A window may cross midnight (22:00 to 08:00). */
+data class QuietHours(val enabled: Boolean, val fromMin: Int, val toMin: Int) {
+ fun isQuiet(minuteOfDay: Int): Boolean {
+ if (!enabled || fromMin == toMin) return false
+ return if (fromMin < toMin) minuteOfDay in fromMin until toMin
+ else minuteOfDay >= fromMin || minuteOfDay < toMin
+ }
+
+ companion object {
+ const val STEP = 30
+ fun wrap(min: Int): Int = ((min % 1440) + 1440) % 1440
+ }
+}
+
+/** What the user chose in Settings. Defaults keep the app as it was before the settings existed. */
+data class UserSettings(
+ val soundOn: Boolean = true,
+ val volume: Float = com.coucou.android.sound.SoundVolume.DEFAULT,
+ val notifyDone: Boolean = true,
+ val quiet: QuietHours = QuietHours(false, 22 * 60, 8 * 60),
+ /** Mochi's outfit on this phone: "computer" (follow the one chosen on the computer), "auto", "none" or an outfit. */
+ val outfit: String = com.coucou.android.mochi.outfit.Wardrobe.FOLLOW,
+ /** Use the relay when the computer is not reachable on this network (only matters when the pairing includes one). */
+ val useRelay: Boolean = true,
+) {
+ companion object {
+ private const val SOUND = "sound_on"
+ private const val VOLUME = "sound_volume"
+ private const val DONE = "notify_done"
+ private const val Q_ON = "quiet_on"
+ private const val Q_FROM = "quiet_from"
+ private const val Q_TO = "quiet_to"
+ private const val OUTFIT = "outfit_choice"
+ private const val RELAY = "use_relay"
+
+ fun load(store: KeyValueStore): UserSettings {
+ val d = UserSettings()
+ return UserSettings(
+ soundOn = store.getBoolean(SOUND, d.soundOn),
+ volume = com.coucou.android.sound.SoundVolume.clamp(store.getFloat(VOLUME, d.volume)),
+ notifyDone = store.getBoolean(DONE, d.notifyDone),
+ quiet = QuietHours(
+ store.getBoolean(Q_ON, d.quiet.enabled),
+ QuietHours.wrap(store.getInt(Q_FROM, d.quiet.fromMin)),
+ QuietHours.wrap(store.getInt(Q_TO, d.quiet.toMin)),
+ ),
+ outfit = com.coucou.android.mochi.outfit.Wardrobe.parseLocal(store.getString(OUTFIT, d.outfit)),
+ useRelay = store.getBoolean(RELAY, d.useRelay),
+ )
+ }
+
+ fun save(store: KeyValueStore, s: UserSettings) {
+ store.put(SOUND, s.soundOn)
+ store.put(VOLUME, com.coucou.android.sound.SoundVolume.clamp(s.volume))
+ store.put(DONE, s.notifyDone)
+ store.put(Q_ON, s.quiet.enabled)
+ store.put(Q_FROM, QuietHours.wrap(s.quiet.fromMin))
+ store.put(Q_TO, QuietHours.wrap(s.quiet.toMin))
+ store.put(OUTFIT, com.coucou.android.mochi.outfit.Wardrobe.parseLocal(s.outfit))
+ store.put(RELAY, s.useRelay)
+ }
+ }
+}
+
+/** What to do when a session changes state while the app may be in the background. */
+data class Announce(val sound: Boolean, val notify: Boolean, val pill: Boolean) {
+ companion object { val NONE = Announce(sound = false, notify = false, pill = false) }
+}
+
+object StatusPolicy {
+ /** Finished, failed and rate limited are "news"; a question is more: it is waiting for the user. */
+ private val NEWS = setOf(BotState.FINISHED, BotState.ERROR, BotState.RATELIMIT)
+
+ /**
+ * Only a change into one of those states counts, never the first picture after connecting
+ * (previous == null), so sessions that ended long ago stay quiet.
+ *
+ * - The switch "when an agent finishes or fails" governs finished / failed / rate limited.
+ * - Quiet hours silence those too (no sound, no pill) but the notice stays in the shade.
+ * A question is never silenced: like a permission request it needs the user.
+ * - Inside Coucou the screen already shows everything: no notification, no pill. The sound stays.
+ * - The notification is always posted quietly (shade only): the sound is Mochi's own and the pill
+ * is the on-screen alert, so nothing overlaps or rings twice.
+ */
+ fun announce(previous: BotState?, now: BotState, s: UserSettings, minuteOfDay: Int, appInForeground: Boolean): Announce {
+ if (previous == null || previous == now) return Announce.NONE
+ val question = now == BotState.QUESTION
+ if (!question && now !in NEWS) return Announce.NONE
+ if (!question && !s.notifyDone) return Announce.NONE
+ val quiet = !question && s.quiet.isQuiet(minuteOfDay)
+ return Announce(
+ sound = s.soundOn && !quiet,
+ notify = !appInForeground,
+ pill = !appInForeground && !quiet,
+ )
+ }
+
+ /** The approval sound and the like for a change into approval; unchanged behaviour, minus the first picture. */
+ fun stateSoundWanted(previous: BotState?, now: BotState, s: UserSettings): Boolean =
+ s.soundOn && previous != null && previous != now && now == BotState.APPROVAL
+}
+
+/** One decision made on this phone. Kept only on this phone. */
+data class Decision(val agent: String, val tool: String, val command: String, val allowed: Boolean, val atMs: Long)
+
+/** The phone's own list of decisions, newest first, at most 50. */
+class DecisionLog(private val store: KeyValueStore, private val key: String = "decisions") {
+ fun all(): List<Decision> {
+ val raw = store.getString(key, "")
+ if (raw.isEmpty()) return emptyList()
+ return raw.split(ROW).mapNotNull { row ->
+ val f = row.split(COL)
+ if (f.size != 5) return@mapNotNull null
+ val at = f[4].toLongOrNull() ?: return@mapNotNull null
+ Decision(f[0], f[1], f[2], f[3] == "1", at)
+ }
+ }
+
+ fun add(d: Decision) {
+ val list = listOf(clean(d)) + all()
+ store.put(key, list.take(MAX).joinToString(ROW) { listOf(it.agent, it.tool, it.command, if (it.allowed) "1" else "0", it.atMs).joinToString(COL) })
+ }
+
+ fun clear() = store.put(key, "")
+
+ private fun clean(d: Decision) = d.copy(
+ agent = strip(d.agent).take(64), tool = strip(d.tool).take(64), command = strip(d.command).take(COMMAND_MAX),
+ )
+
+ private fun strip(s: String) = s.replace(ROW, " ").replace(COL, " ")
+
+ companion object {
+ const val MAX = 50
+ /** Only the start of a command is kept: a long one could carry something private. */
+ const val COMMAND_MAX = 120
+ private const val ROW = "\u001E"
+ private const val COL = "\u001F"
+ }
+}
+
+/** Days for the history list. */
+object HistoryDays {
+ enum class Day { TODAY, YESTERDAY, OTHER }
+
+ fun classify(atMs: Long, nowMs: Long, zone: ZoneId): Pair<Day, LocalDate> {
+ val date = Instant.ofEpochMilli(atMs).atZone(zone).toLocalDate()
+ val today = Instant.ofEpochMilli(nowMs).atZone(zone).toLocalDate()
+ return when (date) {
+ today -> Day.TODAY to date
+ today.minusDays(1) -> Day.YESTERDAY to date
+ else -> Day.OTHER to date
+ }
+ }
+
+ /** Consecutive decisions of the same day grouped together, keeping the newest-first order. */
+ fun group(list: List<Decision>, nowMs: Long, zone: ZoneId): List<Pair<Pair<Day, LocalDate>, List<Decision>>> {
+ val out = ArrayList<Pair<Pair<Day, LocalDate>, MutableList<Decision>>>()
+ for (d in list) {
+ val key = classify(d.atMs, nowMs, zone)
+ if (out.isNotEmpty() && out.last().first.second == key.second) out.last().second.add(d)
+ else out.add(key to mutableListOf(d))
+ }
+ return out
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/ApprovalBook.kt b/android/app/src/main/kotlin/com/coucou/android/link/ApprovalBook.kt
new file mode 100644
index 00000000..28b66081
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/ApprovalBook.kt
@@ -0,0 +1,43 @@
+package com.coucou.android.link
+
+/**
+ * Pending approvals as the phone sees them. A decision can only be sent for a request that is
+ * still pending and younger than [Protocol.APPROVAL_TTL_MS]; each request is decided once.
+ *
+ * The age is counted from the moment the request ARRIVED, on this phone's own clock. The
+ * desktop's `createdAt` is not used for it: a computer whose clock is a few minutes off would
+ * otherwise make every request look expired (or immortal) on the phone.
+ */
+class ApprovalBook(private val clockMs: () -> Long) {
+ private class Entry(val request: ApprovalRequest, val arrivedMs: Long)
+
+ private val pending = LinkedHashMap<String, Entry>()
+
+ @Synchronized fun add(r: ApprovalRequest) {
+ // The same request sent again (a reconnect) keeps its first arrival time.
+ pending.getOrPut(r.fingerprint) { Entry(r, clockMs()) }
+ }
+
+ @Synchronized fun resolve(fingerprint: String): ApprovalRequest? = pending.remove(fingerprint)?.request
+
+ /** Still-valid requests, oldest first. Expired ones are dropped as a side effect. */
+ @Synchronized fun active(): List<ApprovalRequest> {
+ val now = clockMs()
+ pending.values.removeAll { now - it.arrivedMs >= Protocol.APPROVAL_TTL_MS }
+ return pending.values.map { it.request }
+ }
+
+ /** Takes the request out for deciding; null if unknown, already decided or expired. */
+ @Synchronized fun claim(fingerprint: String): ApprovalRequest? {
+ active()
+ return pending.remove(fingerprint)?.request
+ }
+
+ /** Puts a claimed request back (the decision could not be sent) with its remaining time. */
+ @Synchronized fun restore(r: ApprovalRequest, arrivedMs: Long) { pending[r.fingerprint] = Entry(r, arrivedMs) }
+
+ /** How long ago it arrived, or null if it is not pending. */
+ @Synchronized fun ageMs(fingerprint: String): Long? = pending[fingerprint]?.let { clockMs() - it.arrivedMs }
+
+ @Synchronized fun clear() = pending.clear()
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/DemoLink.kt b/android/app/src/main/kotlin/com/coucou/android/link/DemoLink.kt
new file mode 100644
index 00000000..16d4c0ab
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/DemoLink.kt
@@ -0,0 +1,94 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.BotState
+
+/**
+ * Offline demo of the desktop link: a few fake sessions and one approval, so the app can be
+ * tried (and tested) without a desktop. It never opens a socket, and a "decision" made here
+ * only changes the demo; nothing is sent anywhere.
+ */
+class DemoLink(
+ private val listener: LinkListener,
+ private val clockMs: () -> Long = System::currentTimeMillis,
+ /** Pause between script steps; tests pass 0 and call [step] themselves. */
+ private val stepDelayMs: Long = 2_500,
+ private val autoRun: Boolean = true,
+) : DesktopLink {
+ override val approvals = ApprovalBook(clockMs)
+
+ @Volatile private var running = false
+ @Volatile private var thread: Thread? = null
+ private var cursor = 0
+
+ companion object {
+ const val SESSION_ID = "demo_session"
+ const val TOOL = "Bash"
+ const val COMMAND = "npm run build"
+ val FINGERPRINT: String = Fingerprint.of("integration_claude", SESSION_ID, TOOL, COMMAND, "demo")
+ const val STEPS = 8
+ }
+
+ private fun session(pill: String, agent: String, state: BotState, text: String, i: Int, n: Int) =
+ SessionInfo(pill, agent, state, text, i, n, clockMs())
+
+ @Synchronized override fun start() {
+ if (running) return
+ running = true
+ listener.onState(LinkState.CONNECTED)
+ listener.onWelcome("Demo", "demo")
+ if (autoRun) thread = Thread({
+ try {
+ while (running) { step(); Thread.sleep(stepDelayMs) }
+ } catch (_: InterruptedException) { }
+ }, "coucou-demo").apply { isDaemon = true; start() }
+ }
+
+ @Synchronized override fun stop() {
+ running = false
+ thread?.interrupt()
+ thread = null
+ approvals.clear()
+ listener.onState(LinkState.DISCONNECTED)
+ }
+
+ /** Advances the script by one step; loops forever. Public so tests can drive it. */
+ @Synchronized fun step() {
+ when (cursor % STEPS) {
+ 0 -> listener.onSessions(listOf(session("integration_claude", "Claude Code", BotState.THINKING, "Reading the project", 1, 6)))
+ 1 -> listener.onSessions(listOf(
+ session("integration_claude", "Claude Code", BotState.WORKING, "Editing files", 2, 6),
+ session("agent_codex", "Codex", BotState.SEARCHING, "Searching the code", 1, 4),
+ ))
+ 2 -> {
+ val r = ApprovalRequest("integration_claude", FINGERPRINT, TOOL, COMMAND, clockMs())
+ approvals.add(r)
+ listener.onSessions(listOf(
+ session("integration_claude", "Claude Code", BotState.APPROVAL, "Waiting for your approval", 3, 6),
+ session("agent_codex", "Codex", BotState.WORKING, "Running tests", 2, 4),
+ ))
+ listener.onApproval(r)
+ }
+ 3 -> listener.onSessions(listOf(
+ session("integration_claude", "Claude Code", BotState.WORKING, "Building", 4, 6),
+ session("agent_codex", "Codex", BotState.QUESTION, "Which branch?", 3, 4),
+ ))
+ 4 -> listener.onSessions(listOf(
+ session("integration_claude", "Claude Code", BotState.FINISHED, "Done", 6, 6),
+ session("agent_codex", "Codex", BotState.ERROR, "Tests failed", 3, 4),
+ ))
+ 5 -> listener.onSessions(listOf(session("agent_codex", "Codex", BotState.RATELIMIT, "Rate limited", 3, 4)))
+ 6 -> listener.onSessions(listOf(session("agent_gemini", "Gemini CLI", BotState.SLEEPING, "Idle", 0, 0)))
+ else -> {
+ if (approvals.resolve(FINGERPRINT) != null) listener.onApprovalResolved(FINGERPRINT)
+ listener.onSessions(emptyList())
+ }
+ }
+ cursor++
+ }
+
+ override fun decide(fingerprint: String, allow: Boolean): Boolean {
+ val r = approvals.claim(fingerprint) ?: return false
+ listener.onApprovalResolved(r.fingerprint)
+ return true
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Diagnostics.kt b/android/app/src/main/kotlin/com/coucou/android/link/Diagnostics.kt
new file mode 100644
index 00000000..d3bb1634
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Diagnostics.kt
@@ -0,0 +1,211 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.net.HttpURLConnection
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.net.SocketTimeoutException
+import java.net.URL
+import javax.net.ssl.SSLException
+
+/** The questions "Can't connect?" asks, in the order that makes each answer meaningful. */
+enum class DiagStep(val title: String) {
+ NETWORK("Phone network"),
+ ADDRESS("Saved address answers"),
+ DISCOVERY("Computer announces itself"),
+ SECURE("Secure connection (pinned certificate)"),
+ TOKEN("Pairing code and version"),
+ RELAY("Relay"),
+}
+
+sealed class DiagResult {
+ /** [detail] says what was seen in a few words. */
+ data class Ok(val detail: String) : DiagResult()
+ /** [problem] is what is wrong; [hint] is what to try, calmly. */
+ data class Problem(val problem: String, val hint: String) : DiagResult()
+ /** Not asked, because a step before it already failed. */
+ data class Skipped(val why: String) : DiagResult()
+}
+
+/** What the checks need from the phone; the real one is [LanDiagnostics], tests use fakes. */
+interface DiagEnv {
+ fun network(): DiagResult
+ fun address(): DiagResult
+ fun discovery(): DiagResult
+ fun secure(): DiagResult
+ fun token(): DiagResult
+ /** Null when the pairing has no relay. */
+ fun relay(): DiagResult?
+}
+
+object Diagnostics {
+ /** Runs every check, reporting each as it finishes. A step whose premise failed is skipped, not guessed. */
+ fun run(env: DiagEnv, onResult: (DiagStep, DiagResult) -> Unit = { _, _ -> }): List<Pair<DiagStep, DiagResult>> {
+ val out = ArrayList<Pair<DiagStep, DiagResult>>()
+ fun put(step: DiagStep, r: DiagResult) { out += step to r; onResult(step, r) }
+ fun failed(step: DiagStep) = out.any { it.first == step && it.second !is DiagResult.Ok }
+
+ put(DiagStep.NETWORK, safe { env.network() })
+ put(DiagStep.ADDRESS, if (failed(DiagStep.NETWORK)) DiagResult.Skipped("Needs the Wi-Fi") else safe { env.address() })
+ put(DiagStep.DISCOVERY, if (failed(DiagStep.NETWORK)) DiagResult.Skipped("Needs the Wi-Fi") else safe { env.discovery() })
+ put(DiagStep.SECURE, if (failed(DiagStep.ADDRESS)) DiagResult.Skipped("Needs the address to answer") else safe { env.secure() })
+ put(DiagStep.TOKEN, if (failed(DiagStep.ADDRESS) || failed(DiagStep.SECURE)) DiagResult.Skipped("Needs the secure connection") else safe { env.token() })
+ try { env.relay() } catch (e: Exception) { broken(e) }?.let { put(DiagStep.RELAY, it) }
+ return out
+ }
+
+ private fun broken(e: Exception) = DiagResult.Problem("The check itself failed (${e.javaClass.simpleName})", "Try again.")
+
+ private fun safe(f: () -> DiagResult): DiagResult = try { f() } catch (e: Exception) { broken(e) }
+
+ /** "192.168.1.20" -> "192.168.x.x": enough to tell a home network from a hotspot, not enough to find a house. */
+ fun maskHost(host: String): String {
+ val parts = host.split(".")
+ return if (parts.size == 4 && parts.all { p -> p.isNotEmpty() && p.all(Char::isDigit) }) "${parts[0]}.${parts[1]}.x.x" else "a name (hidden)"
+ }
+
+ /**
+ * The report the user can copy and send. It names the checks and what they found; it never contains the pairing code,
+ * the certificate fingerprint, the computer's name, the full address or any key.
+ */
+ fun report(appVersion: String, androidVersion: String, device: String, results: List<Pair<DiagStep, DiagResult>>, hostMasked: String, via: String): String =
+ buildString {
+ appendLine("Coucou for Android $appVersion · Android $androidVersion · $device")
+ appendLine("Computer: $hostMasked · connected via: $via")
+ for ((step, r) in results) {
+ appendLine(
+ when (r) {
+ is DiagResult.Ok -> "OK ${step.title}: ${r.detail}"
+ is DiagResult.Problem -> "PROBLEM ${step.title}: ${r.problem}"
+ is DiagResult.Skipped -> "SKIPPED ${step.title}: ${r.why}"
+ },
+ )
+ }
+ }.trimEnd()
+}
+
+/**
+ * The real checks against one pairing. Plain JVM except what the phone supplies: whether Wi-Fi is up, and a way to look the computer
+ * up on the network ([discover]). The pairing code is used only to say hello, as the app does; it is never put in a result.
+ */
+class LanDiagnostics(
+ private val p: PairingPayload,
+ private val wifiUp: () -> Boolean,
+ private val onCellular: () -> Boolean,
+ private val discover: () -> List<Found>,
+ private val connector: Connector = PinnedTls.connector(p),
+ private val relayCheck: (() -> DiagResult)? = null,
+ private val timeoutMs: Int = 3_000,
+) : DiagEnv {
+ override fun network(): DiagResult = when {
+ wifiUp() -> DiagResult.Ok("Wi-Fi is connected")
+ p.relay != null && onCellular() -> DiagResult.Ok("Mobile data (the relay can be used; the direct link needs the home Wi-Fi)")
+ else -> DiagResult.Problem("The phone is not on a Wi-Fi network", "Join the same Wi-Fi as your computer, or turn on Away from home Wi-Fi to use the relay.")
+ }
+
+ override fun address(): DiagResult {
+ val started = System.nanoTime()
+ val s = Socket()
+ return try {
+ s.connect(InetSocketAddress(p.host, p.port), timeoutMs)
+ DiagResult.Ok("Answers in ${(System.nanoTime() - started) / 1_000_000} ms at ${Diagnostics.maskHost(p.host)}")
+ } catch (_: SocketTimeoutException) {
+ DiagResult.Problem(
+ "No answer from ${Diagnostics.maskHost(p.host)}",
+ "Is the computer on and Coucou running with the Phone link switched on? Same Wi-Fi? A guest network or client isolation blocks it.",
+ )
+ } catch (_: IOException) {
+ DiagResult.Problem("Cannot reach ${Diagnostics.maskHost(p.host)}", "The computer may have a new address: see the next line, or type the address in Home.")
+ } finally {
+ runCatching { s.close() }
+ }
+ }
+
+ override fun discovery(): DiagResult {
+ val found = Discovery.candidates(discover(), p)
+ return when {
+ found.isEmpty() -> DiagResult.Problem(
+ "The computer is not announcing itself here",
+ "Some networks block this. If the saved address answers, you can ignore it; otherwise type the address in Home.",
+ )
+ found.any { it.host == p.host && it.port == p.port } -> DiagResult.Ok("Found, same address as the saved one")
+ else -> DiagResult.Problem("Found at ${Diagnostics.maskHost(found.first().host)}, not at the saved address", "Open Home: the phone updates the address by itself when it is not connected.")
+ }
+ }
+
+ override fun secure(): DiagResult = try {
+ connector.connect(timeoutMs).close()
+ DiagResult.Ok("The computer's certificate is the one you paired with")
+ } catch (e: SSLException) {
+ if (generateSequence<Throwable>(e) { it.cause }.any { it is java.security.cert.CertificateException }) {
+ DiagResult.Problem("This is not the computer you paired with (its certificate differs)", "Coucou may have been reinstalled, or this is another computer. Pair again.")
+ } else {
+ DiagResult.Problem("The secure handshake failed", "Try again. If it keeps failing, pair again.")
+ }
+ } catch (_: IOException) {
+ DiagResult.Problem("The secure connection could not be opened", "The address answers but nothing speaks Coucou there. Is the Phone link switched on?")
+ }
+
+ override fun token(): DiagResult {
+ val s = try {
+ connector.connect(timeoutMs)
+ } catch (_: IOException) {
+ return DiagResult.Problem("Could not connect to say hello", "See the lines above.")
+ }
+ return try {
+ s.soTimeout = 5_000
+ s.getOutputStream().apply { write((Wire.encode(ClientMsg.Hello(Protocol.VERSION, p.token, "Diagnostics", emptyList())) + "\n").toByteArray()); flush() }
+ val line = readLine(s) ?: return DiagResult.Problem("The computer closed the connection at once", "Try again.")
+ when (val m = Wire.decodeServer(line)) {
+ is ServerMsg.Welcome ->
+ if (m.version == Protocol.VERSION) DiagResult.Ok("Pairing code accepted, protocol version ${m.version}")
+ else DiagResult.Problem("The computer speaks version ${m.version}, this app speaks ${Protocol.VERSION}", "Update Coucou on the computer or the app.")
+ is ServerMsg.Error ->
+ if (m.code == "auth") DiagResult.Problem("The pairing code was refused", "The computer made a new code (Pair again). Scan its new code.")
+ else DiagResult.Problem("The computer answered with an error (${m.code})", "Try again.")
+ else -> DiagResult.Problem("An unexpected answer to hello", "Update Coucou on the computer and the app.")
+ }
+ } catch (_: SocketTimeoutException) {
+ DiagResult.Problem("No answer to hello", "The computer is busy or asleep. Try again.")
+ } catch (_: IOException) {
+ DiagResult.Problem("The connection broke while saying hello", "Try again.")
+ } finally {
+ runCatching { s.getOutputStream().apply { write((Wire.encode(ClientMsg.Bye) + "\n").toByteArray()); flush() } }
+ runCatching { s.close() }
+ }
+ }
+
+ override fun relay(): DiagResult? = relayCheck?.invoke()
+
+ private fun readLine(s: Socket): String? {
+ val b = java.io.ByteArrayOutputStream()
+ while (b.size() < Protocol.MAX_LINE_BYTES) {
+ val x = s.getInputStream().read()
+ if (x < 0) return null
+ if (x == '\n'.code) return b.toString("UTF-8")
+ b.write(x)
+ }
+ return null
+ }
+
+ companion object {
+ /**
+ * The relay answers `GET /` with "Coucou link relay" without a key and without touching any room, so this check can never
+ * replace the phone's live connection (joining a room as the phone would).
+ */
+ fun relayReachable(relay: RelayPairing, timeoutMs: Int = 5_000): DiagResult {
+ val url = relay.relayUrl() ?: return DiagResult.Problem("The relay address in the pairing is not valid", "Pair again.")
+ return try {
+ val conn = URL("${if (url.tls) "https" else "http"}://${url.host}:${url.port}/").openConnection() as HttpURLConnection
+ conn.connectTimeout = timeoutMs
+ conn.readTimeout = timeoutMs
+ conn.instanceFollowRedirects = false
+ val body = try { conn.inputStream.bufferedReader().readText().take(64) } finally { conn.disconnect() }
+ if (conn.responseCode == 200 && body.startsWith("Coucou link relay")) DiagResult.Ok("The relay at ${url.host} answers")
+ else DiagResult.Problem("${url.host} answers but is not a Coucou relay", "Check the address on the computer (Away from home Wi-Fi).")
+ } catch (_: IOException) {
+ DiagResult.Problem("Cannot reach the relay at ${url.host}", "Check your internet connection and the relay's address.")
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Discovery.kt b/android/app/src/main/kotlin/com/coucou/android/link/Discovery.kt
new file mode 100644
index 00000000..b25319e5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Discovery.kt
@@ -0,0 +1,250 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.security.SecureRandom
+import javax.net.ssl.SSLContext
+
+/**
+ * Finding the paired computer again when its address changed (another Wi-Fi, a hotspot). The computer announces
+ * `_coucou._tcp` on the local network while its phone link is on (docs/ANDROID_LINK.md, "Finding the computer").
+ *
+ * The announcement is a hint, never a credential: it carries the protocol version and the first 16 hex characters of the
+ * certificate's SHA-256. The phone matches on that id, then checks the **full** pinned certificate with a bare TLS
+ * handshake (no token is sent) before it saves the new address. A lookalike cannot get the token.
+ */
+
+/** A computer seen on the local network. */
+data class Found(val name: String, val host: String, val port: Int, val fingerprintId: String?, val version: String?)
+
+enum class DiscoveryState { IDLE, LOOKING, NOT_FOUND }
+
+enum class ProbeResult { MATCH, PIN_MISMATCH, UNREACHABLE }
+
+/**
+ * Checks that [host]:[port] presents the pinned certificate, by TLS handshake only. It takes no token on purpose:
+ * nothing secret can be sent, whatever answers.
+ */
+fun interface Probe { fun check(host: String, port: Int, certSha256: String): ProbeResult }
+
+/** Where services come from: the system's NsdManager in the app, a fake in tests. */
+interface DiscoverySource {
+ fun start(onFound: (Found) -> Unit)
+ fun stop()
+}
+
+object Discovery {
+ const val SERVICE_TYPE = "_coucou._tcp"
+ const val FP_ID_LEN = 16
+ const val TXT_VERSION = "1"
+ const val DEFAULT_PORT = 47821
+
+ /** The short id of a certificate fingerprint (first 16 lowercase hex), or null if it is not hex. */
+ fun fingerprintId(sha256Hex: String): String? {
+ val f = sha256Hex.trim().lowercase()
+ if (f.length < FP_ID_LEN || !f.all { it in '0'..'9' || it in 'a'..'f' }) return null
+ return f.substring(0, FP_ID_LEN)
+ }
+
+ /** The only rule for "this is my computer": same fingerprint id, and a protocol version we speak. Name and address never count. */
+ fun matches(f: Found, p: PairingPayload): Boolean {
+ val mine = fingerprintId(p.certSha256) ?: return false
+ val theirs = f.fingerprintId?.trim()?.lowercase() ?: return false
+ return theirs == mine && (f.version == null || f.version == TXT_VERSION)
+ }
+
+ /** An IPv4 literal on the local network: private, link-local or loopback. The computer refuses every other peer too. */
+ fun isLocalHost(host: String): Boolean {
+ val o = ipv4(host) ?: return false
+ return o[0] == 10 || (o[0] == 172 && o[1] in 16..31) || (o[0] == 192 && o[1] == 168) ||
+ (o[0] == 169 && o[1] == 254) || o[0] == 127 || (o[0] == 100 && o[1] in 64..127)
+ }
+
+ private fun ipv4(host: String): IntArray? {
+ val parts = host.split(".")
+ if (parts.size != 4) return null
+ val n = parts.map { it.takeIf { s -> s.isNotEmpty() && s.length <= 3 && s.all(Char::isDigit) }?.toInt() ?: return null }
+ return if (n.all { it in 0..255 }) n.toIntArray() else null
+ }
+
+ /** The services worth checking, in the order they were seen: matching, on the local network, no duplicate address. */
+ fun candidates(seen: List<Found>, p: PairingPayload): List<Found> =
+ seen.filter { matches(it, p) && isLocalHost(it.host) && it.port in 1..65535 }.distinctBy { it.host to it.port }
+
+ /** The pairing with a new address. The token and the pinned fingerprint are the same objects, untouched. */
+ fun withAddress(p: PairingPayload, host: String, port: Int): PairingPayload = p.copy(host = host, port = port)
+
+ /** "192.168.1.20", "192.168.1.20:47821" or "my-pc.local:47821"; the port defaults to 47821. Null if it cannot be an address. */
+ fun parseAddress(text: String): Pair<String, Int>? {
+ val t = text.trim()
+ if (t.isEmpty() || t.any { it.isWhitespace() } || t.contains("/") || t.contains("@") || t.contains("[")) return null
+ val colon = t.lastIndexOf(':')
+ val host = if (colon >= 0) t.substring(0, colon) else t
+ val port = if (colon >= 0) t.substring(colon + 1).takeIf { it.isNotEmpty() && it.length <= 5 && it.all(Char::isDigit) }?.toInt() ?: return null else DEFAULT_PORT
+ if (port !in 1..65535 || host.isEmpty() || host.contains(":")) return null
+ val looksNumeric = host.all { it.isDigit() || it == '.' }
+ val ok = if (looksNumeric) ipv4(host) != null else host.length <= 253 && host.split(".").all { label ->
+ label.isNotEmpty() && label.length <= 63 && label.all { it.isLetterOrDigit() || it == '-' } && !label.startsWith("-") && !label.endsWith("-")
+ }
+ return if (ok) host to port else null
+ }
+}
+
+/** When and how long to look. Pure numbers, so the battery rules are tests. */
+object DiscoveryPolicy {
+ /** The saved address is tried first and given this long to answer (TCP connect). */
+ const val SAVED_CONNECT_TIMEOUT_MS = 2_000
+ /** The saved address must fail this many times in a row before the network is searched. */
+ const val FAILURES_BEFORE_DISCOVERY = 1
+ /** One search lasts this long. If nothing is found the calm hint appears. */
+ const val WINDOW_MS = 15_000L
+ /** Wait before search number n (0 = right away). It never gets faster, and never slower than 5 minutes. */
+ private val ROUND_DELAYS_MS = longArrayOf(0, 20_000, 60_000, 180_000, 300_000)
+
+ fun delayBeforeRound(round: Int): Long = ROUND_DELAYS_MS[round.coerceIn(0, ROUND_DELAYS_MS.size - 1)]
+
+ /** Searching costs battery: only when there is a computer to find, on a Wi-Fi (or cable), and the link is not up. */
+ fun mayDiscover(paired: Boolean, demo: Boolean, wifiUp: Boolean, linkConnected: Boolean): Boolean =
+ paired && !demo && wifiUp && !linkConnected
+}
+
+fun interface Cancelable { fun cancel() }
+
+fun interface Scheduler { fun after(delayMs: Long, task: () -> Unit): Cancelable }
+
+fun interface Runner { fun run(task: () -> Unit) }
+
+/**
+ * One search at a time: browse for the service, check each matching one with the [Probe], and hand the first that
+ * passes to [onAddress]. After a search that finds nothing it waits longer and longer before the next. All state
+ * changes happen under one lock; probes run on [runner], never on the browsing callback's thread.
+ */
+class AddressFinder(
+ private val source: DiscoverySource,
+ private val probe: Probe,
+ private val pairing: () -> PairingPayload?,
+ private val allowed: () -> Boolean,
+ private val onAddress: (host: String, port: Int) -> Unit,
+ private val onState: (DiscoveryState) -> Unit,
+ private val scheduler: Scheduler,
+ private val runner: Runner,
+) {
+ private val lock = Any()
+ private var state = DiscoveryState.IDLE
+ private var round = 0
+ private var window: Cancelable? = null
+ private var waiting: Cancelable? = null
+ private val seen = HashSet<String>()
+ /** Addresses whose certificate did not match this search: dropped, never tried again until the next search. */
+ private val rejected = HashSet<String>()
+
+ val current: DiscoveryState get() = synchronized(lock) { state }
+
+ /** Starts a search unless one is running or the next is already scheduled. */
+ fun request() {
+ synchronized(lock) {
+ if (state == DiscoveryState.LOOKING || waiting != null) return
+ beginRound()
+ }
+ }
+
+ /** The network changed: forget the waiting, search now. */
+ fun networkChanged() {
+ synchronized(lock) {
+ waiting?.cancel(); waiting = null
+ if (state == DiscoveryState.LOOKING) return
+ round = 0
+ beginRound()
+ }
+ }
+
+ /** The link is up: nothing more to find. */
+ fun connected() { synchronized(lock) { halt() } }
+
+ fun stop() { synchronized(lock) { halt() } }
+
+ private fun halt() {
+ window?.cancel(); window = null
+ waiting?.cancel(); waiting = null
+ runCatching { source.stop() }
+ round = 0
+ setState(DiscoveryState.IDLE)
+ }
+
+ private fun beginRound() {
+ if (!allowed() || pairing() == null) { setState(DiscoveryState.IDLE); return }
+ seen.clear(); rejected.clear()
+ setState(DiscoveryState.LOOKING)
+ window = scheduler.after(DiscoveryPolicy.WINDOW_MS) { endRound() }
+ source.start { f -> runner.run { handle(f) } }
+ }
+
+ private fun endRound() {
+ synchronized(lock) {
+ if (state != DiscoveryState.LOOKING) return
+ window = null
+ runCatching { source.stop() }
+ setState(DiscoveryState.NOT_FOUND)
+ round++
+ waiting = scheduler.after(DiscoveryPolicy.delayBeforeRound(round)) {
+ synchronized(lock) { waiting = null; if (state == DiscoveryState.NOT_FOUND) beginRound() }
+ }
+ }
+ }
+
+ private fun handle(f: Found) {
+ val p: PairingPayload
+ val key = "${f.host}:${f.port}"
+ synchronized(lock) {
+ if (state != DiscoveryState.LOOKING) return
+ p = pairing() ?: return
+ if (Discovery.candidates(listOf(f), p).isEmpty() || key in rejected || !seen.add(key)) return
+ }
+ // The check is a network handshake: outside the lock. It carries no token.
+ val result = try { probe.check(f.host, f.port, p.certSha256) } catch (_: Exception) { ProbeResult.UNREACHABLE }
+ synchronized(lock) {
+ if (state != DiscoveryState.LOOKING) return
+ when (result) {
+ ProbeResult.MATCH -> {
+ window?.cancel(); window = null
+ runCatching { source.stop() }
+ round = 0
+ setState(DiscoveryState.IDLE)
+ onAddress(f.host, f.port)
+ }
+ ProbeResult.PIN_MISMATCH -> rejected.add(key) // a lookalike: dropped
+ ProbeResult.UNREACHABLE -> seen.remove(key) // may be announced again
+ }
+ }
+ }
+
+ private fun setState(s: DiscoveryState) {
+ if (state == s) return
+ state = s
+ onState(s)
+ }
+}
+
+/** The real [Probe]: a TLS handshake against the pinned certificate, then close. The token is never involved. */
+object PinnedProbe : Probe {
+ override fun check(host: String, port: Int, certSha256: String): ProbeResult {
+ val ctx = SSLContext.getInstance("TLS").apply { init(null, arrayOf(PinnedTrustManager(certSha256)), SecureRandom()) }
+ val raw = Socket()
+ return try {
+ raw.connect(InetSocketAddress(host, port), 2_000)
+ val tls = ctx.socketFactory.createSocket(raw, host, port, true) as javax.net.ssl.SSLSocket
+ tls.enabledProtocols = tls.supportedProtocols.filter { it == "TLSv1.3" || it == "TLSv1.2" }.toTypedArray()
+ tls.soTimeout = 5_000
+ tls.startHandshake()
+ ProbeResult.MATCH
+ } catch (e: javax.net.ssl.SSLException) {
+ if (generateSequence<Throwable>(e) { it.cause }.any { it is java.security.cert.CertificateException }) ProbeResult.PIN_MISMATCH
+ else ProbeResult.UNREACHABLE
+ } catch (_: IOException) {
+ ProbeResult.UNREACHABLE
+ } finally {
+ runCatching { raw.close() }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/LinkClient.kt b/android/app/src/main/kotlin/com/coucou/android/link/LinkClient.kt
new file mode 100644
index 00000000..444e9ee7
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/LinkClient.kt
@@ -0,0 +1,380 @@
+package com.coucou.android.link
+
+import java.io.BufferedInputStream
+import java.io.ByteArrayOutputStream
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.security.SecureRandom
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+import javax.net.ssl.SSLContext
+
+enum class LinkState { DISCONNECTED, CONNECTING, CONNECTED }
+
+/** Why a link that had been working ended, as far as the phone can tell. */
+enum class LostReason {
+ /** Nothing came back: the read timed out or a liveness check got no answer (typical after the phone slept). */
+ SILENT,
+ /** The computer closed the connection (it restarted, or dropped a connection that had been silent for too long). */
+ CLOSED,
+ /** The network under it failed (reset, unreachable, Wi-Fi changed). */
+ NETWORK,
+}
+
+interface LinkListener {
+ fun onState(state: LinkState) {}
+ fun onWelcome(desktopName: String, os: String) {}
+ /** The optional features this computer offers right now (after the welcome). */
+ fun onCaps(caps: Set<String>) {}
+ fun onSessions(sessions: List<SessionInfo>) {}
+ fun onApproval(request: ApprovalRequest) {}
+ fun onApprovalResolved(fingerprint: String) {}
+ /** A question to answer (only with the `answers` capability). It is removed by [onApprovalResolved] with the same fingerprint. */
+ fun onQuestion(request: QuestionRequest) {}
+ /** What Mochi wears on the computer: "auto" or an outfit (only with the `prefs` capability). */
+ fun onPrefs(outfit: String) {}
+ /** A part of a file's diff the phone asked for (only with the `diffs` capability). */
+ fun onDiff(part: ServerMsg.Diff) {}
+ /** The plan usage (only with the `usage` capability); both plans null: nothing to show any more. */
+ fun onUsage(usage: UsageSnapshot) {}
+ /** The service cards (only with the `services` capability); an empty list: none to show any more. */
+ fun onServices(cards: List<ServiceCard>) {}
+ /** The relay's access key was replaced on the computer (only with the `relay` capability). */
+ fun onRelayAccess(access: String) {}
+ fun onError(code: String, message: String) {}
+ /** A connection attempt failed before the computer answered; [consecutive] counts the failures in a row (1 for the first). */
+ fun onConnectFailed(consecutive: Int) {}
+ /** A link that had been working ended without the user asking for it (not for a wrong token or version: see [onError]). */
+ fun onLinkLost(reason: LostReason) {}
+ fun onChatModels(models: List<ChatModel>) {}
+ fun onChatDelta(id: String, text: String) {}
+ fun onChatDone(id: String, text: String?) {}
+ fun onChatError(id: String, reason: String, message: String) {}
+}
+
+/** What the UI talks to: the real [LinkClient] or the offline [DemoLink]. */
+interface DesktopLink {
+ val approvals: ApprovalBook
+ fun start()
+ fun stop()
+ /** Try the connection again now (the network changed); the demo has nothing to retry. */
+ fun retryNow() {}
+ /**
+ * Is the link alive right now? Connected: asks the computer for a pong and drops the connection (so it reconnects) if none
+ * comes in time. Not connected: reconnects at once. Called when the screen turns on, when a network appears, and by the alarm.
+ */
+ fun checkNow() {}
+ /** allow/deny for a pending approval; false if unknown, expired, already decided or not connected. */
+ fun decide(fingerprint: String, allow: Boolean): Boolean
+
+ /** Sends the picks for a question; false if the link is down or the computer did not offer `answers`. */
+ fun answer(fingerprint: String, picks: List<List<String>>): Boolean = false
+
+ /** Asks for the lines of a file in a session's list; false if the link is down or the computer did not offer `diffs`. */
+ fun getDiff(pillId: String, fileId: Long): Boolean = false
+
+ // Chat through the computer (docs/ANDROID_LINK.md). Not offered by the demo.
+ fun chatModels() {}
+ /** False if the link is down; the answer arrives through the listener. */
+ fun chatSend(id: String, model: String, text: String): Boolean = false
+ fun chatCancel(id: String) {}
+ fun chatReset() {}
+}
+
+/** Opens the (TLS) connection to the desktop. Swappable so tests can use plain sockets. */
+fun interface Connector { fun connect(timeoutMs: Int): Socket }
+
+object PinnedTls {
+ private const val HANDSHAKE_TIMEOUT_MS = 10_000
+
+ fun connector(p: PairingPayload) = Connector { timeoutMs ->
+ val ctx = SSLContext.getInstance("TLS").apply {
+ init(null, arrayOf(PinnedTrustManager(p.certSha256)), SecureRandom())
+ }
+ val raw = Socket()
+ raw.connect(InetSocketAddress(p.host, p.port), timeoutMs)
+ val tls = ctx.socketFactory.createSocket(raw, p.host, p.port, true) as javax.net.ssl.SSLSocket
+ tls.enabledProtocols = tls.supportedProtocols.filter { it == "TLSv1.3" || it == "TLSv1.2" }.toTypedArray()
+ tls.soTimeout = HANDSHAKE_TIMEOUT_MS // the TCP connect above is quick (a wrong address must fail fast); the handshake gets longer
+ tls.startHandshake()
+ tls
+ }
+}
+
+/**
+ * Background connection to one paired desktop: hello, then messages until the link drops, then
+ * reconnect with backoff. Plain threads, no coroutines, no polling: the thread blocks on the
+ * socket, so an idle link costs no CPU. Listener callbacks arrive on the link thread.
+ */
+class LinkClient(
+ private val pairing: PairingPayload,
+ private val deviceName: String,
+ private val listener: LinkListener,
+ private val connector: Connector = PinnedTls.connector(pairing),
+ private val clockMs: () -> Long = System::currentTimeMillis,
+ private val readTimeoutMs: Int = 60_000,
+ private val pingEveryMs: Long = 20_000,
+ private val backoffMs: LongArray = longArrayOf(1_000, 2_000, 4_000, 8_000, 16_000, 30_000),
+ /** The optional features asked for in the hello; empty is what an app without them sends. */
+ private val caps: List<String> = Protocol.CAPABILITIES,
+ /** How long the saved address gets to accept the connection before it counts as a failure (then the network is searched). */
+ private val connectTimeoutMs: Int = DiscoveryPolicy.SAVED_CONNECT_TIMEOUT_MS,
+ /** How long a liveness check ([checkNow]) waits for any answer before it gives the connection up. */
+ private val pongWaitMs: Long = 8_000,
+) : DesktopLink {
+ override val approvals = ApprovalBook(clockMs)
+
+ @Volatile private var running = false
+ /** Set by an auth or version error: retrying with the same pairing can never work. */
+ @Volatile private var fatal = false
+ /** The computer's welcome offered `answers` on this connection. */
+ @Volatile private var answersOffered = false
+ /** The computer's welcome offered `prefs` on this connection. */
+ @Volatile private var prefsOffered = false
+ /** The computer's welcome offered `diffs` on this connection. */
+ @Volatile private var diffsOffered = false
+ /** The computer's welcome offered `usage` on this connection. */
+ @Volatile private var usageOffered = false
+ /** The computer's welcome offered `services` on this connection. */
+ @Volatile private var servicesOffered = false
+ /** The computer's welcome offered `relay` on this connection. */
+ @Volatile private var relayOffered = false
+ @Volatile private var socket: Socket? = null
+ /** When the last line arrived (the clock of [clockMs]); a liveness check compares it with the moment it asked. */
+ @Volatile private var lastInboundMs = 0L
+ /** Set when a liveness check closed the socket itself, so the loss is reported as silence, not as a network error. */
+ @Volatile private var probeKilled = false
+ @Volatile private var out: OutputStream? = null
+ @Volatile private var thread: Thread? = null
+ private val writeLock = Any()
+ /** Released by [retryNow] to cut a backoff wait short (the network changed). */
+ private val wake = java.util.concurrent.Semaphore(0)
+ /** Android forbids network I/O on the main thread, and the UI calls decide() and stop(): writes happen here. */
+ @Volatile private var writer: ExecutorService? = null
+
+ @Synchronized override fun start() {
+ if (running) return
+ running = true
+ fatal = false
+ writer = Executors.newSingleThreadExecutor { r -> Thread(r, "coucou-link-writer").apply { isDaemon = true } }
+ thread = Thread(::loop, "coucou-link").apply { isDaemon = true; start() }
+ }
+
+ @Synchronized override fun stop() {
+ running = false
+ val s = socket
+ // Sent and closed off the caller's thread; "bye" is best effort.
+ writer?.let { w ->
+ runCatching { w.execute { runCatching { send(ClientMsg.Bye) }; runCatching { s?.close() } } }
+ w.shutdown()
+ } ?: runCatching { s?.close() }
+ writer = null
+ thread?.interrupt()
+ thread = null
+ }
+
+ /** Try again now instead of waiting out the backoff: the network changed, or a new address was found. */
+ override fun retryNow() { wake.release() }
+
+ override fun checkNow() {
+ if (!running) return
+ val s = socket
+ if (out == null || s == null) { wake.release(); return } // not connected: do not wait out the backoff
+ val asked = clockMs()
+ if (!queue(ClientMsg.Ping)) return
+ // Any line that arrives after the question proves the connection works. If none does, it is half-dead
+ // (the phone slept, the Wi-Fi changed): close it, and the loop reconnects.
+ Thread({
+ try {
+ Thread.sleep(pongWaitMs)
+ if (running && socket === s && lastInboundMs < asked) {
+ probeKilled = true
+ runCatching { s.close() }
+ }
+ } catch (_: InterruptedException) { }
+ }, "coucou-link-check").apply { isDaemon = true; start() }
+ }
+
+ /** Sends allow/deny for a pending approval. False if it is unknown, expired, decided or the link is down. */
+ override fun decide(fingerprint: String, allow: Boolean): Boolean {
+ val w = writer
+ if (out == null || w == null) return false
+ val age = approvals.ageMs(fingerprint) ?: 0L
+ val request = approvals.claim(fingerprint) ?: return false
+ // If it cannot be sent it goes back with the time it has already used, not a fresh 120 s.
+ val back = { approvals.restore(request, clockMs() - age) }
+ return try {
+ w.execute {
+ try {
+ send(ClientMsg.Decision(request.fingerprint, allow))
+ } catch (_: IOException) {
+ back() // not sent: keep it so the user can retry while it is still valid
+ listener.onError("send", "could not reach the desktop")
+ }
+ }
+ true
+ } catch (_: java.util.concurrent.RejectedExecutionException) {
+ back()
+ false
+ }
+ }
+
+ /** Queues a message on the writer thread (never on the caller's: it may be the main thread). */
+ private fun queue(m: ClientMsg): Boolean {
+ val w = writer
+ if (out == null || w == null) return false
+ return try {
+ w.execute { try { send(m) } catch (_: IOException) { listener.onError("send", "could not reach the desktop") } }
+ true
+ } catch (_: java.util.concurrent.RejectedExecutionException) {
+ false
+ }
+ }
+
+ /** Asks for the lines of a file of the session list. False if the computer did not offer `diffs` or the link is down. */
+ override fun getDiff(pillId: String, fileId: Long): Boolean =
+ diffsOffered && Protocol.CAP_DIFFS in caps && queue(ClientMsg.GetDiff(pillId, fileId))
+
+ override fun answer(fingerprint: String, picks: List<List<String>>): Boolean =
+ answersOffered && Protocol.CAP_ANSWERS in caps && queue(ClientMsg.Answer(fingerprint, picks))
+
+ override fun chatModels() { queue(ClientMsg.ChatModels) }
+ override fun chatSend(id: String, model: String, text: String) = queue(ClientMsg.ChatSend(id, model, text))
+ override fun chatCancel(id: String) { queue(ClientMsg.ChatCancel(id)) }
+ override fun chatReset() { queue(ClientMsg.ChatReset) }
+
+ private fun send(m: ClientMsg) {
+ val o = out ?: throw IOException("not connected")
+ synchronized(writeLock) {
+ o.write((Wire.encode(m) + "\n").toByteArray(Charsets.UTF_8))
+ o.flush()
+ }
+ }
+
+ private fun loop() {
+ var attempt = 0
+ while (running) {
+ listener.onState(LinkState.CONNECTING)
+ var connectedOnce = false
+ var lost: LostReason? = null
+ probeKilled = false
+ try {
+ val s = connector.connect(connectTimeoutMs)
+ socket = s
+ s.soTimeout = readTimeoutMs
+ s.tcpNoDelay = true
+ // The system's own probe of a silent connection; its default delay is long, so the real liveness
+ // checks are the app's pings and checkNow(). It costs nothing and catches a connection the network dropped.
+ runCatching { s.keepAlive = true }
+ lastInboundMs = clockMs()
+ out = s.getOutputStream()
+ send(ClientMsg.Hello(Protocol.VERSION, pairing.token, deviceName, caps))
+ val pinger = startPinger()
+ try {
+ read(BufferedInputStream(s.getInputStream())) { connectedOnce = true }
+ } finally {
+ pinger.interrupt()
+ }
+ } catch (e: java.net.SocketTimeoutException) {
+ lost = LostReason.SILENT
+ } catch (_: IOException) {
+ lost = LostReason.NETWORK
+ } catch (_: InterruptedException) {
+ // stop() was called
+ } finally {
+ out = null
+ answersOffered = false
+ prefsOffered = false
+ diffsOffered = false
+ usageOffered = false
+ servicesOffered = false
+ relayOffered = false
+ runCatching { socket?.close() }
+ socket = null
+ approvals.clear()
+ }
+ if (fatal) running = false
+ if (!running) break
+ // A link that had been working and ended on its own: say why (a clean end of the stream is the computer closing it).
+ if (connectedOnce) listener.onLinkLost(if (probeKilled) LostReason.SILENT else lost ?: LostReason.CLOSED)
+ listener.onState(LinkState.DISCONNECTED)
+ if (connectedOnce) attempt = 0 else listener.onConnectFailed(attempt + 1)
+ val wait = backoffMs[minOf(attempt, backoffMs.size - 1)]
+ attempt++
+ wake.drainPermits()
+ try { wake.tryAcquire(wait, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: InterruptedException) { break }
+ }
+ listener.onState(LinkState.DISCONNECTED)
+ }
+
+ private fun startPinger() = Thread({
+ try {
+ while (true) {
+ Thread.sleep(pingEveryMs)
+ send(ClientMsg.Ping)
+ }
+ } catch (_: Exception) {
+ // interrupted or link closed: the reader notices on its own
+ }
+ }, "coucou-link-ping").apply { isDaemon = true; start() }
+
+ private fun read(input: InputStream, onFirstMessage: () -> Unit) {
+ var first = true
+ while (running) {
+ val line = readLine(input) ?: return
+ lastInboundMs = clockMs()
+ val msg = Wire.decodeServer(line) ?: continue
+ if (first) { first = false; onFirstMessage() }
+ when (msg) {
+ is ServerMsg.Welcome -> {
+ if (msg.version != Protocol.VERSION) { listener.onError("version", "desktop speaks v${msg.version}"); fatal = true; return }
+ // Stored before anyone is told, so a listener that reacts to the welcome can already use what was offered.
+ answersOffered = Protocol.CAP_ANSWERS in msg.caps
+ prefsOffered = Protocol.CAP_PREFS in msg.caps
+ diffsOffered = Protocol.CAP_DIFFS in msg.caps
+ usageOffered = Protocol.CAP_USAGE in msg.caps
+ servicesOffered = Protocol.CAP_SERVICES in msg.caps
+ relayOffered = Protocol.CAP_RELAY in msg.caps
+ listener.onState(LinkState.CONNECTED)
+ listener.onWelcome(msg.desktopName, msg.os)
+ listener.onCaps(msg.caps)
+ // Told what it may use right away, so the Chat screen has its list when it opens.
+ if (Protocol.CAP_CHAT in msg.caps && Protocol.CAP_CHAT in caps) queue(ClientMsg.ChatModels)
+ }
+ is ServerMsg.Sessions -> listener.onSessions(msg.sessions)
+ is ServerMsg.Approval -> { approvals.add(msg.request); listener.onApproval(msg.request) }
+ is ServerMsg.ApprovalResolved -> { approvals.resolve(msg.fingerprint); listener.onApprovalResolved(msg.fingerprint) }
+ // Only offered to a phone that asked and was offered `answers`; ignored from a computer that did not.
+ is ServerMsg.Question -> if (answersOffered && Protocol.CAP_ANSWERS in caps) listener.onQuestion(msg.request)
+ // Only after the phone asked for it, and only on a connection that was offered `diffs`.
+ is ServerMsg.Diff -> if (diffsOffered && Protocol.CAP_DIFFS in caps) listener.onDiff(msg)
+ is ServerMsg.Services -> if (servicesOffered && Protocol.CAP_SERVICES in caps) listener.onServices(msg.cards)
+ is ServerMsg.Usage -> if (usageOffered && Protocol.CAP_USAGE in caps) listener.onUsage(msg.usage)
+ // Only on a connection that was offered `relay`, and only a well-formed key.
+ is ServerMsg.RelayAccess -> if (relayOffered && Protocol.CAP_RELAY in caps) listener.onRelayAccess(msg.access)
+ is ServerMsg.Prefs -> if (prefsOffered && Protocol.CAP_PREFS in caps) listener.onPrefs(msg.outfit)
+ ServerMsg.Pong -> {}
+ is ServerMsg.ChatModels -> listener.onChatModels(msg.models)
+ is ServerMsg.ChatDelta -> listener.onChatDelta(msg.id, msg.text)
+ is ServerMsg.ChatDone -> listener.onChatDone(msg.id, msg.text)
+ is ServerMsg.ChatError -> listener.onChatError(msg.id, msg.reason, msg.message)
+ is ServerMsg.Error -> { listener.onError(msg.code, msg.message); if (msg.code == "auth") { fatal = true; return } }
+ }
+ }
+ }
+
+ /** Reads one '\n'-terminated line; null at end of stream. Throws if a line passes the size limit. */
+ private fun readLine(input: InputStream): String? {
+ val buf = ByteArrayOutputStream()
+ while (true) {
+ val b = input.read()
+ if (b < 0) return null
+ if (b == '\n'.code) return String(buf.toByteArray(), Charsets.UTF_8)
+ if (buf.size() >= Protocol.MAX_LINE_BYTES) throw IOException("line too long")
+ buf.write(b)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/LinkHealth.kt b/android/app/src/main/kotlin/com/coucou/android/link/LinkHealth.kt
new file mode 100644
index 00000000..8d4748e5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/LinkHealth.kt
@@ -0,0 +1,90 @@
+package com.coucou.android.link
+
+/**
+ * What the phone knows about the health of the link, in plain terms, so Home can say what happened ("Connection lost 2 min ago,
+ * reconnecting") instead of showing a silent state. Pure: the clock is passed in, so every sentence is a unit test.
+ */
+data class LinkHealth(
+ /** When the link that had been working ended (null: it never did, or it is back). */
+ val lostAtMs: Long? = null,
+ val reason: LostReason? = null,
+ /** Failed attempts since then. */
+ val attempts: Int = 0,
+ /** How many times a link ended on its own after the screen had been off (this is what the battery hint is about). */
+ val dropsWhileScreenOff: Int = 0,
+) {
+ fun lost(atMs: Long, why: LostReason, screenWasOff: Boolean) =
+ copy(lostAtMs = atMs, reason = why, attempts = 0, dropsWhileScreenOff = dropsWhileScreenOff + if (screenWasOff) 1 else 0)
+
+ fun failedAttempt(count: Int) = copy(attempts = count)
+
+ /** Connected again: the story is over (the number of drops while the screen was off stays). */
+ fun recovered() = copy(lostAtMs = null, reason = null, attempts = 0)
+}
+
+object LinkHealthText {
+ /** "less than a minute", "2 min", "1 h 5 min", "3 h". */
+ fun ago(ms: Long): String {
+ val minutes = (ms.coerceAtLeast(0) / 60_000).toInt()
+ return when {
+ minutes < 1 -> "less than a minute"
+ minutes < 60 -> "$minutes min"
+ minutes % 60 == 0 -> "${minutes / 60} h"
+ else -> "${minutes / 60} h ${minutes % 60} min"
+ }
+ }
+
+ private fun why(reason: LostReason?) = when (reason) {
+ LostReason.SILENT -> "The computer stopped answering. This is usual after the phone slept."
+ LostReason.CLOSED -> "The computer closed the connection."
+ LostReason.NETWORK -> "The network dropped."
+ null -> ""
+ }
+
+ /** The two lines for Home while the link is down after having worked; null when there is nothing to say. */
+ fun lines(connected: Boolean, health: LinkHealth, nowMs: Long): Pair<String, String>? {
+ val at = health.lostAtMs ?: return null
+ if (connected) return null
+ val head = "Connection lost ${ago(nowMs - at)} ago, reconnecting" + if (health.attempts >= 3) " (${health.attempts} tries)" else ""
+ return head to why(health.reason)
+ }
+}
+
+/** The alarm that keeps the link honest while the phone sleeps (see docs/ANDROID_LINK.md, "Keeping the link alive"). */
+object KeepAlivePolicy {
+ /**
+ * How often the alarm asks for a check. Android may delay it in Doze (to about 9 minutes, or a maintenance window), never make it
+ * more frequent. The computer allows [COMPUTER_IDLE_MS] of silence, which is several times longer.
+ */
+ const val INTERVAL_MS = 4 * 60_000L
+ /** How long the computer tolerates silence from an authenticated phone (windows/src-tauri/.../server.rs, IDLE_TIMEOUT). */
+ const val COMPUTER_IDLE_MS = 20 * 60_000L
+ /** The wake lock held during one check, only so the question and its answer can cross; released as soon as it is done. */
+ const val WAKE_LOCK_MS = 15_000L
+
+ /** An alarm exists only while a real computer is paired. */
+ fun shouldArm(paired: Boolean, demo: Boolean) = paired && !demo
+}
+
+/**
+ * When to suggest the battery setting. Only when it would help: the link ended on its own after the screen had been off, the
+ * app is still restricted, and the user did not say "not now" recently.
+ */
+object BatteryHint {
+ const val SNOOZE_MS = 7 * 24 * 3_600_000L
+
+ fun shouldShow(paired: Boolean, health: LinkHealth, ignoringOptimizations: Boolean, snoozedAtMs: Long?, nowMs: Long): Boolean =
+ paired && !ignoringOptimizations && health.dropsWhileScreenOff >= 1 &&
+ (snoozedAtMs == null || nowMs - snoozedAtMs >= SNOOZE_MS)
+
+ /** Where to look: Samsung hides the setting in two places. */
+ fun isSamsung(manufacturer: String) = manufacturer.equals("samsung", ignoreCase = true)
+
+ fun steps(samsung: Boolean): List<String> =
+ if (samsung) listOf(
+ "Open Settings > Apps > Coucou for Android > Battery and choose Unrestricted.",
+ "Then Settings > Battery > Background usage limits: make sure Coucou is not in Sleeping apps or Deep sleeping apps (add it to Never sleeping apps).",
+ ) else listOf(
+ "Open the app's battery setting and choose Unrestricted (or Don't optimise).",
+ )
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Pairing.kt b/android/app/src/main/kotlin/com/coucou/android/link/Pairing.kt
new file mode 100644
index 00000000..093959d9
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Pairing.kt
@@ -0,0 +1,88 @@
+package com.coucou.android.link
+
+import android.annotation.SuppressLint
+import java.net.URI
+import java.net.URLDecoder
+import java.security.MessageDigest
+import java.security.cert.CertificateException
+import java.security.cert.X509Certificate
+import javax.net.ssl.X509TrustManager
+
+/**
+ * What the desktop shows as a QR code: coucou://pair?v=1&host=...&port=...&fp=...&token=...&name=...
+ * (and, when its relay is on, &relay=...&room=...&key=...&access=..., see docs/RELAY_LINK.md).
+ * `fp` is the SHA-256 (hex) of the desktop's TLS certificate; `token` is the shared pairing secret.
+ */
+data class PairingPayload(
+ val host: String,
+ val port: Int,
+ val certSha256: String,
+ val token: String,
+ val desktopName: String,
+ /** The relay fields of the link (all four or none); null for a link that only works on the local network. */
+ val relay: RelayPairing? = null,
+) {
+ companion object {
+ /** Returns null for anything that is not a well-formed v1 pairing link. */
+ fun parse(text: String): PairingPayload? {
+ val uri = try { URI(text.trim()) } catch (_: Exception) { return null }
+ if (uri.scheme != "coucou" || uri.host != "pair") return null
+ val q = (uri.rawQuery ?: return null).split("&").mapNotNull {
+ val i = it.indexOf('=')
+ if (i <= 0) null else it.substring(0, i) to URLDecoder.decode(it.substring(i + 1), "UTF-8")
+ }.toMap()
+ if (q["v"] != Protocol.VERSION.toString()) return null
+ val host = q["host"]?.takeIf { it.isNotBlank() && it.length <= 253 } ?: return null
+ val port = q["port"]?.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
+ val fp = q["fp"]?.lowercase()?.takeIf(Wire::isFingerprint) ?: return null
+ val token = q["token"]?.takeIf { it.length in 16..128 && it.all { c -> c.isLetterOrDigit() || c == '-' || c == '_' } }
+ ?: return null
+ // The relay fields are all there and well formed, or all absent; anything in between is a damaged link.
+ val relay = when (val r = RelayPairing.fromQuery(q)) {
+ RelayPairing.Companion.Parsed.Absent -> null
+ RelayPairing.Companion.Parsed.Invalid -> return null
+ is RelayPairing.Companion.Parsed.Ok -> r.relay
+ }
+ return PairingPayload(host, port, fp, token, q["name"].orEmpty().take(64), relay)
+ }
+ }
+}
+
+/** Accepts exactly one certificate, the one whose SHA-256 was in the QR code. No CA, no hostname check. */
+@SuppressLint("CustomX509TrustManager") // intentional: certificate pinning to the paired desktop
+class PinnedTrustManager(private val pinnedSha256Hex: String) : X509TrustManager {
+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
+ val leaf = chain?.firstOrNull() ?: throw CertificateException("empty certificate chain")
+ val actual = MessageDigest.getInstance("SHA-256").digest(leaf.encoded).joinToString("") { "%02x".format(it) }
+ if (!MessageDigest.isEqual(actual.toByteArray(), pinnedSha256Hex.lowercase().toByteArray())) {
+ throw CertificateException("certificate does not match the paired desktop")
+ }
+ }
+
+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
+ throw CertificateException("client certificates are not used")
+ }
+
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+}
+
+/**
+ * How a pairing is kept (encrypted by SecureStore): one field per line, the relay's four after the five LAN ones. An older
+ * file with five lines reads as a LAN-only pairing, so an app update never loses a pairing.
+ */
+object PairingCodec {
+ fun encode(p: PairingPayload): String {
+ val base = listOf(p.host, p.port.toString(), p.certSha256, p.token, p.desktopName)
+ val r = p.relay ?: return base.joinToString("\n")
+ return (base + listOf(r.url, r.room, r.key, r.access)).joinToString("\n")
+ }
+
+ /** Null when the text is not a pairing this build can use. */
+ fun decode(text: String): PairingPayload? {
+ val parts = text.split("\n")
+ if (parts.size < 4) return null
+ val port = parts[1].toIntOrNull() ?: return null
+ val relay = if (parts.size >= 9) RelayPairing(parts[5], parts[6], parts[7], parts[8]) else null
+ return PairingPayload(parts[0], port, parts[2], parts[3], parts.getOrElse(4) { "" }, relay)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Protocol.kt b/android/app/src/main/kotlin/com/coucou/android/link/Protocol.kt
new file mode 100644
index 00000000..439e75b9
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Protocol.kt
@@ -0,0 +1,389 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.outfit.Wardrobe
+import java.security.MessageDigest
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+
+/**
+ * Wire format of the desktop link (docs/ANDROID_LINK.md): newline-delimited JSON over TLS.
+ * Pure Kotlin plus org.json, so it runs in JVM unit tests.
+ */
+object Protocol {
+ const val VERSION = 1
+ /** The desktop dismisses an approval after 115 s; the phone stops offering it at 120 s. */
+ const val APPROVAL_TTL_MS = 120_000L
+ /** One message never exceeds this; a longer line is a protocol error. */
+ const val MAX_LINE_BYTES = 64 * 1024
+ /** Optional features this app understands; the desktop offers back the ones it has switched on. */
+ val CAPABILITIES = listOf("chat", "details", "answers", "prefs", "diffs", "usage", "services", "relay")
+ const val CAP_CHAT = "chat"
+ /** Steps, last line, project folder name and colour of each session. */
+ const val CAP_DETAILS = "details"
+ /** Answering the questions Claude Code asks, from the phone (each answer confirmed with the screen lock). */
+ const val CAP_ANSWERS = "answers"
+ /** What Mochi wears on the computer (no switch there: it is no secret). */
+ const val CAP_PREFS = "prefs"
+ /** The files an agent changed (a list on each session) and, when asked for one, its lines. */
+ const val CAP_DIFFS = "diffs"
+ /** How much of the Claude and Codex plans is used, and when they reset. */
+ const val CAP_USAGE = "usage"
+ /** Read-only cards of the services the user ticked on the computer (Stripe, GitHub...). */
+ const val CAP_SERVICES = "services"
+ /** The computer's relay switch is on: it sends the new access key when the user replaces it (docs/RELAY_LINK.md). */
+ const val CAP_RELAY = "relay"
+ const val MAX_SERVICES = 7
+ const val MAX_SERVICE_ITEMS = 3
+ const val MAX_SERVICE_TEXT = 80
+ const val MAX_FILES = 20
+ const val MAX_FILE_NAME_CHARS = 80
+ /** The computer sends at most this many lines of one file, each cut at [MAX_DIFF_LINE_CHARS], in parts of at most [PART_LINES]. */
+ const val MAX_DIFF_LINES = 200
+ const val MAX_DIFF_LINE_CHARS = 400
+ const val PART_LINES = 100
+ const val MAX_DIFF_PARTS = 4
+ const val MAX_QUESTIONS = 4
+ const val MAX_OPTIONS = 8
+ const val MAX_STEPS = 20
+ const val MAX_STEP_CHARS = 200
+ const val MAX_PROJECT_CHARS = 64
+ /** What the desktop accepts for one chat message; longer is refused there, so it is refused here first. */
+ const val CHAT_MAX_TEXT = 4000
+}
+
+/** A model the user allowed on the computer for the phone. [id] is "provider/model". */
+data class ChatModel(val id: String, val provider: String, val label: String)
+
+/** One window of a plan: whole percent used (0..100) and when it resets (epoch ms). */
+data class PlanWindow(val pct: Int, val resetsAtMs: Long)
+
+/** What the computer knows of one plan. [plan] is a short name such as "plus"; [resetCredits] Codex's free resets. */
+data class PlanUsage(
+ val fiveHour: PlanWindow?, val sevenDay: PlanWindow?, val resetCredits: Int? = null, val plan: String? = null, val updatedAtMs: Long = 0,
+)
+
+/** Both plans; null for one the computer does not know. */
+data class UsageSnapshot(val claude: PlanUsage?, val codex: PlanUsage?)
+
+/** One line of a service card. */
+data class ServiceLine(val label: String, val detail: String)
+
+/** What one service's pill shows: a headline, why, up to three lines. Read-only. */
+data class ServiceCard(val id: String, val title: String, val headline: String, val reason: String?, val items: List<ServiceLine>)
+
+/** A file an agent changed. [name] is a file name, never a path. */
+data class FileChange(val id: Long, val name: String, val added: Int, val removed: Int, val tooLarge: Boolean = false, val isNew: Boolean = false)
+
+/** One line of a diff: [kind] is '+', '-', ' ' (context) or '@' (a hunk starts). */
+data class DiffRow(val kind: Char, val text: String)
+
+data class SessionInfo(
+ val pillId: String,
+ val agent: String,
+ val state: BotState,
+ val statusText: String,
+ val stepIndex: Int,
+ val stepCount: Int,
+ val updatedAtMs: Long,
+ // Only with the "details" capability (the user's switch on the computer); empty or null otherwise.
+ val steps: List<String> = emptyList(),
+ val finalLine: String? = null,
+ /** A folder name, never a path. */
+ val project: String? = null,
+ /** "#RRGGBB" or null. */
+ val color: String? = null,
+ /** Only with the "diffs" capability (the user's switch on the computer). */
+ val files: List<FileChange> = emptyList(),
+)
+
+data class ApprovalRequest(
+ val pillId: String,
+ val fingerprint: String,
+ val tool: String,
+ val command: String,
+ val createdAtMs: Long,
+ /** The computer cut the command to fit (it sends at most 500 characters): what is shown is not all of it. Additive; absent means false. */
+ val truncated: Boolean = false,
+)
+
+/** One option of a question Claude Code asked. */
+data class AskedOption(val label: String, val description: String)
+
+/** One question of an AskUserQuestion call. */
+data class AskedQuestion(val question: String, val options: List<AskedOption>, val multiSelect: Boolean)
+
+/** A question waiting for an answer (cap `answers`). */
+data class QuestionRequest(val pillId: String, val fingerprint: String, val questions: List<AskedQuestion>, val createdAtMs: Long)
+
+sealed interface ServerMsg {
+ data class Welcome(val version: Int, val desktopName: String, val os: String, val caps: Set<String> = emptySet()) : ServerMsg
+ data class Sessions(val sessions: List<SessionInfo>) : ServerMsg
+ data class Approval(val request: ApprovalRequest) : ServerMsg
+ data class ApprovalResolved(val fingerprint: String) : ServerMsg
+ data class Question(val request: QuestionRequest) : ServerMsg
+ /** What Mochi wears on the computer: "auto" or an outfit, exactly one of [com.coucou.android.mochi.outfit.Wardrobe.SELECTIONS]. */
+ data class Prefs(val outfit: String) : ServerMsg
+ /** The relay's access key was replaced on the computer (only with the `relay` capability). */
+ data class RelayAccess(val access: String) : ServerMsg
+ /** The service cards the user allowed; an empty list takes them away. */
+ data class Services(val cards: List<ServiceCard>) : ServerMsg
+ /** The plan usage; both null means the computer has nothing to say any more. */
+ data class Usage(val usage: UsageSnapshot) : ServerMsg
+ /** One part of a file's diff; [gone]: the computer no longer has it; [truncated]: there were more lines than it sends. */
+ data class Diff(
+ val pillId: String, val fileId: Long, val name: String, val added: Int, val removed: Int,
+ val tooLarge: Boolean, val gone: Boolean, val truncated: Boolean, val part: Int, val parts: Int, val lines: List<DiffRow>,
+ ) : ServerMsg
+ data object Pong : ServerMsg
+ data class ChatModels(val models: List<ChatModel>) : ServerMsg
+ /** [text] is appended to the answer being written. */
+ data class ChatDelta(val id: String, val text: String) : ServerMsg
+ /** [text], when present, is the full answer and replaces what was streamed. */
+ data class ChatDone(val id: String, val text: String?) : ServerMsg
+ /** [reason] is a fixed code (off, busy, rate, auth...); [message] a fixed sentence written by the computer. */
+ data class ChatError(val id: String, val reason: String, val message: String) : ServerMsg
+ data class Error(val code: String, val message: String) : ServerMsg
+}
+
+sealed interface ClientMsg {
+ data class Hello(val version: Int, val token: String, val deviceName: String, val caps: List<String> = emptyList()) : ClientMsg
+ /** Only allow and deny exist from the phone: no "always". */
+ data class Decision(val fingerprint: String, val allow: Boolean) : ClientMsg
+ data object Ping : ClientMsg
+ data object Bye : ClientMsg
+ /** [picks]: one list of labels per question, in order (exactly one for a single choice). */
+ data class Answer(val fingerprint: String, val picks: List<List<String>>) : ClientMsg
+ /** The lines of one file the session list showed (cap `diffs`). */
+ data class GetDiff(val pillId: String, val fileId: Long) : ClientMsg
+ data object ChatModels : ClientMsg
+ data class ChatSend(val id: String, val model: String, val text: String) : ClientMsg
+ data class ChatCancel(val id: String) : ClientMsg
+ /** New chat: the computer forgets its side of the conversation and stops a running answer. */
+ data object ChatReset : ClientMsg
+}
+
+object Wire {
+ fun encode(m: ClientMsg): String {
+ val o = JSONObject()
+ when (m) {
+ is ClientMsg.Hello -> {
+ o.put("type", "hello").put("v", m.version).put("token", m.token).put("device", m.deviceName)
+ // Only when there is something to say: an app with no optional features sends the v1 hello unchanged.
+ if (m.caps.isNotEmpty()) o.put("caps", JSONArray(m.caps))
+ }
+ is ClientMsg.Decision -> o.put("type", "decision").put("fingerprint", m.fingerprint)
+ .put("decision", if (m.allow) "allow" else "deny")
+ ClientMsg.Ping -> o.put("type", "ping")
+ ClientMsg.Bye -> o.put("type", "bye")
+ is ClientMsg.Answer -> o.put("type", "answer").put("fingerprint", m.fingerprint)
+ .put("picks", JSONArray(m.picks.map { JSONArray(it) }))
+ is ClientMsg.GetDiff -> o.put("type", "getDiff").put("pillId", m.pillId).put("fileId", m.fileId)
+ ClientMsg.ChatModels -> o.put("type", "chatModels")
+ is ClientMsg.ChatSend -> o.put("type", "chatSend").put("id", m.id).put("model", m.model).put("text", m.text)
+ is ClientMsg.ChatCancel -> o.put("type", "chatCancel").put("id", m.id)
+ ClientMsg.ChatReset -> o.put("type", "chatReset")
+ }
+ return o.toString()
+ }
+
+ /** Returns null for anything malformed or unknown: a bad line never crashes the client. */
+ fun decodeServer(line: String): ServerMsg? {
+ if (line.length > Protocol.MAX_LINE_BYTES) return null
+ return try {
+ val o = JSONObject(line)
+ when (o.getString("type")) {
+ "welcome" -> ServerMsg.Welcome(o.getInt("v"), o.optString("desktop", ""), o.optString("os", ""), strings(o.optJSONArray("caps")))
+ "sessions" -> ServerMsg.Sessions(o.getJSONArray("sessions").objects().map(::session))
+ "approval" -> ServerMsg.Approval(
+ ApprovalRequest(
+ pillId = o.getString("pillId"),
+ fingerprint = o.getString("fingerprint").also { require(isFingerprint(it)) },
+ tool = o.getString("tool"),
+ command = o.getString("command"),
+ createdAtMs = o.getLong("createdAt"),
+ truncated = o.optBoolean("truncated", false),
+ ),
+ )
+ "approvalResolved" -> ServerMsg.ApprovalResolved(o.getString("fingerprint"))
+ "question" -> question(o)?.let { ServerMsg.Question(it) }
+ // A value this build does not know is dropped rather than guessed: the phone keeps what it had.
+ "diff" -> diff(o)
+ "services" -> ServerMsg.Services(services(o.getJSONArray("services")))
+ "usage" -> ServerMsg.Usage(UsageSnapshot(plan(o.optJSONObject("claude")), plan(o.optJSONObject("codex"))))
+ "prefs" -> o.optString("outfit", "").takeIf { it in Wardrobe.SELECTIONS }?.let { ServerMsg.Prefs(it) }
+ "relayAccess" -> o.optString("access", "").takeIf(RelayPairing::isSecret)?.let { ServerMsg.RelayAccess(it) }
+ "pong" -> ServerMsg.Pong
+ "chatModels" -> ServerMsg.ChatModels(o.getJSONArray("models").objects().mapNotNull(::chatModel))
+ "chatDelta" -> ServerMsg.ChatDelta(chatId(o), o.getString("text"))
+ "chatDone" -> ServerMsg.ChatDone(chatId(o), if (o.has("text")) o.getString("text") else null)
+ "chatError" -> ServerMsg.ChatError(chatId(o), o.optString("reason", "internal"), o.optString("message", ""))
+ "error" -> ServerMsg.Error(o.optString("code", ""), o.optString("message", ""))
+ else -> null
+ }
+ } catch (_: JSONException) {
+ null
+ } catch (_: IllegalArgumentException) {
+ null
+ }
+ }
+
+ private fun session(o: JSONObject) = SessionInfo(
+ pillId = o.getString("pillId"),
+ agent = o.optString("agent", ""),
+ state = BotState.entries.firstOrNull { it.key == o.optString("state") } ?: BotState.IDLE,
+ statusText = o.optString("statusText", ""),
+ stepIndex = o.optInt("stepIndex", 0),
+ stepCount = o.optInt("stepCount", 0),
+ updatedAtMs = o.optLong("updatedAt", 0),
+ steps = stringList(o.optJSONArray("steps")).take(Protocol.MAX_STEPS).map { it.take(Protocol.MAX_STEP_CHARS) },
+ finalLine = o.optString("finalLine", "").take(Protocol.MAX_STEP_CHARS).ifBlank { null },
+ project = folderName(o.optString("project", "")),
+ color = o.optString("color", "").takeIf { isColor(it) },
+ files = files(o.optJSONArray("files")),
+ )
+
+ private val SERVICE_IDS = setOf(
+ "integration_stripe", "integration_github", "integration_vercel", "integration_n8n",
+ "integration_resend", "integration_notion", "integration_calcom",
+ )
+
+ private fun oneLine(s: String, max: Int) = s.filter { !it.isISOControl() }.trim().take(max)
+
+ /** Cards of the services this app knows, each cut to size; anything else is skipped. */
+ private fun services(a: JSONArray): List<ServiceCard> {
+ val seen = HashSet<String>()
+ return (0 until a.length()).mapNotNull { i ->
+ val o = a.optJSONObject(i) ?: return@mapNotNull null
+ val id = o.optString("id", "")
+ if (id !in SERVICE_IDS || !seen.add(id)) return@mapNotNull null
+ val items = o.optJSONArray("items")?.let { arr ->
+ (0 until arr.length()).mapNotNull { j ->
+ val it = arr.optJSONObject(j) ?: return@mapNotNull null
+ val label = oneLine(it.optString("label", ""), Protocol.MAX_SERVICE_TEXT)
+ if (label.isEmpty()) null else ServiceLine(label, oneLine(it.optString("detail", ""), Protocol.MAX_SERVICE_TEXT))
+ }.take(Protocol.MAX_SERVICE_ITEMS)
+ }.orEmpty()
+ ServiceCard(
+ id, oneLine(o.optString("title", ""), Protocol.MAX_SERVICE_TEXT), oneLine(o.optString("headline", ""), Protocol.MAX_SERVICE_TEXT),
+ oneLine(o.optString("reason", ""), Protocol.MAX_SERVICE_TEXT).ifBlank { null }, items,
+ )
+ }.take(Protocol.MAX_SERVICES)
+ }
+
+ private fun window(o: JSONObject?): PlanWindow? {
+ if (o == null || !o.has("pct") || !o.has("resetsAt")) return null
+ val pct = o.optInt("pct", -1)
+ val at = o.optLong("resetsAt", 0)
+ return if (pct in 0..100 && at > 0) PlanWindow(pct, at) else null
+ }
+
+ private fun plan(o: JSONObject?): PlanUsage? {
+ if (o == null) return null
+ val five = window(o.optJSONObject("fiveHour"))
+ val seven = window(o.optJSONObject("sevenDay"))
+ if (five == null && seven == null) return null
+ val name = o.optString("plan", "").filter { it.isLetterOrDigit() || it == ' ' || it == '-' }.trim().take(20).ifBlank { null }
+ val credits = if (o.has("resetCredits")) o.optInt("resetCredits", -1).takeIf { it in 0..99 } else null
+ return PlanUsage(five, seven, credits, name, o.optLong("updatedAt", 0).coerceAtLeast(0))
+ }
+
+ /** Files with an id and a name, as names only (even if a path were sent), at most [Protocol.MAX_FILES]. */
+ private fun files(a: JSONArray?): List<FileChange> {
+ if (a == null) return emptyList()
+ return (0 until a.length()).mapNotNull { i ->
+ val f = a.optJSONObject(i) ?: return@mapNotNull null
+ if (!f.has("id")) return@mapNotNull null
+ val id = f.optLong("id", -1)
+ val name = fileNameOf(f.optString("name", "")) ?: return@mapNotNull null
+ if (id < 0) return@mapNotNull null
+ FileChange(id, name, f.optInt("added", 0).coerceAtLeast(0), f.optInt("removed", 0).coerceAtLeast(0), f.optBoolean("tooLarge", false), f.optBoolean("isNew", false))
+ }.takeLast(Protocol.MAX_FILES)
+ }
+
+ /** The last segment of a path, without control characters and cut; null if nothing is left. */
+ fun fileNameOf(raw: String): String? {
+ val last = raw.trimEnd('/', '\\').substringAfterLast('/').substringAfterLast('\\').filter { !it.isISOControl() }.trim().take(Protocol.MAX_FILE_NAME_CHARS)
+ return last.takeIf { it.isNotEmpty() && it != "." && it != ".." }
+ }
+
+ /** A part of a diff, or null if it breaks the limits the computer keeps (so it cannot be a real one). */
+ private fun diff(o: JSONObject): ServerMsg.Diff? {
+ val parts = o.getInt("parts")
+ val part = o.getInt("part")
+ if (parts !in 1..Protocol.MAX_DIFF_PARTS || part !in 0 until parts) return null
+ val arr = o.getJSONArray("lines")
+ if (arr.length() > Protocol.PART_LINES) return null
+ val rows = (0 until arr.length()).map { i ->
+ val r = arr.getJSONArray(i)
+ val k = r.getString(0)
+ val kind = if (k.length == 1 && k[0] in "+-@") k[0] else ' '
+ DiffRow(kind, r.getString(1).take(Protocol.MAX_DIFF_LINE_CHARS))
+ }
+ return ServerMsg.Diff(
+ pillId = o.getString("pillId"), fileId = o.getLong("fileId"), name = fileNameOf(o.optString("name", "")).orEmpty(),
+ added = o.optInt("added", 0).coerceAtLeast(0), removed = o.optInt("removed", 0).coerceAtLeast(0),
+ tooLarge = o.optBoolean("tooLarge", false), gone = o.optBoolean("gone", false), truncated = o.optBoolean("truncated", false),
+ part = part, parts = parts, lines = rows,
+ )
+ }
+
+ /**
+ * A question as the computer offers it, or null if it breaks the limits (the computer would not send such a
+ * one): 1 to 4 questions, each with 1 to 8 options that have different, non-blank labels.
+ */
+ private fun question(o: JSONObject): QuestionRequest? {
+ val fingerprint = o.getString("fingerprint").also { require(isFingerprint(it)) }
+ val items = o.getJSONArray("questions").objects().map { q ->
+ val options = q.getJSONArray("options").objects().map { AskedOption(it.getString("label"), it.optString("description", "")) }
+ AskedQuestion(q.getString("question"), options, q.optBoolean("multiSelect", false))
+ }
+ val ok = items.isNotEmpty() && items.size <= Protocol.MAX_QUESTIONS && items.all { i ->
+ i.question.isNotBlank() && i.options.isNotEmpty() && i.options.size <= Protocol.MAX_OPTIONS &&
+ i.options.all { it.label.isNotBlank() } && i.options.map { it.label }.distinct().size == i.options.size
+ }
+ return if (ok) QuestionRequest(o.getString("pillId"), fingerprint, items, o.optLong("createdAt", 0)) else null
+ }
+
+ /** Strings of a JSON array, in order; anything else in it is skipped. */
+ private fun stringList(a: JSONArray?): List<String> =
+ if (a == null) emptyList() else (0 until a.length()).mapNotNull { (a.opt(it) as? String)?.takeIf { s -> s.isNotBlank() } }
+
+ /** Even from a computer that should not send one, never a path: only the last segment is kept. */
+ fun folderName(raw: String): String? {
+ val last = raw.trimEnd('/', '\\').substringAfterLast('/').substringAfterLast('\\')
+ .filter { !it.isISOControl() }.trim().take(Protocol.MAX_PROJECT_CHARS)
+ return last.takeIf { it.isNotEmpty() && it != "." && it != ".." }
+ }
+
+ fun isColor(s: String) = s.length == 7 && s[0] == '#' && s.drop(1).all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
+
+ private fun strings(a: JSONArray?): Set<String> =
+ if (a == null) emptySet() else (0 until a.length()).mapNotNull { a.optString(it, "").takeIf { s -> s.isNotEmpty() } }.toSet()
+
+ /** A model without a usable id is dropped; a missing label shows the id. */
+ private fun chatModel(o: JSONObject): ChatModel? {
+ val id = o.optString("id", "")
+ if (id.isBlank() || id.length > 300 || id.indexOf('/') <= 0) return null
+ return ChatModel(id, o.optString("provider", id.substringBefore('/')), o.optString("label", "").ifBlank { id })
+ }
+
+ private fun chatId(o: JSONObject): String = o.getString("id").also { require(isChatId(it)) }
+
+ private fun JSONArray.objects(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }
+
+ /** The id the phone makes for a chat message and the computer echoes: 1 to 64 of letters, digits, - and _. */
+ fun isChatId(s: String) = s.isNotEmpty() && s.length <= 64 && s.all { it.isLetterOrDigit() && it.code < 128 || it == '-' || it == '_' }
+
+ fun isFingerprint(s: String) = s.length == 64 && s.all { it in '0'..'9' || it in 'a'..'f' }
+}
+
+/** Same derivation as ApprovalRelay.fingerprint on the Mac: SHA-256 of the fields joined by U+001F. */
+object Fingerprint {
+ fun of(pillId: String, sessionId: String, tool: String, command: String, inputKey: String): String {
+ val raw = listOf(pillId, sessionId, tool, command, inputKey).joinToString("\u001F")
+ return MessageDigest.getInstance("SHA-256").digest(raw.toByteArray(Charsets.UTF_8))
+ .joinToString("") { "%02x".format(it) }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Reconnect.kt b/android/app/src/main/kotlin/com/coucou/android/link/Reconnect.kt
new file mode 100644
index 00000000..241f33fc
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Reconnect.kt
@@ -0,0 +1,37 @@
+package com.coucou.android.link
+
+/** Things that should make the phone look at its link right away instead of waiting for the next timer. */
+enum class Wake {
+ /** The screen turned on or the phone was unlocked. */
+ SCREEN_ON,
+ SCREEN_OFF,
+ /** The default network changed to a new one (Wi-Fi joined, Wi-Fi to mobile data...). */
+ NEW_NETWORK,
+ /** The network under the link went away. */
+ NETWORK_LOST,
+ /** The periodic alarm (KeepAlivePolicy). */
+ ALARM,
+}
+
+/**
+ * What to do on each [Wake]. Pure, so the rules are tests with fake events:
+ * - connected: ask the computer for a pong now (the connection may be half dead: asleep, or on a network that is gone);
+ * - not connected: reconnect now, but only if there is a network the link could use (Wi-Fi, or a relay over mobile data);
+ * - losing the network or turning the screen off needs nothing: the loop notices a dead connection by itself.
+ */
+object ReconnectPolicy {
+ enum class Action { NONE, RETRY_NOW, CHECK_NOW }
+
+ fun decide(event: Wake, paired: Boolean, connected: Boolean, wifiUp: Boolean, hasRelay: Boolean): Action {
+ if (!paired) return Action.NONE
+ return when (event) {
+ Wake.SCREEN_OFF, Wake.NETWORK_LOST -> Action.NONE
+ Wake.SCREEN_ON, Wake.NEW_NETWORK, Wake.ALARM ->
+ when {
+ connected -> Action.CHECK_NOW
+ event == Wake.SCREEN_ON || wifiUp || hasRelay -> Action.RETRY_NOW
+ else -> Action.NONE
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/RelayCrypto.kt b/android/app/src/main/kotlin/com/coucou/android/link/RelayCrypto.kt
new file mode 100644
index 00000000..55a5c858
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/RelayCrypto.kt
@@ -0,0 +1,316 @@
+package com.coucou.android.link
+
+import java.nio.ByteBuffer
+import java.security.GeneralSecurityException
+import java.security.MessageDigest
+import javax.crypto.Cipher
+import javax.crypto.Mac
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * The end-to-end encrypted channel for the relay link (docs/RELAY_LINK.md, sections 4 and 5): the Kotlin twin of
+ * windows/src-tauri/src/phone_link/relay_crypto.rs. Pure: bytes in, bytes out; no sockets, no clock, no files, no logging.
+ * Both twins are checked against android/relay/test-vectors.json, so what one writes the other reads.
+ *
+ * - 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; any fault kills the session;
+ * - secrets print as ".." and are wiped on [wipe]; nothing here writes them anywhere.
+ */
+object RelayCrypto {
+ const val LABEL = "coucou-relay/v1"
+ const val VER = 1
+ const val T_INIT = 1
+ const val T_ACCEPT = 2
+ const val T_DATA = 3
+ /** What the relay accepts in one WebSocket message. */
+ const val MAX_FRAME = 66_000
+ /** A protocol v1 line, as on the LAN. */
+ const val MAX_LINE = 65_536
+ /** The last counter a session may use (2^32 - 1); then the phone re-handshakes. */
+ const val LAST_COUNTER = 0xFFFF_FFFFL
+ const val NONCE_LEN = 16
+ private const val HEADER = 10
+ private const val TAG = 16
+ private const val MAC_LEN = 32
+ private const val BLOCK = 128
+
+ enum class Dir(val byte: Int) { PHONE_TO_HOST(1), HOST_TO_PHONE(2) }
+
+ enum class Failure {
+ /** Too short, an unknown version or an unexpected frame type. */
+ BAD_HEADER,
+ /** The authentication tag (or a handshake MAC) did not verify: wrong key, room or direction, altered or truncated. */
+ BAD_TAG,
+ /** Not the next expected counter (repeat, gap, jump) or past the last allowed. */
+ BAD_COUNTER,
+ BAD_PADDING,
+ TOO_LONG,
+ /** The session used its last counter; start a new handshake. */
+ EXHAUSTED,
+ /** An earlier fault ended this session. */
+ FAULTED,
+ }
+
+ /** Carries only the reason: never a key, a frame or a line. */
+ class ChannelException(val failure: Failure) : Exception(failure.name)
+
+ // ── secrets ─────────────────────────────────────────────────────────────────
+
+ /** Secret bytes: printed as "..", wiped on request. */
+ class Secret(internal val bytes: ByteArray) {
+ fun wipe() = bytes.fill(0)
+ override fun toString() = "Secret(..)"
+ }
+
+ /** K, the pairing key from the pairing link (43 base64url characters), or made fresh. */
+ class PairingKey(bytes: ByteArray) {
+ private val secret = Secret(bytes.copyOf().also { require(it.size == 32) { "a pairing key has 32 bytes" } })
+ internal val raw: ByteArray get() = secret.bytes
+ fun toBase64Url(): String = base64UrlEncode(secret.bytes)
+ fun wipe() = secret.wipe()
+ override fun toString() = "PairingKey(..)"
+
+ companion object {
+ fun fromBase64Url(text: String): PairingKey? = base64UrlDecode(text)?.takeIf { it.size == 32 }?.let { PairingKey(it) }
+ }
+ }
+
+ // ── derivation ──────────────────────────────────────────────────────────────
+
+ private fun hmac(key: ByteArray, vararg parts: ByteArray): ByteArray {
+ val mac = Mac.getInstance("HmacSHA256")
+ mac.init(SecretKeySpec(if (key.isEmpty()) ByteArray(32) else key, "HmacSHA256")) // an empty key is a zero block (RFC 2104)
+ for (p in parts) mac.update(p)
+ return mac.doFinal()
+ }
+
+ /** HKDF-SHA-256 (RFC 5869). */
+ fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {
+ require(length in 1..255 * 32)
+ val prk = hmac(if (salt.isEmpty()) ByteArray(32) else salt, ikm)
+ val out = ByteArray(length)
+ var previous = ByteArray(0)
+ var done = 0
+ var counter = 1
+ while (done < length) {
+ previous = hmac(prk, previous, info, byteArrayOf(counter.toByte()))
+ val n = minOf(previous.size, length - done)
+ System.arraycopy(previous, 0, out, done, n)
+ done += n
+ counter++
+ }
+ return out
+ }
+
+ private fun derive32(k: PairingKey, what: String): ByteArray = hkdf(k.raw, ByteArray(0), "$LABEL $what".toByteArray(), 32)
+
+ /** `K_auth`: MACs the two handshake frames. */
+ fun kAuth(k: PairingKey): Secret = Secret(derive32(k, "auth"))
+
+ /** `K_join`: presented to the relay as a join proof; one-way from K. */
+ fun kJoin(k: PairingKey): Secret = Secret(derive32(k, "join"))
+
+ /** The join proof for the `coucou.join.<…>` sub-protocol. */
+ fun joinProof(k: PairingKey): String = base64UrlEncode(kJoin(k).bytes)
+
+ /** The two session keys, `(phone → host, host → phone)`. */
+ internal fun sessionKeys(k: PairingKey, nPhone: ByteArray, nHost: ByteArray): Pair<Secret, Secret> {
+ require(nPhone.size == NONCE_LEN && nHost.size == NONCE_LEN)
+ val out = hkdf(k.raw, nPhone + nHost, "$LABEL session".toByteArray(), 64)
+ return Secret(out.copyOfRange(0, 32)) to Secret(out.copyOfRange(32, 64)).also { out.fill(0) }
+ }
+
+ /** `direction ‖ 0x00 0x00 0x00 ‖ counter` (12 bytes). */
+ fun nonceFor(dir: Dir, counter: Long): ByteArray =
+ ByteBuffer.allocate(12).put(dir.byte.toByte()).put(0).put(0).put(0).putLong(counter).array()
+
+ private fun header(type: Int, counter: Long): ByteArray =
+ ByteBuffer.allocate(HEADER).put(VER.toByte()).put(type.toByte()).putLong(counter).array()
+
+ private fun aad(room: String, dir: Dir, header: ByteArray): ByteArray =
+ LABEL.toByteArray() + room.toByteArray() + byteArrayOf(dir.byte.toByte()) + header
+
+ // ── handshake ───────────────────────────────────────────────────────────────
+
+ /** A fresh 16-byte handshake nonce. */
+ fun freshNonce(): ByteArray = ByteArray(NONCE_LEN).also { java.security.SecureRandom().nextBytes(it) }
+
+ private fun parseHandshake(frame: ByteArray, wanted: Int): Pair<ByteArray, ByteArray> {
+ val zeroCounter = frame.size >= HEADER && (2 until HEADER).all { frame[it] == 0.toByte() }
+ if (frame.size != HEADER + NONCE_LEN + MAC_LEN || frame[0].toInt() != VER || frame[1].toInt() != wanted || !zeroCounter) {
+ throw ChannelException(Failure.BAD_HEADER)
+ }
+ return frame.copyOfRange(HEADER, HEADER + NONCE_LEN) to frame.copyOfRange(HEADER + NONCE_LEN, frame.size)
+ }
+
+ private fun macOk(auth: Secret, tag: ByteArray, vararg parts: ByteArray) = MessageDigest.isEqual(hmac(auth.bytes, *parts), tag) // constant time
+
+ /** The phone's first frame; it must remember [nPhone] to check the answer. */
+ fun initFrame(k: PairingKey, room: String, nPhone: ByteArray): ByteArray {
+ require(nPhone.size == NONCE_LEN)
+ val tag = hmac(kAuth(k).bytes, "init".toByteArray(), room.toByteArray(), nPhone)
+ return header(T_INIT, 0) + nPhone + tag
+ }
+
+ /** The computer's side (used by tests and tools): checks an `init`, answers `accept`, and returns the session. */
+ fun acceptInit(k: PairingKey, room: String, init: ByteArray, nHost: ByteArray): Pair<ByteArray, Session> {
+ require(nHost.size == NONCE_LEN)
+ val (nPhone, tag) = parseHandshake(init, T_INIT)
+ val auth = kAuth(k)
+ if (!macOk(auth, tag, "init".toByteArray(), room.toByteArray(), nPhone)) throw ChannelException(Failure.BAD_TAG)
+ val reply = hmac(auth.bytes, "accept".toByteArray(), room.toByteArray(), nPhone, nHost)
+ val (p2h, h2p) = sessionKeys(k, nPhone, nHost)
+ return (header(T_ACCEPT, 0) + nHost + reply) to Session(Dir.HOST_TO_PHONE, room, p2h, h2p)
+ }
+
+ /** The phone's side: checks that the `accept` answers **its current** nonce, and returns the session. */
+ fun finishHandshake(k: PairingKey, room: String, nPhone: ByteArray, accept: ByteArray): Session {
+ val (nHost, tag) = parseHandshake(accept, T_ACCEPT)
+ if (!macOk(kAuth(k), tag, "accept".toByteArray(), room.toByteArray(), nPhone, nHost)) throw ChannelException(Failure.BAD_TAG)
+ val (p2h, h2p) = sessionKeys(k, nPhone, nHost)
+ return Session(Dir.PHONE_TO_HOST, room, p2h, h2p)
+ }
+
+ // ── the session ─────────────────────────────────────────────────────────────
+
+ /** One connection's keys and counters. Not thread safe: one reader and one writer thread should each use their own call path under a lock. */
+ class Session internal constructor(private val me: Dir, private val room: String, p2h: Secret, h2p: Secret) {
+ internal val sendKey: Secret = if (me == Dir.PHONE_TO_HOST) p2h else h2p
+ internal val recvKey: Secret = if (me == Dir.PHONE_TO_HOST) h2p else p2h
+ private var sendCounter = 0L
+ private var recvNext = 0L
+ private var sendDone = false
+ private var faulted = false
+
+ /** The next counter this side will send (carries no secret). */
+
+ /** Encrypts one protocol v1 line (UTF-8 JSON, without the newline) into a binary frame. */
+ @Synchronized fun seal(line: ByteArray): ByteArray {
+ if (faulted) throw ChannelException(Failure.FAULTED)
+ if (line.size > MAX_LINE) throw ChannelException(Failure.TOO_LONG)
+ if (sendDone) throw ChannelException(Failure.EXHAUSTED)
+ val counter = sendCounter
+ val frame = sealWith(sendKey.bytes, room, me, counter, line)
+ if (counter == LAST_COUNTER) sendDone = true else sendCounter++
+ return frame
+ }
+
+ /** Decrypts a binary frame from the other side. The counter must be exactly the next one. Any error ends the session. */
+ @Synchronized fun open(frame: ByteArray): ByteArray {
+ if (faulted) throw ChannelException(Failure.FAULTED)
+ try {
+ if (frame.size > MAX_FRAME) throw ChannelException(Failure.TOO_LONG)
+ if (frame.size < HEADER + TAG || frame[0].toInt() != VER || frame[1].toInt() != T_DATA) throw ChannelException(Failure.BAD_HEADER)
+ val counter = ByteBuffer.wrap(frame, 2, 8).long
+ if (counter != recvNext || counter < 0 || counter > LAST_COUNTER) throw ChannelException(Failure.BAD_COUNTER)
+ val line = openWith(recvKey.bytes, room, if (me == Dir.PHONE_TO_HOST) Dir.HOST_TO_PHONE else Dir.PHONE_TO_HOST, frame)
+ recvNext = counter + 1
+ return line
+ } catch (e: ChannelException) {
+ faulted = true
+ throw e
+ }
+ }
+
+ /** Tests only: makes the next frame carry this counter (to reach the last counter without sending 2^32 frames). */
+ @Synchronized internal fun forceSendCounterForTest(counter: Long) {
+ sendCounter = counter
+ }
+
+ /** Wipes the keys; the session is unusable afterwards. */
+ @Synchronized fun wipe() {
+ sendKey.wipe()
+ recvKey.wipe()
+ faulted = true
+ }
+
+ override fun toString() = "Session(..)"
+ }
+
+ /** 4-byte length, the line, then zeros up to a multiple of 128 bytes (at least 128). */
+ internal fun pad(line: ByteArray): ByteArray {
+ val raw = 4 + line.size
+ val total = maxOf(1, (raw + BLOCK - 1) / BLOCK) * BLOCK
+ return ByteBuffer.allocate(total).putInt(line.size).put(line).array()
+ }
+
+ private fun unpad(plain: ByteArray): ByteArray {
+ if (plain.size < BLOCK || plain.size % BLOCK != 0) throw ChannelException(Failure.BAD_PADDING)
+ val n = ByteBuffer.wrap(plain, 0, 4).int
+ if (n < 0 || n > MAX_LINE || 4 + n > plain.size || (4 + n until plain.size).any { plain[it] != 0.toByte() }) throw ChannelException(Failure.BAD_PADDING)
+ return plain.copyOfRange(4, 4 + n)
+ }
+
+ private fun cipher(mode: Int, key: ByteArray, nonce: ByteArray, aad: ByteArray): Cipher =
+ Cipher.getInstance("AES/GCM/NoPadding").apply {
+ init(mode, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
+ updateAAD(aad)
+ }
+
+ /** Encrypts at an explicit counter. The session guarantees it is never reused; tests use it for the vectors. */
+ internal fun sealWith(key: ByteArray, room: String, dir: Dir, counter: Long, line: ByteArray): ByteArray {
+ val h = header(T_DATA, counter)
+ val body = cipher(Cipher.ENCRYPT_MODE, key, nonceFor(dir, counter), aad(room, dir, h)).doFinal(pad(line))
+ return h + body
+ }
+
+ /** The header is already checked by the caller; verifies the tag under the direction's key and unpads. */
+ internal fun openWith(key: ByteArray, room: String, dir: Dir, frame: ByteArray): ByteArray {
+ val h = frame.copyOfRange(0, HEADER)
+ val counter = ByteBuffer.wrap(h, 2, 8).long
+ val plain = try {
+ cipher(Cipher.DECRYPT_MODE, key, nonceFor(dir, counter), aad(room, dir, h)).doFinal(frame, HEADER, frame.size - HEADER)
+ } catch (e: GeneralSecurityException) {
+ throw ChannelException(Failure.BAD_TAG)
+ }
+ try {
+ return unpad(plain)
+ } finally {
+ plain.fill(0)
+ }
+ }
+
+ // ── base64url (no padding), strict ──────────────────────────────────────────
+
+ private const val B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+
+ fun base64UrlEncode(bytes: ByteArray): String {
+ val sb = StringBuilder()
+ var i = 0
+ while (i < bytes.size) {
+ val b0 = bytes[i].toInt() and 0xff
+ val b1 = if (i + 1 < bytes.size) bytes[i + 1].toInt() and 0xff else 0
+ val b2 = if (i + 2 < bytes.size) bytes[i + 2].toInt() and 0xff else 0
+ val n = (b0 shl 16) or (b1 shl 8) or b2
+ sb.append(B64[(n shr 18) and 63]).append(B64[(n shr 12) and 63])
+ if (i + 1 < bytes.size) sb.append(B64[(n shr 6) and 63])
+ if (i + 2 < bytes.size) sb.append(B64[n and 63])
+ i += 3
+ }
+ return sb.toString()
+ }
+
+ /** Only the 64 URL-safe characters, no padding, and the unused trailing bits must be zero. */
+ fun base64UrlDecode(text: String): ByteArray? {
+ if (text.length % 4 == 1) return null
+ val out = java.io.ByteArrayOutputStream()
+ var i = 0
+ while (i < text.length) {
+ val chunk = text.substring(i, minOf(i + 4, text.length))
+ var n = 0
+ for ((j, c) in chunk.withIndex()) {
+ val v = B64.indexOf(c)
+ if (v < 0) return null
+ n = n or (v shl (18 - 6 * j))
+ }
+ val take = chunk.length * 6 / 8
+ val unusedBits = chunk.length * 6 - take * 8
+ if (unusedBits > 0 && ((n shr (24 - chunk.length * 6)) and ((1 shl unusedBits) - 1)) != 0) return null
+ for (k in 0 until take) out.write((n shr (16 - 8 * k)) and 0xff)
+ i += 4
+ }
+ return out.toByteArray()
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/RelayLink.kt b/android/app/src/main/kotlin/com/coucou/android/link/RelayLink.kt
new file mode 100644
index 00000000..6ec40519
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/RelayLink.kt
@@ -0,0 +1,283 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.Socket
+import java.net.SocketTimeoutException
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+
+/**
+ * The relay half of a pairing link (docs/RELAY_LINK.md section 2): `relay`, `room`, `key` and `access`, present together
+ * or not at all. [key] is K and [access] is the relay's access key, both only ever kept encrypted by [SecureStore].
+ */
+data class RelayPairing(val url: String, val room: String, val key: String, val access: String) {
+ /** Never prints a secret: a log line or a crash report that formats a pairing shows nothing of it. */
+ override fun toString() = "RelayPairing(..)"
+
+ fun relayUrl(): RelayUrl? = RelayUrl.parse(url)
+ fun pairingKey(): RelayCrypto.PairingKey? = RelayCrypto.PairingKey.fromBase64Url(key)
+
+ companion object {
+ sealed class Parsed {
+ /** None of the four fields: a LAN-only link. */
+ object Absent : Parsed()
+ /** Some but not all, or one that is malformed: the whole link is refused. */
+ object Invalid : Parsed()
+ class Ok(val relay: RelayPairing) : Parsed()
+ }
+
+ fun isRoom(s: String) = s.length == 22 && RelayCrypto.base64UrlDecode(s)?.size == 16
+ fun isSecret(s: String) = s.length == 43 && RelayCrypto.base64UrlDecode(s)?.size == 32
+
+ fun fromQuery(q: Map<String, String>): Parsed {
+ val fields = listOf("relay", "room", "key", "access").map { q[it] }
+ if (fields.all { it == null }) return Parsed.Absent
+ val (url, room, key, access) = fields
+ if (url == null || room == null || key == null || access == null) return Parsed.Invalid
+ val parsed = RelayUrl.parse(url) ?: return Parsed.Invalid
+ if (!isRoom(room) || !isSecret(key) || !isSecret(access)) return Parsed.Invalid
+ return Parsed.Ok(RelayPairing(parsed.display, room, key, access))
+ }
+ }
+}
+
+/** Why the last attempt through the relay did not work, for the status line in Settings. */
+enum class RelayIssue { NONE, ACCESS_REFUSED, ROOM_TAKEN, RATE_LIMITED, UNREACHABLE, COMPUTER_AWAY }
+
+/**
+ * Connects to the computer through the user's relay: the WebSocket upgrade with the access key and the join proof, then the
+ * end-to-end handshake (`init`, `accept`), then an ordinary [Socket] whose lines are the v1 conversation, encrypted. The
+ * [LinkClient] on top is unchanged: it neither knows nor cares that the bytes go through a relay.
+ */
+class RelayConnector(
+ private val relay: RelayPairing,
+ private val sockets: (RelayUrl, Int) -> Socket = WsClient.defaultSockets,
+ /** How long to wait for the computer to answer `init` before giving up (the link retries with its backoff). */
+ private val answerTimeoutMs: Int = 15_000,
+ /** How often `init` is sent again while no answer has come (an answer can be missed if the computer joined just after). */
+ private val resendMs: Int = 4_000,
+) : Connector {
+ @Volatile var issue: RelayIssue = RelayIssue.NONE
+ private set
+
+ override fun connect(timeoutMs: Int): Socket {
+ val url = relay.relayUrl() ?: throw IOException("bad relay address")
+ val key = relay.pairingKey() ?: throw IOException("bad pairing key")
+ val ws = try {
+ WsClient.open(
+ url = url,
+ path = "/v1/room/${relay.room}?role=phone",
+ headers = listOf("Authorization" to "Bearer ${relay.access}"),
+ protocols = listOf(SUBPROTOCOL, "coucou.join.${RelayCrypto.joinProof(key)}"),
+ connectTimeoutMs = timeoutMs,
+ maxMessage = RelayCrypto.MAX_FRAME + 1024,
+ sockets = sockets,
+ )
+ } catch (e: WsHandshakeException) {
+ issue = when (e.status) {
+ 401, 403 -> RelayIssue.ACCESS_REFUSED
+ 429 -> RelayIssue.RATE_LIMITED
+ else -> RelayIssue.UNREACHABLE
+ }
+ throw e
+ } catch (e: IOException) {
+ issue = RelayIssue.UNREACHABLE
+ throw e
+ }
+ try {
+ val session = handshake(ws, key)
+ issue = RelayIssue.NONE
+ return RelayStreamSocket(ws, session)
+ } catch (e: Throwable) {
+ ws.close()
+ throw e
+ }
+ }
+
+ private fun handshake(ws: WsConnection, key: RelayCrypto.PairingKey): RelayCrypto.Session {
+ val deadline = System.nanoTime() + answerTimeoutMs * 1_000_000L
+ var nonce = RelayCrypto.freshNonce()
+ sendInit(ws, key, nonce)
+ while (true) {
+ val left = ((deadline - System.nanoTime()) / 1_000_000L).toInt()
+ if (left <= 0) {
+ issue = RelayIssue.COMPUTER_AWAY
+ throw IOException("the computer did not answer")
+ }
+ ws.setReadTimeout(minOf(left, resendMs))
+ val message = try {
+ ws.receive()
+ } catch (_: SocketTimeoutException) {
+ nonce = RelayCrypto.freshNonce() // still nobody: ask again with a fresh nonce
+ sendInit(ws, key, nonce)
+ continue
+ }
+ when (message) {
+ is WsMessage.Binary -> {
+ val frame = message.data
+ if (frame.size > 1 && frame[1].toInt() == RelayCrypto.T_ACCEPT) {
+ try {
+ return RelayCrypto.finishHandshake(key, relay.room, nonce, frame)
+ } catch (_: RelayCrypto.ChannelException) {
+ // An answer to an older init, or not from a holder of K: wait for the right one.
+ }
+ }
+ }
+ is WsMessage.Text -> if (RelayHints.parse(message.text) == RelayHints.Hint.ONLINE) {
+ nonce = RelayCrypto.freshNonce()
+ sendInit(ws, key, nonce)
+ }
+ is WsMessage.Closed -> {
+ issue = issueOf(message.reason)
+ throw IOException("the relay closed the connection")
+ }
+ }
+ }
+ }
+
+ /**
+ * Sends `init`. If the relay has already closed the connection, the write fails before the close frame is read, so the
+ * reason is fetched (briefly) to tell "the room is taken" from "the network dropped".
+ */
+ private fun sendInit(ws: WsConnection, key: RelayCrypto.PairingKey, nonce: ByteArray) {
+ try {
+ ws.sendBinary(RelayCrypto.initFrame(key, relay.room, nonce))
+ } catch (e: IOException) {
+ try {
+ ws.setReadTimeout(500)
+ val m = ws.receive()
+ if (m is WsMessage.Closed) issue = issueOf(m.reason)
+ } catch (_: IOException) {
+ }
+ throw e
+ }
+ }
+
+ private fun issueOf(reason: String) = when (reason) {
+ "join proof", "replaced" -> RelayIssue.ROOM_TAKEN
+ "access key changed" -> RelayIssue.ACCESS_REFUSED
+ else -> RelayIssue.UNREACHABLE
+ }
+
+ companion object {
+ const val SUBPROTOCOL = "coucou.v1"
+ }
+}
+
+/** The relay's text messages. They are hints for the status and the retry, never trusted for anything else. */
+object RelayHints {
+ enum class Hint { ONLINE, OFFLINE, OTHER }
+
+ fun parse(text: String): Hint = when (text) {
+ """{"peer":"online"}""" -> Hint.ONLINE
+ """{"peer":"offline"}""" -> Hint.OFFLINE
+ else -> Hint.OTHER
+ }
+}
+
+/**
+ * A [Socket] whose bytes are the encrypted v1 conversation through the relay. Whole lines are sealed and sent as one frame
+ * each; frames that arrive are opened and handed to the reader as lines. Any fault (a bad tag, a wrong counter, a close) ends
+ * the stream, and the [LinkClient] reconnects with a fresh handshake.
+ */
+class RelayStreamSocket(
+ private val ws: WsConnection,
+ private val session: RelayCrypto.Session,
+) : Socket() {
+ private val incoming = LinkedBlockingQueue<ByteArray>()
+ @Volatile private var closed = false
+ @Volatile private var timeoutMs = 0
+ private var pending: ByteArray = EMPTY
+ private var pendingAt = 0
+
+ private val reader = Thread({ pump() }, "coucou-relay-reader").apply { isDaemon = true; start() }
+
+ private fun pump() {
+ try {
+ while (!closed) {
+ when (val m = ws.receive()) {
+ is WsMessage.Binary -> incoming.put(session.open(m.data) + NEWLINE)
+ is WsMessage.Text -> if (RelayHints.parse(m.text) == RelayHints.Hint.OFFLINE) break // the computer left: the conversation is over
+ is WsMessage.Closed -> break
+ }
+ }
+ } catch (_: IOException) {
+ } catch (_: RelayCrypto.ChannelException) {
+ } finally {
+ closed = true
+ incoming.put(END)
+ }
+ }
+
+ private val input = object : InputStream() {
+ override fun read(): Int {
+ val one = ByteArray(1)
+ return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xFF
+ }
+
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ if (len == 0) return 0
+ if (pendingAt >= pending.size) {
+ val next = if (timeoutMs > 0) incoming.poll(timeoutMs.toLong(), TimeUnit.MILLISECONDS) ?: throw SocketTimeoutException("read timed out") else incoming.take()
+ if (next === END) {
+ incoming.put(END) // stays ended for later reads
+ return -1
+ }
+ pending = next
+ pendingAt = 0
+ }
+ val n = minOf(len, pending.size - pendingAt)
+ System.arraycopy(pending, pendingAt, b, off, n)
+ pendingAt += n
+ return n
+ }
+ }
+
+ private val output = object : OutputStream() {
+ private val line = java.io.ByteArrayOutputStream()
+
+ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
+
+ @Synchronized override fun write(b: ByteArray, off: Int, len: Int) {
+ if (closed) throw IOException("the relay connection is closed")
+ for (i in off until off + len) {
+ if (b[i] == '\n'.code.toByte()) {
+ val text = line.toByteArray()
+ line.reset()
+ try {
+ ws.sendBinary(session.seal(text))
+ } catch (e: RelayCrypto.ChannelException) {
+ throw IOException("could not seal a line (${e.failure})")
+ }
+ } else {
+ if (line.size() >= RelayCrypto.MAX_LINE) throw IOException("line too long")
+ line.write(b[i].toInt())
+ }
+ }
+ }
+ }
+
+ override fun getInputStream(): InputStream = input
+ override fun getOutputStream(): OutputStream = output
+ override fun setSoTimeout(timeout: Int) { timeoutMs = timeout }
+ override fun getSoTimeout(): Int = timeoutMs
+ override fun setTcpNoDelay(on: Boolean) {}
+ override fun isConnected(): Boolean = !closed
+ override fun isClosed(): Boolean = closed
+
+ @Synchronized override fun close() {
+ if (closed && !reader.isAlive) return
+ closed = true
+ runCatching { ws.close() }
+ session.wipe()
+ incoming.put(END)
+ }
+
+ private companion object {
+ val EMPTY = ByteArray(0)
+ val END = ByteArray(0)
+ val NEWLINE = byteArrayOf('\n'.code.toByte())
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/Transport.kt b/android/app/src/main/kotlin/com/coucou/android/link/Transport.kt
new file mode 100644
index 00000000..c95281f3
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/Transport.kt
@@ -0,0 +1,128 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.net.Socket
+
+/** Which way the link reaches the computer. */
+enum class Route { LAN, RELAY }
+
+/**
+ * The rules for choosing between the direct link on the local network (fast, private to the network) and the relay
+ * (works from anywhere). Pure: the clock is injected, so the rules are tested without a network.
+ *
+ * - Without a relay, only the LAN is ever tried.
+ * - With one, the LAN is tried first with a short timeout, and the relay only when the LAN did not answer.
+ * - Having just found the LAN unreachable, the next reconnects go to the relay first for [LAN_SKIP_MS] (so a phone that is away
+ * does not wait out a LAN timeout every time), with the LAN as the fallback if the relay fails too.
+ * - While connected through the relay, the LAN is tried again every [LAN_PROBE_MS] and the link moves back to it.
+ */
+class TransportPolicy(
+ private val relayConfigured: () -> Boolean,
+ private val clockMs: () -> Long = System::currentTimeMillis,
+) {
+ @Volatile private var lanFailedAt: Long = NEVER
+ /** The routes to try now, in order. */
+ fun order(): List<Route> {
+ if (!relayConfigured()) return listOf(Route.LAN)
+ val recently = lanFailedAt != NEVER && clockMs() - lanFailedAt in 0 until LAN_SKIP_MS
+ return if (recently) listOf(Route.RELAY, Route.LAN) else listOf(Route.LAN, Route.RELAY)
+ }
+
+ /** How long the LAN gets before it counts as failed: shorter when there is a relay to fall back on. */
+ fun lanTimeoutMs(requestedMs: Int): Int = if (relayConfigured()) minOf(requestedMs, LAN_FAST_MS) else requestedMs
+
+ fun lanFailed() { lanFailedAt = clockMs() }
+ fun lanWorked() { lanFailedAt = NEVER }
+
+ companion object {
+ const val LAN_FAST_MS = 2_500
+ const val LAN_SKIP_MS = 60_000L
+ const val LAN_PROBE_MS = 90_000L
+ private const val NEVER = Long.MIN_VALUE
+ }
+}
+
+/**
+ * The [Connector] the [LinkClient] uses when a pairing has a relay: tries the routes in the policy's order, and while on the
+ * relay looks for the LAN from time to time and moves back to it. [onRoute] says which way is in use (for the status line).
+ */
+class FallbackConnector(
+ private val lan: Connector,
+ private val relay: Connector,
+ private val policy: TransportPolicy,
+ private val onRoute: (Route) -> Unit = {},
+ private val probeEveryMs: Long = TransportPolicy.LAN_PROBE_MS,
+ private val probeTimeoutMs: Int = TransportPolicy.LAN_FAST_MS,
+) : Connector {
+ @Volatile var route: Route? = null
+ private set
+ @Volatile private var probe: Thread? = null
+ @Volatile private var relaySocket: Socket? = null
+
+ override fun connect(timeoutMs: Int): Socket {
+ var failure: IOException? = null
+ for (r in policy.order()) {
+ try {
+ val s = when (r) {
+ Route.LAN -> lan.connect(policy.lanTimeoutMs(timeoutMs)).also { policy.lanWorked() }
+ Route.RELAY -> relay.connect(timeoutMs)
+ }
+ route = r
+ onRoute(r)
+ if (r == Route.RELAY) {
+ relaySocket = s
+ watchForLan(s)
+ }
+ return s
+ } catch (e: IOException) {
+ if (r == Route.LAN) policy.lanFailed()
+ failure = failure ?: e
+ }
+ }
+ throw failure ?: IOException("no route")
+ }
+
+ /** While [relaySocket] is open, tries the LAN every so often; when it answers, drops the relay so the link reconnects direct. */
+ private fun watchForLan(relaySocket: Socket) {
+ probe?.interrupt()
+ probe = Thread({
+ try {
+ while (!relaySocket.isClosed) {
+ Thread.sleep(probeEveryMs)
+ if (relaySocket.isClosed) break
+ if (lanAnswers()) {
+ policy.lanWorked()
+ runCatching { relaySocket.close() }
+ break
+ }
+ }
+ } catch (_: InterruptedException) {
+ }
+ }, "coucou-lan-probe").apply { isDaemon = true; start() }
+ }
+
+ /** One bare attempt at the LAN link (the pinned TLS handshake), closed again at once. */
+ fun lanAnswers(): Boolean = try {
+ lan.connect(probeTimeoutMs).close()
+ true
+ } catch (_: IOException) {
+ false
+ }
+
+ /** The network changed while on the relay: look for the LAN now instead of waiting for the next probe. */
+ fun networkChanged() {
+ val s = relaySocket ?: return
+ if (s.isClosed) return
+ Thread({
+ if (!s.isClosed && lanAnswers()) {
+ policy.lanWorked()
+ runCatching { s.close() } // the link reconnects, and tries the LAN first
+ }
+ }, "coucou-lan-check").apply { isDaemon = true; start() }
+ }
+
+ fun stop() {
+ probe?.interrupt()
+ probe = null
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/link/WebSocket.kt b/android/app/src/main/kotlin/com/coucou/android/link/WebSocket.kt
new file mode 100644
index 00000000..70203178
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/link/WebSocket.kt
@@ -0,0 +1,389 @@
+package com.coucou.android.link
+
+import java.io.ByteArrayOutputStream
+import java.io.Closeable
+import java.io.EOFException
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.nio.ByteBuffer
+import java.nio.charset.CharacterCodingException
+import java.nio.charset.CodingErrorAction
+import java.security.MessageDigest
+import java.security.SecureRandom
+import javax.net.ssl.SSLParameters
+import javax.net.ssl.SSLSocket
+import javax.net.ssl.SSLSocketFactory
+
+/**
+ * A small WebSocket client (RFC 6455), written for exactly one job: the link to the user's own relay
+ * (docs/RELAY_LINK.md). It has no dependency, speaks only what the relay needs (binary and text messages,
+ * ping/pong, close, fragmentation) and refuses everything else. It was chosen over a library so that the app's
+ * dependency list does not grow for the one feature that opens a connection to the internet (decision D2 of
+ * android/RELAY_PLAN.md); OkHttp stays the fallback if this ever proves unreliable.
+ *
+ * The decoder never allocates more than [WsDecoder.maxMessage] bytes, whatever a frame header claims, and any rule
+ * broken by the other side ends the connection with [WsProtocolException].
+ */
+
+class WsProtocolException(message: String) : IOException(message)
+
+/** The upgrade was refused or answered wrongly. [status] is the HTTP status when there was one (401: access key, 429: rate limit, …). */
+class WsHandshakeException(val status: Int, message: String) : IOException(message)
+
+object WsOpcode {
+ const val CONTINUATION = 0x0
+ const val TEXT = 0x1
+ const val BINARY = 0x2
+ const val CLOSE = 0x8
+ const val PING = 0x9
+ const val PONG = 0xA
+}
+
+sealed class WsMessage {
+ class Binary(val data: ByteArray) : WsMessage()
+ class Text(val text: String) : WsMessage()
+ /** The other side closed (or the connection ended cleanly). [code] is null when none was sent. */
+ class Closed(val code: Int?, val reason: String) : WsMessage()
+}
+
+/** What the decoder found: either a message to hand on, a control frame to answer, or the end. */
+sealed class WsEvent {
+ class Message(val message: WsMessage) : WsEvent()
+ class Ping(val payload: ByteArray) : WsEvent()
+ object Pong : WsEvent()
+}
+
+object WsFrames {
+ /** One complete, unfragmented, masked client frame. */
+ fun encode(opcode: Int, payload: ByteArray, mask: ByteArray): ByteArray {
+ require(mask.size == 4) { "a mask is 4 bytes" }
+ require(opcode == WsOpcode.TEXT || opcode == WsOpcode.BINARY || opcode in WsOpcode.CLOSE..WsOpcode.PONG) { "opcode $opcode" }
+ require(opcode < WsOpcode.CLOSE || payload.size <= 125) { "a control frame carries at most 125 bytes" }
+ val out = ByteArrayOutputStream(payload.size + 14)
+ out.write(0x80 or opcode)
+ when {
+ payload.size < 126 -> out.write(0x80 or payload.size)
+ payload.size <= 0xFFFF -> {
+ out.write(0x80 or 126)
+ out.write(payload.size ushr 8)
+ out.write(payload.size and 0xFF)
+ }
+ else -> {
+ out.write(0x80 or 127)
+ val n = payload.size.toLong()
+ for (shift in 56 downTo 0 step 8) out.write(((n ushr shift) and 0xFF).toInt())
+ }
+ }
+ out.write(mask)
+ val masked = ByteArray(payload.size) { (payload[it].toInt() xor mask[it and 3].toInt()).toByte() }
+ out.write(masked)
+ return out.toByteArray()
+ }
+
+ fun closePayload(code: Int, reason: String = ""): ByteArray {
+ val r = reason.toByteArray(Charsets.UTF_8).let { if (it.size > 123) it.copyOf(123) else it }
+ return byteArrayOf((code ushr 8).toByte(), code.toByte()) + r
+ }
+}
+
+/** Reads server frames. Not thread-safe: one reader. */
+class WsDecoder(private val input: InputStream, val maxMessage: Int) {
+ private var fragments: ByteArrayOutputStream? = null
+ private var fragmentOpcode = 0
+
+ private fun readFully(n: Int): ByteArray {
+ val buf = ByteArray(n)
+ var got = 0
+ while (got < n) {
+ val r = input.read(buf, got, n - got)
+ if (r < 0) throw EOFException("the connection ended")
+ got += r
+ }
+ return buf
+ }
+
+ private fun readByte(): Int {
+ val b = input.read()
+ if (b < 0) throw EOFException("the connection ended")
+ return b
+ }
+
+ /** Blocks for the next event. Throws [EOFException] when the stream ends, [WsProtocolException] when the server breaks a rule. */
+ fun next(): WsEvent {
+ while (true) {
+ val b0 = readByte()
+ val b1 = readByte()
+ val fin = b0 and 0x80 != 0
+ if (b0 and 0x70 != 0) throw WsProtocolException("reserved bits set")
+ val opcode = b0 and 0x0F
+ if (b1 and 0x80 != 0) throw WsProtocolException("a server frame must not be masked")
+ var length = (b1 and 0x7F).toLong()
+ if (length == 126L) {
+ length = ((readByte() shl 8) or readByte()).toLong()
+ } else if (length == 127L) {
+ length = 0
+ for (i in 0 until 8) length = (length shl 8) or readByte().toLong()
+ if (length < 0) throw WsProtocolException("length out of range")
+ }
+ val control = opcode >= WsOpcode.CLOSE
+ if (control && (!fin || length > 125)) throw WsProtocolException("bad control frame")
+ if (opcode != WsOpcode.CONTINUATION && opcode != WsOpcode.TEXT && opcode != WsOpcode.BINARY && !control) {
+ throw WsProtocolException("unknown opcode")
+ }
+ if (control && opcode !in WsOpcode.CLOSE..WsOpcode.PONG) throw WsProtocolException("unknown opcode")
+ // Checked before anything is allocated or read: a header cannot make us buffer more than the limit.
+ val already = fragments?.size()?.toLong() ?: 0L
+ if (!control && already + length > maxMessage) throw WsProtocolException("message too large")
+ val payload = readFully(length.toInt())
+
+ when (opcode) {
+ WsOpcode.PING -> return WsEvent.Ping(payload)
+ WsOpcode.PONG -> return WsEvent.Pong
+ WsOpcode.CLOSE -> return WsEvent.Message(closeOf(payload))
+ WsOpcode.TEXT, WsOpcode.BINARY -> {
+ if (fragments != null) throw WsProtocolException("a new message started inside another")
+ if (fin) return WsEvent.Message(message(opcode, payload))
+ fragments = ByteArrayOutputStream().also { it.write(payload) }
+ fragmentOpcode = opcode
+ }
+ else -> { // continuation
+ val parts = fragments ?: throw WsProtocolException("continuation without a start")
+ parts.write(payload)
+ if (fin) {
+ fragments = null
+ return WsEvent.Message(message(fragmentOpcode, parts.toByteArray()))
+ }
+ }
+ }
+ }
+ }
+
+ private fun message(opcode: Int, payload: ByteArray): WsMessage =
+ if (opcode == WsOpcode.BINARY) WsMessage.Binary(payload) else WsMessage.Text(utf8(payload))
+
+ private fun closeOf(payload: ByteArray): WsMessage.Closed {
+ if (payload.isEmpty()) return WsMessage.Closed(null, "")
+ if (payload.size == 1) throw WsProtocolException("a close frame cannot carry one byte")
+ val code = ((payload[0].toInt() and 0xFF) shl 8) or (payload[1].toInt() and 0xFF)
+ val valid = code in 1000..1003 || code in 1007..1011 || code in 3000..4999
+ if (!valid) throw WsProtocolException("bad close code")
+ return WsMessage.Closed(code, utf8(payload.copyOfRange(2, payload.size)))
+ }
+
+ private fun utf8(bytes: ByteArray): String = try {
+ Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes)).toString()
+ } catch (_: CharacterCodingException) {
+ throw WsProtocolException("text is not valid UTF-8")
+ }
+}
+
+object WsHandshake {
+ private const val GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+ const val MAX_HEADER_BYTES = 8192
+
+ fun newKey(random: SecureRandom = SecureRandom()): String =
+ java.util.Base64.getEncoder().encodeToString(ByteArray(16).also(random::nextBytes))
+
+ fun acceptFor(key: String): String =
+ java.util.Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((key + GUID).toByteArray(Charsets.US_ASCII)))
+
+ /** The upgrade request. Header values may not contain line breaks. */
+ fun request(hostHeader: String, path: String, key: String, headers: List<Pair<String, String>>): ByteArray {
+ val all = listOf("Host" to hostHeader, "Upgrade" to "websocket", "Connection" to "Upgrade", "Sec-WebSocket-Key" to key, "Sec-WebSocket-Version" to "13") + headers
+ require(path.startsWith("/") && path.none { it == '\r' || it == '\n' || it == ' ' }) { "bad path" }
+ val sb = StringBuilder("GET $path HTTP/1.1\r\n")
+ for ((name, value) in all) {
+ require(name.isNotEmpty() && (name + value).none { it == '\r' || it == '\n' || it == '\u0000' }) { "bad header" }
+ sb.append(name).append(": ").append(value).append("\r\n")
+ }
+ return sb.append("\r\n").toString().toByteArray(Charsets.US_ASCII)
+ }
+
+ /**
+ * Reads the response up to the blank line (byte by byte, so no frame data is swallowed) and checks it. Returns the
+ * sub-protocol the server chose. Anything but a correct 101 throws [WsHandshakeException] with the status.
+ */
+ fun readResponse(input: InputStream, key: String, offeredProtocols: Set<String>): String? {
+ val head = ByteArrayOutputStream()
+ var last4 = 0
+ while (true) {
+ val b = input.read()
+ if (b < 0) throw WsHandshakeException(0, "the connection ended during the upgrade")
+ head.write(b)
+ if (head.size() > MAX_HEADER_BYTES) throw WsHandshakeException(0, "the response is too long")
+ last4 = (last4 shl 8) or b
+ if (last4 == 0x0D0A0D0A) break
+ }
+ val lines = head.toString(Charsets.ISO_8859_1.name()).split("\r\n").filter { it.isNotEmpty() }
+ val status = lines.firstOrNull()?.split(" ")?.takeIf { it.size >= 2 && it[0].startsWith("HTTP/1.") }?.get(1)?.toIntOrNull()
+ ?: throw WsHandshakeException(0, "not an HTTP response")
+ if (status != 101) throw WsHandshakeException(status, "the upgrade was refused ($status)")
+ val h = HashMap<String, String>()
+ for (line in lines.drop(1)) {
+ val i = line.indexOf(':')
+ if (i <= 0) throw WsHandshakeException(status, "bad header")
+ h[line.substring(0, i).trim().lowercase()] = line.substring(i + 1).trim()
+ }
+ if (h["upgrade"]?.lowercase() != "websocket") throw WsHandshakeException(status, "not a websocket upgrade")
+ if (h["connection"]?.lowercase()?.split(",")?.map { it.trim() }?.contains("upgrade") != true) throw WsHandshakeException(status, "not an upgrade")
+ if (h["sec-websocket-accept"] != acceptFor(key)) throw WsHandshakeException(status, "wrong accept value")
+ val chosen = h["sec-websocket-protocol"]
+ if (offeredProtocols.isNotEmpty() && chosen !in offeredProtocols) throw WsHandshakeException(status, "no agreed sub-protocol")
+ if (offeredProtocols.isEmpty() && chosen != null) throw WsHandshakeException(status, "unrequested sub-protocol")
+ if (h["sec-websocket-extensions"] != null) throw WsHandshakeException(status, "unrequested extension")
+ return chosen
+ }
+}
+
+/** An open connection. Sending is thread-safe; receiving is for one thread. */
+class WsConnection(
+ private val socket: Socket,
+ input: InputStream,
+ private val output: OutputStream,
+ maxMessage: Int,
+ private val random: SecureRandom = SecureRandom(),
+) : Closeable {
+ private val decoder = WsDecoder(input, maxMessage)
+ private val writeLock = Any()
+ @Volatile private var closeSent = false
+
+ private fun sendFrame(opcode: Int, payload: ByteArray) {
+ val mask = ByteArray(4).also(random::nextBytes)
+ val frame = WsFrames.encode(opcode, payload, mask)
+ synchronized(writeLock) {
+ output.write(frame)
+ output.flush()
+ }
+ }
+
+ fun sendBinary(data: ByteArray) = sendFrame(WsOpcode.BINARY, data)
+
+ /** Waits for the next binary or text message (pings are answered, pongs ignored). A close from the other side is returned once. */
+ fun receive(): WsMessage {
+ while (true) {
+ when (val e = decoder.next()) {
+ is WsEvent.Ping -> sendFrame(WsOpcode.PONG, e.payload)
+ WsEvent.Pong -> {}
+ is WsEvent.Message -> {
+ val m = e.message
+ if (m is WsMessage.Closed) {
+ runCatching { sendClose(m.code ?: 1000, "") }
+ }
+ return m
+ }
+ }
+ }
+ }
+
+ private fun sendClose(code: Int, reason: String) {
+ if (closeSent) return
+ closeSent = true
+ sendFrame(WsOpcode.CLOSE, WsFrames.closePayload(code, reason))
+ }
+
+ fun setReadTimeout(ms: Int) {
+ socket.soTimeout = ms
+ }
+
+ override fun close() {
+ runCatching { sendClose(1000, "") }
+ runCatching { socket.close() }
+ }
+}
+
+/** Where a relay is: the host and port of a `wss://` address (or `ws://` to this same computer, for tests and development). */
+data class RelayUrl(val tls: Boolean, val host: String, val port: Int) {
+ val display: String get() = "${if (tls) "wss" else "ws"}://$host" + if (port == (if (tls) 443 else 80)) "" else ":$port"
+
+ companion object {
+ /** Accepts only `wss://host[:port]`; `ws://` only to localhost. No path, query, fragment or credentials. */
+ fun parse(text: String): RelayUrl? {
+ val t = text.trim()
+ val tls = when {
+ t.startsWith("wss://") -> true
+ t.startsWith("ws://") -> false
+ else -> return null
+ }
+ var rest = t.substringAfter("://").removeSuffix("/")
+ if (rest.isEmpty() || rest.any { it in "/?#@ \\" || it.code < 0x21 || it.code > 0x7E }) return null
+ var port = if (tls) 443 else 80
+ val host: String
+ if (rest.startsWith("[")) {
+ val end = rest.indexOf(']')
+ if (end < 0) return null
+ host = rest.substring(0, end + 1)
+ val tail = rest.substring(end + 1)
+ if (tail.isNotEmpty()) port = tail.removePrefix(":").toIntOrNull() ?: return null
+ if (tail.isNotEmpty() && !tail.startsWith(":")) return null
+ if (host != "[::1]") return null
+ } else {
+ val colon = rest.lastIndexOf(':')
+ if (colon >= 0) {
+ port = rest.substring(colon + 1).toIntOrNull() ?: return null
+ rest = rest.substring(0, colon)
+ }
+ host = rest
+ if (host.isEmpty() || host.length > 253 || host.startsWith(".") || host.startsWith("-") || host.contains("..") ||
+ !host.all { it.isLetterOrDigit() && it.code < 0x80 || it == '.' || it == '-' }
+ ) return null
+ }
+ if (port !in 1..65535) return null
+ if (!tls && host != "localhost" && host != "127.0.0.1" && host != "[::1]") return null
+ return RelayUrl(tls, host, port)
+ }
+ }
+}
+
+object WsClient {
+ const val HANDSHAKE_TIMEOUT_MS = 10_000
+
+ /**
+ * Opens a WebSocket to [url] at [path] with the given extra headers. TLS uses the system's trust store and checks the
+ * host name. Throws [WsHandshakeException] when the server answers but refuses, [IOException] when it cannot be reached.
+ */
+ fun open(
+ url: RelayUrl,
+ path: String,
+ headers: List<Pair<String, String>>,
+ protocols: List<String>,
+ connectTimeoutMs: Int,
+ maxMessage: Int,
+ sockets: (RelayUrl, Int) -> Socket = ::defaultSocket,
+ ): WsConnection {
+ val socket = sockets(url, connectTimeoutMs)
+ try {
+ socket.soTimeout = HANDSHAKE_TIMEOUT_MS
+ socket.tcpNoDelay = true
+ val key = WsHandshake.newKey()
+ val hostHeader = if (url.port == (if (url.tls) 443 else 80)) url.host else "${url.host}:${url.port}"
+ val extra = headers + if (protocols.isEmpty()) emptyList() else listOf("Sec-WebSocket-Protocol" to protocols.joinToString(", "))
+ val out = socket.getOutputStream()
+ out.write(WsHandshake.request(hostHeader, path, key, extra))
+ out.flush()
+ val input = java.io.BufferedInputStream(socket.getInputStream())
+ WsHandshake.readResponse(input, key, if (protocols.isEmpty()) emptySet() else setOf(protocols.first()))
+ return WsConnection(socket, input, out, maxMessage)
+ } catch (e: Throwable) {
+ runCatching { socket.close() }
+ throw e
+ }
+ }
+
+ val defaultSockets: (RelayUrl, Int) -> Socket = ::defaultSocket
+
+ private fun defaultSocket(url: RelayUrl, timeoutMs: Int): Socket {
+ val raw = Socket()
+ raw.connect(InetSocketAddress(url.host.trim('[', ']'), url.port), timeoutMs)
+ if (!url.tls) return raw
+ val tls = (SSLSocketFactory.getDefault() as SSLSocketFactory).createSocket(raw, url.host, url.port, true) as SSLSocket
+ tls.enabledProtocols = tls.supportedProtocols.filter { it == "TLSv1.3" || it == "TLSv1.2" }.toTypedArray()
+ tls.sslParameters = tls.sslParameters.also { p: SSLParameters -> p.endpointIdentificationAlgorithm = "HTTPS" }
+ tls.soTimeout = HANDSHAKE_TIMEOUT_MS
+ tls.startHandshake()
+ return tls
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/MochiEngine.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiEngine.kt
new file mode 100644
index 00000000..79e4fd4e
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiEngine.kt
@@ -0,0 +1,591 @@
+package com.coucou.android.mochi
+
+import com.coucou.android.mochi.outfit.Outfit
+import com.coucou.android.core.Ease
+import com.coucou.android.core.EaseFn
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+import kotlin.random.Random
+
+/**
+ * Mochi's animation state machine: a port of windows/src/mochi/engine.ts (itself a port of
+ * BotEngine.swift). Same constants, tweens, easings and particles. Drawing lives in
+ * MochiPainter; this class has no Android dependency so it runs in plain JVM unit tests.
+ *
+ * Not ported yet: outfits (wardrobe), which the author's assets cover but are a later phase.
+ */
+fun interface SoundSink { fun play(name: String) }
+
+enum class Prop { YAW, PITCH, ROLL, TILT, OPEN, SX, SY, OY, OX, TINT, MORPH, HANDS, BLUSH, ES, BADGE_S, OUTFIT_PRESENCE }
+
+class TweenKey(val target: Double, val durationMs: Double, val ease: EaseFn)
+
+enum class ParticleType { HEART, STAR, SPARK, SWEAT, Z }
+
+class Particle(
+ val type: ParticleType,
+ val x: Double, val y: Double, val vx: Double, val vy: Double,
+ var age: Double, val life: Double, val rot: Double, val size: Double,
+)
+
+private class Tween(
+ val prop: Prop,
+ val keys: List<TweenKey>,
+ var index: Int,
+ var from: Double,
+ var startMs: Double,
+ val onComplete: (() -> Unit)?,
+)
+
+private class Scheduled(val dueMs: Double, val action: () -> Unit)
+
+class MochiEngine(
+ /** Monotonic clock in milliseconds (performance.now() in the TS port). */
+ private val clockMs: () -> Double,
+ private val random: Random = Random.Default,
+ private val sound: SoundSink = SoundSink { },
+) {
+ var isMini = false
+ /** Solid body colour for mini bots (null = Mochi gradient). */
+ var bodyColor: Rgb? = null
+
+ // Animated state (BotEngine `s`)
+ var yaw = 0.0; var pitch = 0.0; var roll = 0.0; var tilt = 0.0; var open = 1.0
+ var sx = 1.0; var sy = 1.0; var oy = 0.0; var ox = 0.0
+ var tint = 0.0; var morph = 0.0; var hands = 0.0; var blush = 0.0; var es = 1.0; var badgeS = 0.0
+
+ // Outfit (the main Mochi only: minis never wear one). `outfit` is what is drawn; it changes only once the previous one has left.
+ var outfit: Outfit = Outfit.NONE
+ private set
+ /** 0 = gone, 1 = fully on. */
+ var outfitPresence = 0.0
+ private var outfitTarget: Outfit = Outfit.NONE
+
+ // Spring lag of the soft parts (pompoms, hat tips, scarf end), -1..1.
+ var physDx = 0.0
+ var physDy = 0.0
+ private var physVx = 0.0
+ private var physVy = 0.0
+ private var prevYaw = 0.0
+ private var prevOy = 0.0
+ private var prevRoll = 0.0
+
+ var tgYaw = 0.0; var tgPitch = 0.0; var tgTilt = 0.0; var tgSy = 1.0; var tgSx = 1.0; var tgEs = 1.0
+
+ /** Extra canvas height above the body so hearts can fly out without clipping. */
+ var particleOverhang = 0.0
+
+ // Mouth spring (fraction of R)
+ var slotH = 0.0; var slotHTarget = 0.0; var slotHVel = 0.0; var isChewing = false
+
+ var col: Rgb = MochiConst.C_IDLE
+ var colT: Rgb = MochiConst.C_IDLE
+
+ var state: BotState = BotState.IDLE
+ private set
+ var cfg: BotStateCfg = MochiConst.STATES.getValue(BotState.IDLE)
+ private set
+
+ var eyeOverride: EyeShape? = null
+ var eyeOverrideUntil = 0.0
+ var permanentEye: EyeShape? = null
+ var permanentEmote: BotEmote? = null
+ private set
+ var miniNextBehavior = 0.0
+
+ var badge: Badge? = null
+ private set
+ private var badgeKey = "none"
+ private var badgeToken = 0
+
+ private val tweens = LinkedHashMap<Prop, Tween>()
+ private val locks = HashSet<Prop>()
+ private val scheduled = ArrayList<Scheduled>()
+ private var _particles = ArrayList<Particle>()
+ val particles: List<Particle> get() = _particles
+
+ var lookX = 0.0
+ var lookY = 0.0
+
+ private val t0 = now() - random.nextDouble() * 5
+ private var nextBlink = now() + 1.5 + random.nextDouble() * 2
+ var waveUntil = 0.0
+ var waveStart = 0.0
+ private var greetToken = 0
+ private var lastAmbient = 0.0
+ private var slapTimes = ArrayList<Double>()
+ private var miniLookX = 0.0
+ private var miniLookY = 0.0
+ private var miniLookNextTime = 0.0
+
+ /** Fired when three slaps land inside 1.7 s (dizzy + confused view). */
+ var onDizzy: (() -> Unit)? = null
+
+ private fun now(): Double = clockMs() / 1000.0
+
+ private fun get(p: Prop): Double = when (p) {
+ Prop.YAW -> yaw; Prop.PITCH -> pitch; Prop.ROLL -> roll; Prop.TILT -> tilt
+ Prop.OPEN -> open; Prop.SX -> sx; Prop.SY -> sy; Prop.OY -> oy; Prop.OX -> ox
+ Prop.TINT -> tint; Prop.MORPH -> morph; Prop.HANDS -> hands; Prop.BLUSH -> blush
+ Prop.ES -> es; Prop.BADGE_S -> badgeS; Prop.OUTFIT_PRESENCE -> outfitPresence
+ }
+
+ private fun set(p: Prop, v: Double) {
+ when (p) {
+ Prop.YAW -> yaw = v; Prop.PITCH -> pitch = v; Prop.ROLL -> roll = v; Prop.TILT -> tilt = v
+ Prop.OPEN -> open = v; Prop.SX -> sx = v; Prop.SY -> sy = v; Prop.OY -> oy = v; Prop.OX -> ox = v
+ Prop.TINT -> tint = v; Prop.MORPH -> morph = v; Prop.HANDS -> hands = v; Prop.BLUSH -> blush = v
+ Prop.ES -> es = v; Prop.BADGE_S -> badgeS = v; Prop.OUTFIT_PRESENCE -> outfitPresence = v
+ }
+ }
+
+ private fun after(delayMs: Double, action: () -> Unit) {
+ scheduled.add(Scheduled(clockMs() + delayMs, action))
+ }
+
+ private fun keys(vararg k: Triple<Double, Double, EaseFn>) = k.map { TweenKey(it.first, it.second, it.third) }
+
+ // ── Public API ──────────────────────────────────────────────────────────────
+
+ fun setState(next: BotState, force: Boolean = false) {
+ if (state == next && !force) return
+ val prev = state
+ state = next
+ cfg = MochiConst.STATES.getValue(next)
+ colT = cfg.color
+ if (Prop.TINT !in locks) tint = cfg.tint
+ if (Prop.TILT !in locks) tgTilt = cfg.tilt
+ setBadge(cfg.badge)
+
+ when (next) {
+ BotState.FINISHED -> {
+ doRoll(950.0, 1)
+ after(500.0) { emit(ParticleType.SPARK, 5) }
+ }
+ BotState.ERROR -> anim(Prop.OX, keys(
+ Triple(0.08, 50.0, Ease.out), Triple(-0.08, 70.0, Ease.inOut),
+ Triple(0.05, 70.0, Ease.inOut), Triple(0.0, 90.0, Ease.out),
+ ))
+ BotState.APPROVAL -> anim(Prop.OY, keys(Triple(-0.2, 150.0, Ease.out), Triple(0.0, 300.0, Ease.back)))
+ BotState.DIZZY -> doRoll(1300.0, 2)
+ BotState.QUESTION -> blink()
+ BotState.RATELIMIT -> emit(ParticleType.SWEAT, 1)
+ else -> if (prev != BotState.IDLE || next != BotState.IDLE) blink()
+ }
+ }
+
+ fun setBadge(b: Badge?) {
+ val key = if (b != null) "${b.kind}-${b.color.r},${b.color.g},${b.color.b}" else "none"
+ if (key == badgeKey) return
+ badgeKey = key
+ val tok = ++badgeToken
+ anim(Prop.BADGE_S, keys(Triple(0.0, 90.0, Ease.inOut)))
+ after(100.0) {
+ if (tok != badgeToken) return@after
+ badge = b
+ if (b != null) anim(Prop.BADGE_S, keys(Triple(1.0, 280.0, Ease.back)))
+ }
+ }
+
+ fun blink() {
+ if (Prop.OPEN in locks) return
+ anim(Prop.OPEN, keys(Triple(0.06, 70.0, Ease.inOut), Triple(1.0, 130.0, Ease.out)))
+ }
+
+ fun squash() {
+ physVy += 0.6
+ anim(Prop.SY, keys(Triple(0.78, 70.0, Ease.out), Triple(1.1, 130.0, Ease.out), Triple(1.0, 170.0, Ease.inOut)))
+ anim(Prop.SX, keys(Triple(1.16, 70.0, Ease.out), Triple(0.95, 130.0, Ease.out), Triple(1.0, 170.0, Ease.inOut)))
+ }
+
+ /** Mailbox swallow: opens the slot, chews, then closes. */
+ fun gulp() {
+ slotHTarget = 0.42
+ after(460.0) {
+ slotHTarget = 0.0
+ isChewing = true
+ after(800.0) { isChewing = false }
+ }
+ anim(Prop.SY, keys(Triple(0.78, 80.0, Ease.out), Triple(1.18, 130.0, Ease.out), Triple(1.0, 220.0, Ease.back)))
+ anim(Prop.SX, keys(Triple(1.28, 80.0, Ease.out), Triple(0.92, 130.0, Ease.out), Triple(1.0, 220.0, Ease.back)))
+ blink()
+ }
+
+ fun slap() {
+ interruptGreet()
+ if (state == BotState.DIZZY) return
+ val t = now()
+ slapTimes = ArrayList(slapTimes.filter { t - it < 1.7 })
+ slapTimes.add(t)
+ sound.play("slap")
+ squash()
+ physVy -= 1.2
+ physVx += if (random.nextDouble() < 0.5) 0.7 else -0.7
+ if (slapTimes.size >= 3) {
+ slapTimes = ArrayList()
+ onDizzy?.invoke()
+ } else {
+ eyeOverride = EyeShape.LINE
+ eyeOverrideUntil = t + 0.8
+ after(60.0) { sound.play("annoyed") }
+ }
+ }
+
+ fun doRoll(durationMs: Double, turns: Int) {
+ roll = 0.0
+ anim(Prop.ROLL, keys(Triple(PI * 2 * turns, durationMs, Ease.inOut))) { roll = 0.0 }
+ }
+
+ /** Peek wave, the "coucou". Timings from BotEngine.greet(). */
+ fun greet() {
+ val t = now()
+ val tok = ++greetToken
+ waveStart = t + 0.45
+ waveUntil = t + 1.55
+ physVx += 0.2
+
+ eyeOverride = EyeShape.HAPPY
+ eyeOverrideUntil = t + 2.0
+ anim(Prop.OY, keys(Triple(-0.06, 220.0, Ease.out), Triple(0.0, 220.0, Ease.back)))
+
+ after(250.0) {
+ if (greetToken != tok) return@after
+ anim(Prop.HANDS, keys(Triple(1.0, 280.0, Ease.out)))
+ anim(Prop.SY, keys(Triple(0.95, 100.0, Ease.out), Triple(1.0, 260.0, Ease.back)))
+ anim(Prop.SX, keys(Triple(1.04, 100.0, Ease.out), Triple(1.0, 260.0, Ease.back)))
+ sound.play("greet")
+ }
+ after(550.0) { if (greetToken == tok) blink() }
+ after(1500.0) { if (greetToken == tok) blink() }
+ after(1550.0) {
+ if (greetToken != tok) return@after
+ waveUntil = 0.0
+ anim(Prop.HANDS, keys(Triple(0.0, 200.0, Ease.inOut)))
+ }
+ after(1750.0) {
+ if (greetToken != tok) return@after
+ eyeOverride = EyeShape.HAPPY
+ eyeOverrideUntil = now() + 0.3
+ }
+ }
+
+ fun interruptGreet() {
+ if (hands <= 0.01 && now() >= waveUntil) return
+ greetToken++
+ waveUntil = 0.0
+ waveStart = 0.0
+ anim(Prop.HANDS, keys(Triple(0.0, 150.0, Ease.inOut)))
+ }
+
+ fun setPermanentEmote(emote: BotEmote?) {
+ permanentEmote = emote
+ if (emote == BotEmote.WINK) {
+ miniNextBehavior = now() + 0.8 + random.nextDouble() * 1.7
+ return
+ }
+ permanentEye = emote?.let { MochiConst.EMOTE_EYE.getValue(it) }
+ if (permanentEye != null) {
+ eyeOverride = permanentEye
+ eyeOverrideUntil = Double.POSITIVE_INFINITY
+ } else if (eyeOverrideUntil == Double.POSITIVE_INFINITY) {
+ eyeOverride = null
+ eyeOverrideUntil = 0.0
+ }
+ miniNextBehavior = now() + 0.8 + random.nextDouble() * 1.7
+ }
+
+ fun triggerEmote(emote: BotEmote, duration: Double = 1.8) {
+ val t = now()
+ eyeOverride = MochiConst.EMOTE_EYE.getValue(emote)
+ eyeOverrideUntil = t + duration
+
+ when (emote) {
+ BotEmote.LOVE -> {
+ anim(Prop.BLUSH, keys(
+ Triple(1.0, 300.0, Ease.out), Triple(1.0, (duration - 0.6) * 1000, Ease.lin), Triple(0.0, 300.0, Ease.inOut),
+ ))
+ emit(ParticleType.HEART, 4)
+ anim(Prop.OY, keys(Triple(-0.1, 160.0, Ease.out), Triple(0.0, 300.0, Ease.back)))
+ }
+ BotEmote.SURPRISED -> {
+ anim(Prop.OY, keys(Triple(-0.3, 140.0, Ease.out), Triple(0.0, 380.0, Ease.back)))
+ anim(Prop.ES, keys(Triple(1.25, 120.0, Ease.out), Triple(1.0, 500.0, Ease.inOut)))
+ }
+ BotEmote.PROUD -> {
+ emit(ParticleType.STAR, 5)
+ anim(Prop.TILT, keys(
+ Triple(-0.14, 220.0, Ease.out), Triple(-0.14, (duration - 0.5) * 1000, Ease.lin), Triple(0.0, 280.0, Ease.inOut),
+ ))
+ anim(Prop.BLUSH, keys(
+ Triple(0.7, 250.0, Ease.out), Triple(0.7, (duration - 0.5) * 1000, Ease.lin), Triple(0.0, 300.0, Ease.inOut),
+ ))
+ }
+ BotEmote.WINK -> anim(Prop.TILT, keys(
+ Triple(0.12, 160.0, Ease.out), Triple(0.12, (duration - 0.4) * 1000, Ease.lin), Triple(0.0, 240.0, Ease.inOut),
+ ))
+ BotEmote.YAWN -> {
+ anim(Prop.SY, keys(Triple(1.12, 500.0, Ease.inOut), Triple(1.0, 500.0, Ease.inOut)))
+ anim(Prop.SX, keys(Triple(0.94, 500.0, Ease.inOut), Triple(1.0, 500.0, Ease.inOut)))
+ after(700.0) { eyeOverride = EyeShape.CLOSED; emit(ParticleType.Z, 2) }
+ }
+ BotEmote.HAPPY -> anim(Prop.BLUSH, keys(Triple(0.6, 200.0, Ease.out), Triple(0.0, 600.0, Ease.inOut)))
+ BotEmote.ANNOYED -> {
+ eyeOverride = EyeShape.LINE
+ eyeOverrideUntil = t + 0.8
+ after(60.0) { sound.play("annoyed") }
+ }
+ }
+ }
+
+ fun emit(type: ParticleType, count: Int) {
+ for (i in 0 until count) {
+ val isZ = type == ParticleType.Z
+ _particles.add(Particle(
+ type = type,
+ x = (random.nextDouble() - 0.5) * 0.9 + (if (isZ) 0.55 else 0.0),
+ y = -0.7 - random.nextDouble() * 0.2,
+ vx = (random.nextDouble() - 0.5) * 0.35 + (if (isZ) 0.18 else 0.0),
+ vy = -(0.45 + random.nextDouble() * 0.35),
+ age = -i * 0.14,
+ life = 1.3 + random.nextDouble() * 0.5,
+ rot = random.nextDouble() * PI * 2,
+ size = 0.15 + random.nextDouble() * 0.08,
+ ))
+ }
+ }
+
+ fun animateMorph(target: Double, durationMs: Double? = null) {
+ val dur = durationMs ?: if (target > 0.5) 550.0 else 650.0
+ anim(Prop.MORPH, keys(Triple(target, dur, Ease.inOut)))
+ }
+
+ /**
+ * Dresses Mochi. Animated: the old outfit leaves (180 ms), the new one drops in (350 ms) and Mochi does a
+ * little squash (BotEngine.setOutfit on the Mac, setOutfit in windows/src/mochi/engine.ts).
+ */
+ fun setOutfit(next: Outfit, animated: Boolean = true) {
+ if (next == outfitTarget) return
+ outfitTarget = next
+ tweens.remove(Prop.OUTFIT_PRESENCE)
+ locks.remove(Prop.OUTFIT_PRESENCE)
+ val enter = {
+ outfit = next
+ anim(Prop.OUTFIT_PRESENCE, keys(Triple(1.0, 350.0, Ease.inOut))) { squash() }
+ }
+ if (!animated) {
+ outfit = next
+ outfitPresence = if (next != Outfit.NONE) 1.0 else 0.0
+ } else if (next == Outfit.NONE) {
+ anim(Prop.OUTFIT_PRESENCE, keys(Triple(0.0, 180.0, Ease.inOut))) { outfit = Outfit.NONE }
+ } else if (outfit == Outfit.NONE) {
+ outfitPresence = 0.0
+ enter()
+ } else {
+ anim(Prop.OUTFIT_PRESENCE, keys(Triple(0.0, 180.0, Ease.inOut))) { enter() }
+ }
+ }
+
+ /** Wearing something visible: the body then turns as one piece when it rolls. */
+ val rigidRoll: Boolean get() = !isMini && outfit != Outfit.NONE && outfitPresence > 0.05
+
+ /** True while anything is still moving, so the host can stop its frame loop. */
+ val busy: Boolean
+ get() = tweens.isNotEmpty() || scheduled.isNotEmpty() || _particles.isNotEmpty() ||
+ cfg.bounces || cfg.scans || cfg.breathes || cfg.zz || cfg.sweat || isMini ||
+ abs(tgYaw - yaw) > 0.002 || abs(tgPitch - pitch) > 0.002 || abs(tgTilt - tilt) > 0.002 ||
+ abs(tgSy - sy) > 0.002 || abs(tgSx - sx) > 0.002 || abs(tgEs - es) > 0.002 ||
+ slotH > 0.001 || abs(slotHVel) > 0.001 ||
+ abs(col.r - colT.r) > 0.003 || abs(col.g - colT.g) > 0.003 || abs(col.b - colT.b) > 0.003 ||
+ (outfit != Outfit.NONE && (abs(physVx) > 0.01 || abs(physVy) > 0.01))
+
+ // ── Tweens ──────────────────────────────────────────────────────────────────
+
+ fun anim(prop: Prop, keys: List<TweenKey>, onComplete: (() -> Unit)? = null) {
+ tweens[prop] = Tween(prop, keys, 0, get(prop), clockMs(), onComplete)
+ locks.add(prop)
+ }
+
+ // ── Update ──────────────────────────────────────────────────────────────────
+
+ fun update(dt: Double) {
+ val n = now()
+ val nowMs = clockMs()
+
+ // Timers that setTimeout handled in the TS port.
+ if (scheduled.isNotEmpty()) {
+ val due = scheduled.filter { it.dueMs <= nowMs }
+ scheduled.removeAll(due.toSet())
+ due.sortedBy { it.dueMs }.forEach { it.action() }
+ }
+
+ for (tw in ArrayList(tweens.values)) {
+ val k = tw.keys[tw.index]
+ val p = min(1.0, max(0.0, (nowMs - tw.startMs) / k.durationMs))
+ set(tw.prop, tw.from + (k.target - tw.from) * k.ease(p))
+ if (p >= 1) {
+ tw.from = k.target
+ tw.index += 1
+ tw.startMs = nowMs
+ if (tw.index >= tw.keys.size) {
+ tweens.remove(tw.prop)
+ locks.remove(tw.prop)
+ tw.onComplete?.invoke()
+ }
+ }
+ }
+
+ val t = n - t0
+ var ty = lookX * 0.62
+ var tp = lookY * 0.5
+
+ cfg.look?.let { (lx, ly) ->
+ ty = ty * 0.35 + lx * 0.55
+ tp = tp * 0.3 + ly * 0.5
+ }
+ if (cfg.scans) {
+ ty = sin(t * 2.6) * 0.6
+ tp = -0.06
+ }
+ if (state == BotState.SLEEPING) { ty = 0.0; tp = -0.14 }
+ if (state == BotState.DIZZY) ty = sin(t * 9) * 0.25
+
+ // Mini bots never follow the pointer; they wander.
+ if (isMini && cfg.look == null && !cfg.scans && state != BotState.SLEEPING && state != BotState.DIZZY) {
+ if (n > miniLookNextTime) {
+ miniLookX = -0.88 + random.nextDouble() * 1.76
+ miniLookY = -0.55 + random.nextDouble() * 1.0
+ miniLookNextTime = n + 0.5 + random.nextDouble() * 1.5
+ }
+ ty = miniLookX * 0.62
+ tp = miniLookY * 0.5
+ }
+
+ tgYaw = ty
+ tgPitch = tp
+ tgTilt = cfg.tilt
+
+ if (n > waveStart && n < waveUntil) {
+ val wt = n - waveStart
+ tgTilt = -0.06 + sin(2 * PI * 1.2 * wt) * 0.07
+ }
+
+ val bounce = if (cfg.bounces) -abs(sin(t * 5.2)) * 0.07 else 0.0
+ val kGen = 1 - 0.0008.pow(dt)
+ if (Prop.OY !in locks) oy += (bounce - oy) * kGen
+
+ if (cfg.breathes) {
+ val amp = if (isMini) 0.07 else 0.035
+ tgSy = 1 + sin(t * 1.8) * amp
+ tgSx = 1 - sin(t * 1.8) * amp * 0.57
+ } else if (isMini) {
+ tgSy = 1 + sin(t * 2.2) * 0.04
+ tgSx = 1 - sin(t * 2.2) * 0.02
+ } else {
+ tgSy = 1.0
+ tgSx = 1.0
+ }
+
+ if (isMini && n > miniNextBehavior) doMiniBehaviorLoop()
+
+ val kLook = 1 - 0.0025.pow(dt)
+ if (Prop.YAW !in locks) yaw += (tgYaw - yaw) * kLook
+ if (Prop.PITCH !in locks) pitch += (tgPitch - pitch) * kLook
+ if (Prop.TILT !in locks) tilt += (tgTilt - tilt) * kGen
+ if (Prop.SY !in locks) sy += (tgSy - sy) * kGen
+ if (Prop.SX !in locks) sx += (tgSx - sx) * kGen
+ if (Prop.ES !in locks) es += (tgEs - es) * kGen
+
+ col = col.mix(colT, 1 - 0.002.pow(dt))
+
+ if (n > nextBlink) {
+ if (state != BotState.SLEEPING && state != BotState.DIZZY) {
+ blink()
+ if (random.nextDouble() < 0.22) after(230.0) { blink() }
+ }
+ nextBlink = n + 2.2 + random.nextDouble() * 3.2
+ }
+
+ if (eyeOverride != null && n > eyeOverrideUntil) {
+ eyeOverride = permanentEye
+ if (permanentEye != null) eyeOverrideUntil = Double.POSITIVE_INFINITY
+ }
+
+ if (n - lastAmbient > 1.3) {
+ lastAmbient = n
+ if (cfg.zz) emit(ParticleType.Z, 1)
+ if (!isMini && cfg.sweat && random.nextDouble() < 0.5) emit(ParticleType.SWEAT, 1)
+ }
+
+ _particles.forEach { it.age += dt }
+ _particles = ArrayList(_particles.filter { it.age < it.life })
+
+ // Mouth slot spring: w0 = 2*pi/0.25, zeta = 0.6
+ val omega = (2 * PI) / 0.25
+ val zeta = 0.6
+ val acc = omega * omega * (slotHTarget - slotH) - 2 * zeta * omega * slotHVel
+ slotHVel += acc * dt
+ slotH = max(0.0, slotH + slotHVel * dt)
+
+ // Soft-part spring: lags behind head turns, hops and rolls (stiffness 60, damping 9).
+ if (dt > 0) {
+ val yawVel = (yaw - prevYaw) / dt
+ val oyVel = (oy - prevOy) / dt
+ // A finished roll snaps from 2*pi*turns back to 0: that jump is not motion.
+ val dRoll = roll - prevRoll
+ val rollVel = if (abs(dRoll) > PI) 0.0 else dRoll / dt
+ val centrifugal = if (rigidRoll) rollVel * 0.18 else 0.0
+ val tDx = (-yawVel * 0.35 - tilt * 2 + centrifugal).coerceIn(-1.0, 1.0)
+ val tDy = (oyVel * 0.5).coerceIn(-1.0, 1.0)
+ physVx += (60 * (tDx - physDx) - 9 * physVx) * dt
+ physVy += (60 * (tDy - physDy) - 9 * physVy) * dt
+ physDx += physVx * dt
+ physDy += physVy * dt
+ }
+ prevYaw = yaw
+ prevOy = oy
+ prevRoll = roll
+ }
+
+ private fun doMiniBehaviorLoop() {
+ val n = now()
+ when (permanentEmote) {
+ BotEmote.HAPPY -> {
+ if (Prop.OY in locks) { miniNextBehavior = n + 0.4; return }
+ anim(Prop.OY, keys(Triple(-0.3, 120.0, Ease.out), Triple(0.03, 200.0, Ease.inOut), Triple(0.0, 160.0, Ease.back)))
+ anim(Prop.SY, keys(
+ Triple(0.82, 80.0, Ease.out), Triple(1.18, 130.0, Ease.out),
+ Triple(0.88, 160.0, Ease.inOut), Triple(1.0, 200.0, Ease.back),
+ ))
+ anim(Prop.SX, keys(
+ Triple(1.15, 80.0, Ease.out), Triple(0.88, 130.0, Ease.out),
+ Triple(1.06, 160.0, Ease.inOut), Triple(1.0, 200.0, Ease.back),
+ ))
+ miniNextBehavior = n + 2.2 + random.nextDouble() * 1.2
+ }
+ BotEmote.ANNOYED -> {
+ if (Prop.YAW in locks) { miniNextBehavior = n + 0.5; return }
+ anim(Prop.YAW, keys(
+ Triple(-0.65, 50.0, Ease.out), Triple(0.65, 90.0, Ease.inOut), Triple(-0.5, 80.0, Ease.inOut),
+ Triple(0.4, 75.0, Ease.inOut), Triple(-0.2, 70.0, Ease.inOut), Triple(0.0, 140.0, Ease.out),
+ ))
+ miniNextBehavior = n + 3.0 + random.nextDouble() * 2.5
+ }
+ BotEmote.WINK -> {
+ eyeOverride = EyeShape.WINK
+ eyeOverrideUntil = n + 0.55
+ anim(Prop.TILT, keys(Triple(0.13, 100.0, Ease.out), Triple(0.13, 320.0, Ease.lin), Triple(0.0, 200.0, Ease.inOut)))
+ miniNextBehavior = n + 2.2 + random.nextDouble() * 2.0
+ }
+ BotEmote.LOVE -> {
+ emit(ParticleType.HEART, 2)
+ anim(Prop.TILT, keys(Triple(-0.1, 180.0, Ease.out), Triple(0.1, 340.0, Ease.inOut), Triple(0.0, 220.0, Ease.inOut)))
+ miniNextBehavior = n + 2.6 + random.nextDouble() * 1.5
+ }
+ else -> miniNextBehavior = n + 3.0 + random.nextDouble() * 2.0
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/MochiGeometry.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiGeometry.kt
new file mode 100644
index 00000000..af9df164
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiGeometry.kt
@@ -0,0 +1,71 @@
+package com.coucou.android.mochi
+
+import com.coucou.android.core.lerp
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.pow
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+data class Pt(val x: Double, val y: Double)
+
+object MochiGeometry {
+ const val BODY_SEGMENTS = 72
+ private const val EXP_N = 2.0 / 2.7
+
+ /** Ray to rounded-rect boundary intersection, for the mailbox morph (engine.ts rrPoint). */
+ fun rrPoint(ca: Double, sa: Double, w: Double, h: Double, cr: Double): Pt {
+ val eps = 1e-6
+ val kx = if (ca >= 0) 1.0 else -1.0
+ val ky = if (sa >= 0) 1.0 else -1.0
+ val cx = kx * (w - cr)
+ val cy = ky * (h - cr)
+
+ val dot = ca * cx + sa * cy
+ val disc = dot * dot - (cx * cx + cy * cy - cr * cr)
+ if (disc >= 0) {
+ val t = dot + sqrt(disc)
+ if (t > eps) {
+ val px = ca * t
+ val py = sa * t
+ if (abs(px) >= w - cr - eps && abs(py) >= h - cr - eps) return Pt(px, py)
+ }
+ }
+ if (abs(sa) > eps) {
+ val t = (ky * h) / sa
+ if (t > eps) {
+ val px = ca * t
+ if (abs(px) <= w - cr + eps) return Pt(px, ky * h)
+ }
+ }
+ if (abs(ca) > eps) {
+ val t = (kx * w) / ca
+ if (t > eps) {
+ val py = sa * t
+ if (abs(py) <= h - cr + eps) return Pt(kx * w, py)
+ }
+ }
+ return Pt(kx * w, ky * h)
+ }
+
+ /** Superellipse (exponent 2.7) blended with the mailbox box by `morph`. */
+ fun bodyPoints(rx: Double, ry: Double, r: Double, morph: Double): List<Pt> {
+ val tw = r * 1.0
+ val th = r * 0.94
+ val tr = r * 0.42
+ return (0..BODY_SEGMENTS).map { i ->
+ val a = i.toDouble() / BODY_SEGMENTS * PI * 2
+ val ca = cos(a)
+ val sa = sin(a)
+ val px0 = rx * (if (ca >= 0) ca.pow(EXP_N) else -(-ca).pow(EXP_N))
+ val py0 = ry * (if (sa >= 0) sa.pow(EXP_N) else -(-sa).pow(EXP_N))
+ if (morph >= 0.005) {
+ val rr = rrPoint(ca, sa, tw, th, tr)
+ Pt(lerp(px0, rr.x, morph), lerp(py0, rr.y, morph))
+ } else {
+ Pt(px0, py0)
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/MochiPainter.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiPainter.kt
new file mode 100644
index 00000000..69b520ec
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiPainter.kt
@@ -0,0 +1,523 @@
+package com.coucou.android.mochi
+
+import android.graphics.Typeface
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Canvas
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.LinearGradientShader
+import androidx.compose.ui.graphics.Paint
+import androidx.compose.ui.graphics.PaintingStyle
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.RadialGradientShader
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.nativeCanvas
+import com.coucou.android.mochi.outfit.ComposeGfx
+import com.coucou.android.mochi.outfit.Ctx2D
+import com.coucou.android.mochi.outfit.Outfit
+import com.coucou.android.mochi.outfit.OutfitState
+import com.coucou.android.mochi.outfit.PUMPKIN_BODY
+import com.coucou.android.mochi.outfit.Css
+import com.coucou.android.mochi.outfit.drawOutfitBehind
+import com.coucou.android.mochi.outfit.drawOutfitFront
+import com.coucou.android.mochi.outfit.makeHead
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+
+/**
+ * Compose Canvas port of MochiEngine.draw() in windows/src/mochi/engine.ts.
+ * Draws hands, body, blush, eyes, mouth, badge, particles and the outfits (mochi/outfit, checked against the PC's drawing).
+ */
+object MochiPainter {
+ private val INK = Color(26, 20, 18)
+ private val MINI_INK = Color(16, 19, 26)
+
+ private fun Rgb.color(a: Double = 1.0) =
+ Color(r.toFloat().coerceIn(0f, 1f), g.toFloat().coerceIn(0f, 1f), b.toFloat().coerceIn(0f, 1f), a.toFloat().coerceIn(0f, 1f))
+
+ private fun cssColor(s: String): Color = Css.parse(s).let { Color((it.r / 255).toFloat(), (it.g / 255).toFloat(), (it.b / 255).toFloat(), it.a.toFloat()) }
+
+ private fun fillPaint(c: Color) = Paint().apply { color = c; isAntiAlias = true }
+ private fun strokePaint(c: Color, w: Float) = Paint().apply {
+ color = c; isAntiAlias = true; style = PaintingStyle.Stroke; strokeWidth = w; strokeCap = StrokeCap.Round
+ }
+
+ fun bodyPath(e: MochiEngine, rx: Double, ry: Double, r: Double): Path {
+ val pts = MochiGeometry.bodyPoints(rx, ry, r, e.morph)
+ return Path().apply {
+ pts.forEachIndexed { i, p -> if (i == 0) moveTo(p.x.toFloat(), p.y.toFloat()) else lineTo(p.x.toFloat(), p.y.toFloat()) }
+ close()
+ }
+ }
+
+ /** Draws Mochi centred in this DrawScope. `nowSec` drives spirals, wave and badge pulses. */
+ fun DrawScope.drawMochi(e: MochiEngine, nowSec: Double) {
+ val w = size.width.toDouble()
+ val h = size.height.toDouble()
+ val r = w * 0.3
+ val rx = r * 1.14
+ val ry = r * 0.88
+ val cx = w / 2 + e.ox * r
+ val cy = h / 2 + e.particleOverhang / 2 + e.oy * r + r * 0.06
+
+ drawIntoCanvas { c ->
+ // With an outfit on, a roll turns the whole character, hat included, as one piece.
+ c.save()
+ if (e.rigidRoll && abs(e.roll) > 0.001) {
+ c.translate(cx.toFloat(), cy.toFloat())
+ c.rotate((e.roll * 180 / PI).toFloat())
+ c.translate(-cx.toFloat(), -cy.toFloat())
+ }
+ drawHandsBehind(c, e, nowSec, r, rx, ry, cx, cy)
+
+ c.save()
+ c.translate(cx.toFloat(), cy.toFloat())
+ if (e.tilt != 0.0) c.rotate((e.tilt * 180 / PI).toFloat())
+ c.scale(e.sx.toFloat(), e.sy.toFloat())
+
+ val dressed = !e.isMini && e.outfit != Outfit.NONE
+ val head = if (dressed) makeHead(r, e.yaw, e.pitch, e.physDx, e.physDy) else null
+ val outfitState = OutfitState(e.outfitPresence, e.morph)
+ val outfitCtx = if (head != null) Ctx2D(ComposeGfx(c, Rect(Offset(-w.toFloat(), -h.toFloat()), Offset(w.toFloat(), h.toFloat())))) else null
+ if (head != null && outfitCtx != null) drawOutfitBehind(outfitCtx, e.outfit, head, outfitState)
+
+ val body = bodyPath(e, rx, ry, r)
+ drawBody(c, e, body, r, rx, ry)
+
+ val blushVal = max(e.blush, e.tint * 0.5) * (1 - e.morph)
+ if (blushVal > 0.01) {
+ c.save()
+ c.clipPath(body)
+ val yOffset = sin(e.yaw) * rx * 0.8
+ val p = fillPaint(Color(255, 120, 150, (255 * 0.5 * blushVal).toInt().coerceIn(0, 255)))
+ for (sd in intArrayOf(-1, 1)) {
+ c.drawOval(
+ Rect(
+ (sd * rx * 0.55 + yOffset - r * 0.17).toFloat(), (ry * 0.2 - r * 0.1).toFloat(),
+ (sd * rx * 0.55 + yOffset + r * 0.17).toFloat(), (ry * 0.2 + r * 0.1).toFloat(),
+ ), p,
+ )
+ }
+ c.restore()
+ }
+
+ drawEyes(c, e, nowSec, body, r, rx, ry)
+ if (e.morph > 0.05) drawMouth(c, e, body, r)
+
+ if (head != null && outfitCtx != null) drawOutfitFront(outfitCtx, e.outfit, head, outfitState)
+ c.restore()
+ c.restore()
+
+ val badge = e.badge
+ if (badge != null && e.badgeS > 0.01 && e.morph < 0.25) drawBadge(c, e, nowSec, badge, r, cx, cy)
+ drawParticles(c, e, r, cx, cy)
+ }
+ }
+
+ private fun drawBody(c: Canvas, e: MochiEngine, body: Path, r: Double, rx: Double, ry: Double) {
+ val bodyColor = e.bodyColor
+ if (bodyColor != null) {
+ c.drawPath(body, fillPaint(bodyColor.color()))
+ } else {
+ val p = Paint().apply {
+ isAntiAlias = true
+ shader = LinearGradientShader(
+ Offset((rx * 0.7).toFloat(), (-ry * 0.85).toFloat()), Offset((-rx * 0.8).toFloat(), (ry * 0.9).toFloat()),
+ listOf(MochiConst.BASE_TOP.color(), MochiConst.BASE_BOTTOM.color()),
+ )
+ }
+ c.drawPath(body, p)
+ }
+
+ // The pumpkin's orange comes and goes with the outfit; a flat-coloured body only gets the shading while it is a pumpkin.
+ val pumpkin = if (e.isMini || e.outfit != Outfit.PUMPKIN) 0.0 else min(1.0, e.outfitPresence * 2.5) * (1 - e.morph)
+ var tail = 1f
+ if (pumpkin > 0.001) {
+ val pg = Paint().apply {
+ isAntiAlias = true
+ alpha = pumpkin.toFloat().coerceIn(0f, 1f)
+ shader = LinearGradientShader(
+ Offset((rx * 0.7).toFloat(), (-ry * 0.85).toFloat()), Offset((-rx * 0.8).toFloat(), (ry * 0.9).toFloat()),
+ listOf(cssColor(PUMPKIN_BODY.first), cssColor(PUMPKIN_BODY.second)),
+ )
+ }
+ c.drawPath(body, pg)
+ if (bodyColor != null) tail = pumpkin.toFloat().coerceIn(0f, 1f)
+ }
+
+ val effectiveTint = e.tint * (1 - e.morph)
+ if (effectiveTint > 0.01) {
+ val tg = Paint().apply {
+ isAntiAlias = true
+ alpha = tail
+ shader = LinearGradientShader(
+ Offset(0f, ry.toFloat()), Offset(0f, (-ry).toFloat()),
+ listOf(e.col.color(0.72 * effectiveTint), e.col.color(0.0)),
+ )
+ }
+ c.drawPath(body, tg)
+ }
+
+ // Shade: transparent until 0.6 of the 0.15R..1.25R ramp, then black 20%.
+ val outer = r * 1.25
+ val shadeStart = ((r * 0.15 + 0.6 * (outer - r * 0.15)) / outer).toFloat()
+ val sh = Paint().apply {
+ isAntiAlias = true
+ alpha = tail
+ shader = RadialGradientShader(
+ Offset.Zero, outer.toFloat(),
+ listOf(Color(0, 0, 0, 0), Color(0, 0, 0, 0), Color(0, 0, 0, 51)),
+ listOf(0f, shadeStart, 1f),
+ )
+ }
+ c.drawPath(body, sh)
+
+ val hc = Offset((rx * 0.34).toFloat(), (-ry * 0.46).toFloat())
+ val hl = Paint().apply {
+ isAntiAlias = true
+ alpha = tail
+ shader = RadialGradientShader(hc, (r * 0.42).toFloat(), listOf(Color(255, 255, 255, 140), Color(255, 255, 255, 0)))
+ }
+ c.drawPath(body, hl)
+ }
+
+ private fun drawEyes(c: Canvas, e: MochiEngine, nowSec: Double, body: Path, r: Double, rx: Double, ry: Double) {
+ var shape = e.eyeOverride ?: e.cfg.eye
+ if (e.morph > 0.5) {
+ if (e.isChewing) shape = EyeShape.HAPPY
+ else if (e.slotHTarget > 0.05 || e.slotH > 0.1) shape = EyeShape.CUP
+ }
+ c.save()
+ c.clipPath(body)
+ val ink = if (e.isMini) MINI_INK else INK
+
+ for (sd in intArrayOf(-1, 1)) {
+ val eyeYaw = sd * MochiConst.EYE_SP + e.yaw
+ // Rolling with an outfit on, the whole body turns: the eyes must not roll again.
+ var eyePitch = MochiConst.EYE_P + e.pitch + (if (e.rigidRoll) 0.0 else e.roll)
+ eyePitch = (((eyePitch + PI) % (PI * 2)) + PI * 2) % (PI * 2) - PI
+ val cp = cos(eyePitch)
+ if (cos(eyeYaw) * cp <= 0.04) continue
+
+ val ex = sin(eyeYaw) * cp * rx
+ val ey = -sin(eyePitch) * ry + (if (e.morph > 0) ry * 0.14 * e.morph else 0.0)
+ val fx = lerpD(max(0.18, cos(eyeYaw)), 1.0, e.morph * 0.7)
+ val fy = lerpD(max(0.18, cp), 1.0, e.morph * 0.7)
+ val mult = if (e.isMini) 1.9 else 1.0
+ val ew = r * MochiConst.EYE_W * e.es * mult
+ val eh = r * MochiConst.EYE_H * e.es * mult
+
+ c.save()
+ c.translate(ex.toFloat(), ey.toFloat())
+ c.scale(fx.toFloat(), fy.toFloat())
+ drawEyeShape(c, e, nowSec, shape, ew, eh, sd, ink)
+ c.restore()
+ }
+ c.restore()
+ }
+
+ private fun roundRect(c: Canvas, x: Double, y: Double, w: Double, h: Double, rad: Double, p: Paint) {
+ val rr = max(0.0, min(rad, min(w / 2, h / 2))).toFloat()
+ c.drawRoundRect(x.toFloat(), y.toFloat(), (x + w).toFloat(), (y + h).toFloat(), rr, rr, p)
+ }
+
+ private fun arcStroke(c: Canvas, cx: Double, cy: Double, rad: Double, startRad: Double, endRad: Double, p: Paint) {
+ val path = Path().apply {
+ arcTo(
+ Rect((cx - rad).toFloat(), (cy - rad).toFloat(), (cx + rad).toFloat(), (cy + rad).toFloat()),
+ (startRad * 180 / PI).toFloat(), ((endRad - startRad) * 180 / PI).toFloat(), true,
+ )
+ }
+ c.drawPath(path, p)
+ }
+
+ private fun heartPath(s: Double) = Path().apply {
+ val f = s.toFloat()
+ moveTo(0f, f * 0.38f)
+ cubicTo(-f * 1.05f, -f * 0.15f, -f * 0.5f, -f * 0.95f, 0f, -f * 0.38f)
+ cubicTo(f * 0.5f, -f * 0.95f, f * 1.05f, -f * 0.15f, 0f, f * 0.38f)
+ close()
+ }
+
+ private fun starPath(ro: Double, ri: Double) = Path().apply {
+ for (i in 0 until 10) {
+ val rad = if (i % 2 == 1) ri else ro
+ val a = -PI / 2 + i * PI / 5
+ val px = (cos(a) * rad).toFloat()
+ val py = (sin(a) * rad).toFloat()
+ if (i == 0) moveTo(px, py) else lineTo(px, py)
+ }
+ close()
+ }
+
+ private fun drawEyeShape(c: Canvas, e: MochiEngine, nowSec: Double, shape: EyeShape, w: Double, h: Double, sd: Int, ink: Color) {
+ val fill = fillPaint(ink)
+ when (shape) {
+ EyeShape.WIDE -> drawEyeShape(c, e, nowSec, EyeShape.PILL, w * 1.16, h * 1.12, sd, ink)
+ EyeShape.PILL -> {
+ val hh = max(h * e.open, w * 0.3)
+ roundRect(c, -w / 2, -hh / 2, w, hh, min(w / 2, hh / 2), fill)
+ }
+ EyeShape.DOT -> c.drawCircle(Offset.Zero, (w * 0.45).toFloat(), fill)
+ EyeShape.LINE -> {
+ c.save()
+ c.rotate((-sd * 0.2 * 180 / PI).toFloat())
+ roundRect(c, -w * 0.78, -w * 0.21, w * 1.56, w * 0.42, w * 0.21, fill)
+ c.restore()
+ }
+ EyeShape.FLAT -> roundRect(c, -w * 0.72, -w * 0.2, w * 1.44, w * 0.4, w * 0.2, fill)
+ EyeShape.HAPPY -> arcStroke(c, 0.0, h * 0.18, w * 0.82, PI * 1.12, PI * 1.88, strokePaint(ink, (w * 0.5).toFloat()))
+ EyeShape.CLOSED -> arcStroke(c, 0.0, -h * 0.08, w * 0.78, PI * 0.15, PI * 0.85, strokePaint(ink, (w * 0.36).toFloat()))
+ EyeShape.SPIRAL -> {
+ val path = Path()
+ var a = 0.0
+ var first = true
+ while (a < 4.4 * PI) {
+ val rad = w * 0.06 + a * w * 0.058
+ val aa = a + nowSec * 9 * sd
+ val px = (cos(aa) * rad).toFloat()
+ val py = (sin(aa) * rad).toFloat()
+ if (first) { path.moveTo(px, py); first = false } else path.lineTo(px, py)
+ a += 0.2
+ }
+ c.drawPath(path, strokePaint(ink, (w * 0.22).toFloat()))
+ }
+ EyeShape.HEART -> c.drawPath(heartPath(w * 1.2), fillPaint(Color(0xFF, 0x4D, 0x6D)))
+ EyeShape.STAR -> {
+ c.save()
+ c.rotate((nowSec * 1.5 * sd * 180 / PI).toFloat())
+ c.drawPath(starPath(w * 1.05, w * 0.46), fillPaint(Color(0xF7, 0xB3, 0x2B)))
+ c.restore()
+ }
+ EyeShape.TIRED -> {
+ roundRect(c, -w / 2, -h * 0.02, w, h * 0.38, w / 2, fill)
+ roundRect(c, -w * 0.62, -h * 0.1, w * 1.24, w * 0.22, w * 0.11, fill)
+ }
+ EyeShape.WINK -> if (sd < 0) {
+ val hh = max(h * e.open, w * 0.3)
+ roundRect(c, -w / 2, -hh / 2, w, hh, min(w / 2, hh / 2), fill)
+ } else {
+ arcStroke(c, 0.0, h * 0.18, w * 0.82, PI * 1.12, PI * 1.88, strokePaint(ink, (w * 0.5).toFloat()))
+ }
+ EyeShape.CUP -> {
+ // Flat top, rounded bottom corners (U shape), used while the box is open.
+ val hh = max(h * e.open, w * 0.3)
+ val cr = min(w / 2, hh / 2)
+ val path = Path().apply {
+ moveTo((-w / 2).toFloat(), (-hh / 2).toFloat())
+ lineTo((w / 2).toFloat(), (-hh / 2).toFloat())
+ lineTo((w / 2).toFloat(), (hh / 2 - cr).toFloat())
+ quadraticBezierTo((w / 2).toFloat(), (hh / 2).toFloat(), (w / 2 - cr).toFloat(), (hh / 2).toFloat())
+ lineTo((-w / 2 + cr).toFloat(), (hh / 2).toFloat())
+ quadraticBezierTo((-w / 2).toFloat(), (hh / 2).toFloat(), (-w / 2).toFloat(), (hh / 2 - cr).toFloat())
+ close()
+ }
+ c.drawPath(path, fill)
+ }
+ }
+ }
+
+ /** Mailbox slot: dark pill cut into the box face, with rim and lip highlights. */
+ private fun drawMouth(c: Canvas, e: MochiEngine, body: Path, r: Double) {
+ val m = e.morph
+ val hW = r * 1.8 * m
+ val hH = e.slotH * r * m
+ val hX = -hW / 2
+ val boxTop = -r * (0.88 + 0.06 * m)
+ val hY = boxTop + r * 0.08 * m
+
+ c.save()
+ c.clipPath(body)
+ val rim = strokePaint(Color(255, 255, 255, (255 * 0.55 * m).toInt().coerceIn(0, 255)), 1f)
+ c.drawLine(Offset((-r * 0.9 * m).toFloat(), (boxTop + 1).toFloat()), Offset((r * 0.9 * m).toFloat(), (boxTop + 1).toFloat()), rim)
+
+ if (hH > 0.8) {
+ val hR = min(hW / 2, hH / 2)
+ val g = Paint().apply {
+ isAntiAlias = true
+ shader = LinearGradientShader(
+ Offset(0f, hY.toFloat()), Offset(0f, (hY + hH).toFloat()),
+ listOf(Color(7, 8, 10), Color(16, 19, 26)),
+ )
+ }
+ roundRect(c, hX, hY, hW, hH, hR, g)
+ if (hH > 4) {
+ val lipR = min(hR, (hW - 2) / 2)
+ val lip = strokePaint(Color(255, 255, 255, (255 * 0.28 * m).toInt().coerceIn(0, 255)), 1f)
+ c.drawLine(
+ Offset((hX + lipR).toFloat(), (hY + hH - 0.5).toFloat()),
+ Offset((hX + hW - lipR).toFloat(), (hY + hH - 0.5).toFloat()), lip,
+ )
+ }
+ }
+ c.restore()
+ }
+
+ /** Hands sit behind the body, so they are drawn first, in world coordinates. */
+ private fun drawHandsBehind(c: Canvas, e: MochiEngine, n: Double, r: Double, rx: Double, ry: Double, cx: Double, cy: Double) {
+ if (e.hands <= 0.01 || e.isMini) return
+ if (r <= 14) return // meaningless at compact sizes
+
+ val bodyH = 2 * ry
+ val hew = 0.3 * ry * e.hands
+ val heh = 0.26 * ry * e.hands
+ val hwB = rx * e.sx
+ val hhB = ry * e.sy
+ val isWaving = n >= e.waveStart && e.waveStart > 0 && n < e.waveUntil
+
+ for (sd in intArrayOf(-1, 1)) {
+ var localX: Double
+ var localY: Double
+ var handRot = 0.0
+
+ if (sd > 0 && isWaving) {
+ val wt = n - e.waveStart
+ val rise = min(1.0, wt / 0.18)
+ val riseEased = 1 - (1 - rise).pow(3)
+ val restX = hwB * 1.08
+ val restY = hhB * 0.7
+ val oscX = cos(13 * wt) * 0.06 * bodyH
+ val oscY = -sin(13 * wt) * 0.14 * bodyH
+ val waveX = hwB * 1.1 + oscX
+ val waveY = -hhB * 0.15 + oscY
+ localX = restX + (waveX - restX) * riseEased
+ localY = restY + (waveY - restY) * riseEased
+ handRot = (-0.5 + sin(13 * wt) * 0.35) * riseEased
+ } else if (sd < 0 && isWaving) {
+ val wt = n - e.waveStart
+ localX = -hwB * 1.08
+ localY = hhB * 0.7 + sin(6 * wt) * 0.04 * bodyH
+ } else {
+ localX = sd * hwB * 1.08
+ localY = hhB * 0.7
+ }
+
+ val cosT = cos(e.tilt)
+ val sinT = sin(e.tilt)
+ val worldX = cx + cosT * localX - sinT * localY
+ val worldY = cy + sinT * localX + cosT * localY
+
+ c.save()
+ c.translate(worldX.toFloat(), worldY.toFloat())
+ if (handRot != 0.0) c.rotate((handRot * 180 / PI).toFloat())
+ val top = e.bodyColor?.mix(Rgb(1.0, 1.0, 1.0), 0.35) ?: MochiConst.BASE_TOP
+ val bottom = e.bodyColor ?: MochiConst.BASE_BOTTOM
+ val fill = Paint().apply {
+ isAntiAlias = true
+ shader = LinearGradientShader(
+ Offset((hew * 0.7).toFloat(), (-heh * 0.85).toFloat()), Offset((-hew * 0.8).toFloat(), (heh * 0.9).toFloat()),
+ listOf(top.color(), bottom.color()),
+ )
+ }
+ val oval = Rect((-hew).toFloat(), (-heh).toFloat(), hew.toFloat(), heh.toFloat())
+ c.drawOval(oval, fill)
+ c.drawOval(oval, strokePaint(Color(0, 0, 0, 20), 1f))
+ c.restore()
+ }
+ }
+
+ private fun drawBadge(c: Canvas, e: MochiEngine, t: Double, badge: Badge, r: Double, cx: Double, cy: Double) {
+ val bs = e.badgeS * (if (e.isMini) 1.25 else 1.0)
+ val bx = cx - r * 0.72 * e.sx
+ val by = cy - r * 0.72 * e.sy
+ val col = badge.color.color()
+ val black = fillPaint(Color.Black)
+
+ c.save()
+ c.translate(bx.toFloat(), by.toFloat())
+ c.scale(bs.toFloat(), bs.toFloat())
+
+ when (badge.kind) {
+ BadgeKind.DOTS -> if (e.isMini) {
+ val phase = (t * 2.4) % 1
+ val dotR = r * 0.22 * (1 + 0.25 * sin(phase * PI * 2))
+ c.drawCircle(Offset.Zero, (r * 0.2).toFloat(), black)
+ c.drawCircle(Offset.Zero, dotR.toFloat(), fillPaint(col))
+ } else {
+ val pw = r * 0.72
+ val ph = r * 0.36
+ roundRect(c, -pw / 2, -ph / 2, pw, ph, ph / 2, fillPaint(col))
+ for (i in 0 until 3) {
+ val phase = (((t * 2.4 - i * 0.22) % 1) + 1) % 1
+ val dotR = r * 0.055 * (1 + 0.4 * max(0.0, sin(phase * PI * 2)))
+ c.drawCircle(Offset(((i - 1) * r * 0.18).toFloat(), 0f), dotR.toFloat(), fillPaint(Color.White))
+ }
+ }
+ BadgeKind.BANG, BadgeKind.QUESTION -> {
+ c.drawCircle(Offset.Zero, (r * 0.3).toFloat(), black)
+ c.drawCircle(Offset.Zero, (r * 0.23).toFloat(), fillPaint(col))
+ if (!e.isMini) {
+ drawText(c, if (badge.kind == BadgeKind.BANG) "!" else "?", 0f, (r * 0.02).toFloat(), (r * 0.32).toFloat(), android.graphics.Color.WHITE, 1f)
+ }
+ }
+ BadgeKind.DOT -> {
+ c.drawCircle(Offset.Zero, (r * 0.2).toFloat(), black)
+ c.drawCircle(Offset.Zero, (r * 0.135).toFloat(), fillPaint(col))
+ }
+ }
+ c.restore()
+ }
+
+ private fun drawText(c: Canvas, s: String, x: Float, y: Float, size: Float, argb: Int, alpha: Float) {
+ val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ color = argb
+ textSize = size
+ textAlign = android.graphics.Paint.Align.CENTER
+ typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
+ this.alpha = (255 * alpha).toInt().coerceIn(0, 255)
+ }
+ val centred = y - (p.ascent() + p.descent()) / 2
+ c.nativeCanvas.drawText(s, x, centred, p)
+ }
+
+ private fun drawParticles(c: Canvas, e: MochiEngine, r: Double, cx: Double, cy: Double) {
+ for (p in e.particles) {
+ if (p.age <= 0) continue
+ val k = p.age / p.life
+ val a = if (k < 0.2) k / 0.2 else 1 - (k - 0.2) / 0.8
+ val px = cx + (p.x + p.vx * p.age) * r * 1.3
+ val py = cy + (p.y + p.vy * p.age) * r * 1.3
+ val sz = r * p.size * (1 + k * 0.4)
+ val alpha = a.coerceIn(0.0, 1.0).toFloat()
+
+ c.save()
+ c.translate(px.toFloat(), py.toFloat())
+ fun tinted(base: Color) = fillPaint(base.copy(alpha = alpha))
+ when (p.type) {
+ ParticleType.HEART -> {
+ c.rotate((sin(p.age * 6) * 0.3 * 180 / PI).toFloat())
+ c.drawPath(heartPath(sz), tinted(Color(0xFF, 0x4D, 0x6D)))
+ }
+ ParticleType.STAR -> {
+ c.rotate(((p.rot + p.age * 2) * 180 / PI).toFloat())
+ c.drawPath(starPath(sz, sz * 0.45), tinted(Color(0xF7, 0xB3, 0x2B)))
+ }
+ ParticleType.SPARK -> {
+ c.rotate((p.rot * 180 / PI).toFloat())
+ c.drawPath(starPath(sz * 0.8, sz * 0.18), tinted(Color.White))
+ }
+ ParticleType.SWEAT -> {
+ val path = Path().apply {
+ val s = sz.toFloat()
+ moveTo(0f, -s)
+ quadraticBezierTo(s * 0.8f, s * 0.2f, 0f, s * 0.6f)
+ quadraticBezierTo(-s * 0.8f, s * 0.2f, 0f, -s)
+ }
+ c.drawPath(path, tinted(Color(0x7C, 0xC7, 0xFF)))
+ }
+ ParticleType.Z -> drawText(c, "z", 0f, 0f, (sz * 1.9).toFloat(), android.graphics.Color.rgb(209, 219, 235), alpha)
+ }
+ c.restore()
+ }
+ }
+
+ private fun lerpD(a: Double, b: Double, t: Double) = a + (b - a) * t
+
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/MochiTypes.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiTypes.kt
new file mode 100644
index 00000000..8e780335
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiTypes.kt
@@ -0,0 +1,86 @@
+package com.coucou.android.mochi
+
+/** Components 0..1, like the TS `RGB` tuple. */
+data class Rgb(val r: Double, val g: Double, val b: Double) {
+ fun mix(o: Rgb, t: Double) = Rgb(r + (o.r - r) * t, g + (o.g - g) * t, b + (o.b - b) * t)
+}
+
+enum class EyeShape { PILL, WIDE, DOT, LINE, FLAT, HAPPY, CLOSED, SPIRAL, HEART, STAR, TIRED, WINK, CUP }
+
+enum class BadgeKind { DOTS, BANG, QUESTION, DOT }
+
+data class Badge(val kind: BadgeKind, val color: Rgb)
+
+enum class BotState(val key: String) {
+ IDLE("idle"), WORKING("working"), THINKING("thinking"), SEARCHING("searching"),
+ APPROVAL("approval"), QUESTION("question"), ERROR("error"), FINISHED("finished"),
+ RATELIMIT("ratelimit"), SLEEPING("sleeping"), DIZZY("dizzy"),
+}
+
+enum class BotEmote(val key: String) {
+ LOVE("love"), SURPRISED("surprised"), PROUD("proud"), WINK("wink"),
+ YAWN("yawn"), HAPPY("happy"), ANNOYED("annoyed"),
+}
+
+data class BotStateCfg(
+ val color: Rgb,
+ val tint: Double,
+ val eye: EyeShape,
+ val badge: Badge?,
+ val bounces: Boolean = false,
+ val scans: Boolean = false,
+ val breathes: Boolean = false,
+ val zz: Boolean = false,
+ val sweat: Boolean = false,
+ val look: Pair<Double, Double>? = null,
+ val tilt: Double = 0.0,
+)
+
+object MochiConst {
+ const val EYE_W = 0.25
+ const val EYE_H = 0.27
+ const val EYE_SP = 0.37
+ const val EYE_P = -0.12
+ val BASE_TOP = Rgb(0.929, 0.929, 0.937) // #EDEDEF
+ val BASE_BOTTOM = Rgb(0.769, 0.773, 0.792) // #C4C5CA
+
+ val C_IDLE = Rgb(0.902, 0.914, 0.933)
+ val C_WORKING = Rgb(0.231, 0.62, 1.0)
+ val C_THINKING = Rgb(0.545, 0.361, 0.965)
+ val C_SEARCHING = Rgb(0.388, 0.396, 0.949)
+ val C_APPROVAL = Rgb(0.961, 0.647, 0.141)
+ val C_QUESTION = Rgb(0.133, 0.827, 0.933)
+ val C_ERROR = Rgb(0.957, 0.314, 0.369)
+ val C_FINISHED = Rgb(0.204, 0.831, 0.6)
+ val C_RATELIMIT = Rgb(0.984, 0.573, 0.235)
+ val C_SLEEPING = Rgb(0.58, 0.635, 0.722)
+ val C_DIZZY = Rgb(0.957, 0.447, 0.714)
+
+ val STATES: Map<BotState, BotStateCfg> = mapOf(
+ BotState.IDLE to BotStateCfg(C_IDLE, 0.0, EyeShape.PILL, null),
+ BotState.WORKING to BotStateCfg(C_WORKING, 0.72, EyeShape.PILL, Badge(BadgeKind.DOTS, C_WORKING)),
+ BotState.THINKING to BotStateCfg(C_THINKING, 0.72, EyeShape.PILL, Badge(BadgeKind.DOTS, C_THINKING), look = 0.55 to 0.55),
+ BotState.SEARCHING to BotStateCfg(C_SEARCHING, 0.72, EyeShape.PILL, Badge(BadgeKind.DOTS, C_SEARCHING), scans = true),
+ BotState.APPROVAL to BotStateCfg(C_APPROVAL, 0.78, EyeShape.WIDE, Badge(BadgeKind.BANG, C_APPROVAL), bounces = true),
+ BotState.QUESTION to BotStateCfg(C_QUESTION, 0.75, EyeShape.PILL, Badge(BadgeKind.QUESTION, C_QUESTION), tilt = 0.17),
+ BotState.ERROR to BotStateCfg(C_ERROR, 0.78, EyeShape.FLAT, Badge(BadgeKind.DOT, C_ERROR)),
+ BotState.FINISHED to BotStateCfg(C_FINISHED, 0.35, EyeShape.HAPPY, Badge(BadgeKind.DOT, C_FINISHED)),
+ BotState.RATELIMIT to BotStateCfg(C_RATELIMIT, 0.72, EyeShape.TIRED, Badge(BadgeKind.DOT, C_RATELIMIT), sweat = true),
+ BotState.SLEEPING to BotStateCfg(C_SLEEPING, 0.32, EyeShape.CLOSED, null, breathes = true, zz = true),
+ BotState.DIZZY to BotStateCfg(C_DIZZY, 0.7, EyeShape.SPIRAL, null),
+ )
+
+ /** State to sound file name (res/raw), as STATE_SOUND in engine.ts. */
+ val STATE_SOUND: Map<BotState, String> = mapOf(
+ BotState.WORKING to "work", BotState.THINKING to "think", BotState.SEARCHING to "search",
+ BotState.APPROVAL to "approval", BotState.QUESTION to "question", BotState.ERROR to "error",
+ BotState.FINISHED to "finish", BotState.RATELIMIT to "rate", BotState.SLEEPING to "sleep",
+ BotState.DIZZY to "dizzy",
+ )
+
+ val EMOTE_EYE: Map<BotEmote, EyeShape> = mapOf(
+ BotEmote.LOVE to EyeShape.HEART, BotEmote.SURPRISED to EyeShape.DOT, BotEmote.PROUD to EyeShape.STAR,
+ BotEmote.WINK to EyeShape.WINK, BotEmote.YAWN to EyeShape.TIRED, BotEmote.HAPPY to EyeShape.HAPPY,
+ BotEmote.ANNOYED to EyeShape.LINE,
+ )
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/MochiView.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiView.kt
new file mode 100644
index 00000000..afe030ee
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/MochiView.kt
@@ -0,0 +1,40 @@
+package com.coucou.android.mochi
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalLifecycleOwner
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.repeatOnLifecycle
+import com.coucou.android.mochi.MochiPainter.drawMochi
+
+/**
+ * Hosts a [MochiEngine] and redraws it every frame while the screen is visible.
+ * The frame loop only runs while the lifecycle is STARTED, so a backgrounded app costs no CPU.
+ */
+@Composable
+fun MochiView(engine: MochiEngine, modifier: Modifier = Modifier) {
+ val frame = remember { mutableLongStateOf(0L) }
+ val lifecycle = LocalLifecycleOwner.current.lifecycle
+ LaunchedEffect(engine, lifecycle) {
+ lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
+ var last = 0L
+ while (true) {
+ androidx.compose.runtime.withFrameNanos { ns ->
+ val dt = if (last == 0L) 1.0 / 60 else ((ns - last) / 1e9).coerceIn(0.0, 0.1)
+ last = ns
+ engine.update(dt)
+ frame.longValue = ns
+ }
+ }
+ }
+ }
+ Canvas(modifier) {
+ frame.longValue // read so the canvas redraws every frame
+ drawMochi(engine, System.nanoTime() / 1e9)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/ComposeGfx.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/ComposeGfx.kt
new file mode 100644
index 00000000..ef79b5aa
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/ComposeGfx.kt
@@ -0,0 +1,160 @@
+package com.coucou.android.mochi.outfit
+
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Canvas
+import androidx.compose.ui.graphics.ClipOp
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.LinearGradientShader
+import androidx.compose.ui.graphics.Matrix
+import androidx.compose.ui.graphics.Paint
+import androidx.compose.ui.graphics.PaintingStyle
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathFillType
+import androidx.compose.ui.graphics.RadialGradientShader
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.max
+
+/**
+ * Draws what the outfit code asks for (see [Ctx2D]) on a Compose canvas. [bounds] is the area a translucent layer
+ * covers (the whole Mochi view is enough).
+ */
+class ComposeGfx(private val c: Canvas, private val bounds: Rect) : Gfx {
+ private val paint = Paint().apply { isAntiAlias = true }
+
+ override fun save() = c.save()
+ override fun restore() = c.restore()
+ override fun translate(x: Double, y: Double) = c.translate(x.toFloat(), y.toFloat())
+ override fun scale(x: Double, y: Double) = c.scale(x.toFloat(), y.toFloat())
+ override fun rotate(angle: Double) = c.rotate((angle * 180 / PI).toFloat())
+
+ override fun clip(path: Path2D, evenOdd: Boolean) {
+ c.clipPath(toPath(path, evenOdd), ClipOp.Intersect)
+ }
+
+ override fun fill(path: Path2D, style: Style) {
+ paint.style = PaintingStyle.Fill
+ paint.alpha = 1f
+ paint.shader = null
+ setStyle(style)
+ c.drawPath(toPath(path, false), paint)
+ paint.shader = null
+ }
+
+ override fun stroke(path: Path2D, style: Style, width: Double, cap: Cap, join: Join) {
+ paint.style = PaintingStyle.Stroke
+ paint.alpha = 1f
+ paint.shader = null
+ paint.strokeWidth = width.toFloat()
+ paint.strokeCap = if (cap == Cap.ROUND) StrokeCap.Round else StrokeCap.Butt
+ paint.strokeJoin = if (join == Join.ROUND) StrokeJoin.Round else StrokeJoin.Miter
+ setStyle(style)
+ c.drawPath(toPath(path, false), paint)
+ paint.shader = null
+ paint.style = PaintingStyle.Fill
+ }
+
+ override fun layer(alpha: Double, block: () -> Unit) {
+ val p = Paint().apply { this.alpha = alpha.toFloat().coerceIn(0f, 1f) }
+ c.saveLayer(bounds, p)
+ block()
+ c.restore()
+ }
+
+ private fun color(x: Rgba) = Color(
+ (x.r / 255).toFloat().coerceIn(0f, 1f), (x.g / 255).toFloat().coerceIn(0f, 1f),
+ (x.b / 255).toFloat().coerceIn(0f, 1f), x.a.toFloat().coerceIn(0f, 1f),
+ )
+
+ private fun setStyle(style: Style) {
+ when (style) {
+ is Solid -> paint.color = color(style.c)
+ is LinearGradient -> {
+ paint.color = Color.Black
+ paint.shader = LinearGradientShader(
+ Offset(style.x0.toFloat(), style.y0.toFloat()), Offset(style.x1.toFloat(), style.y1.toFloat()),
+ style.stops.map { color(it.c) }, style.stops.map { it.offset.toFloat() },
+ )
+ }
+ is RadialGradient -> {
+ paint.color = Color.Black
+ // A circle that starts at r0 > 0 shows the first colour inside r0 and the ramp from there: shift the stops.
+ val r1 = max(style.r1, 0.001)
+ val k = (style.r0 / r1).coerceIn(0.0, 1.0)
+ val stops = if (k > 0) listOf(Stop(0.0, style.stops.first().c)) + style.stops.map { Stop(k + it.offset * (1 - k), it.c) } else style.stops
+ paint.shader = RadialGradientShader(
+ Offset(style.x.toFloat(), style.y.toFloat()), r1.toFloat(),
+ stops.map { color(it.c) }, stops.map { it.offset.toFloat() },
+ )
+ }
+ }
+ }
+
+ companion object {
+ /** The path as a Compose path; the browser's arcTo, arc and ellipse are turned into arcs here. */
+ fun toPath(p: Path2D, evenOdd: Boolean): Path {
+ val out = Path()
+ out.fillType = if (evenOdd) PathFillType.EvenOdd else PathFillType.NonZero
+ var cx = 0.0
+ var cy = 0.0
+ var sx = 0.0
+ var sy = 0.0
+ for (s in p.segs) {
+ when (s) {
+ is Seg.MoveTo -> { out.moveTo(s.x.toFloat(), s.y.toFloat()); cx = s.x; cy = s.y; sx = s.x; sy = s.y }
+ is Seg.LineTo -> { out.lineTo(s.x.toFloat(), s.y.toFloat()); cx = s.x; cy = s.y }
+ is Seg.QuadTo -> { out.quadraticBezierTo(s.cx.toFloat(), s.cy.toFloat(), s.x.toFloat(), s.y.toFloat()); cx = s.x; cy = s.y }
+ is Seg.CubicTo -> {
+ out.cubicTo(s.c1x.toFloat(), s.c1y.toFloat(), s.c2x.toFloat(), s.c2y.toFloat(), s.x.toFloat(), s.y.toFloat())
+ cx = s.x; cy = s.y
+ }
+ is Seg.ArcTo -> {
+ val a = ArcToMath.compute(cx, cy, s.x1, s.y1, s.x2, s.y2, s.r)
+ if (a == null) {
+ out.lineTo(s.x1.toFloat(), s.y1.toFloat()); cx = s.x1; cy = s.y1
+ } else {
+ out.lineTo(a.startX.toFloat(), a.startY.toFloat())
+ out.arcTo(
+ Rect((a.cx - a.r).toFloat(), (a.cy - a.r).toFloat(), (a.cx + a.r).toFloat(), (a.cy + a.r).toFloat()),
+ Math.toDegrees(a.startAngle).toFloat(), Math.toDegrees(a.sweep).toFloat(), false,
+ )
+ cx = a.endX; cy = a.endY
+ }
+ }
+ is Seg.Arc -> {
+ addEllipse(out, s.x, s.y, s.r, s.r, 0.0, s.a0, s.a1)
+ cx = s.x + s.r * kotlin.math.cos(s.a1); cy = s.y + s.r * kotlin.math.sin(s.a1)
+ }
+ is Seg.Ellipse -> {
+ addEllipse(out, s.x, s.y, s.rx, s.ry, s.rot, s.a0, s.a1)
+ cx = s.x; cy = s.y
+ }
+ is Seg.Rect -> {
+ out.addRect(Rect(s.x.toFloat(), s.y.toFloat(), (s.x + s.w).toFloat(), (s.y + s.h).toFloat()))
+ cx = s.x; cy = s.y; sx = s.x; sy = s.y
+ }
+ Seg.Close -> { out.close(); cx = sx; cy = sy }
+ }
+ }
+ return out
+ }
+
+ private fun addEllipse(out: Path, x: Double, y: Double, rx: Double, ry: Double, rot: Double, a0: Double, a1: Double) {
+ val oval = Rect((x - rx).toFloat(), (y - ry).toFloat(), (x + rx).toFloat(), (y + ry).toFloat())
+ val part = Path()
+ if (abs(a1 - a0) >= 2 * PI - 1e-9) part.addOval(oval)
+ else part.arcTo(oval, Math.toDegrees(a0).toFloat(), Math.toDegrees(a1 - a0).toFloat(), true)
+ if (rot != 0.0) {
+ val m = Matrix()
+ m.translate(x.toFloat(), y.toFloat())
+ m.rotateZ(Math.toDegrees(rot).toFloat())
+ m.translate(-x.toFloat(), -y.toFloat())
+ part.transform(m)
+ }
+ out.addPath(part)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Ctx2D.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Ctx2D.kt
new file mode 100644
index 00000000..bf9b58fe
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Ctx2D.kt
@@ -0,0 +1,190 @@
+package com.coucou.android.mochi.outfit
+
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.atan2
+import kotlin.math.hypot
+import kotlin.math.tan
+
+/**
+ * A small stateful 2D context shaped like the browser's CanvasRenderingContext2D, so the outfit drawing of
+ * windows/src/mochi/outfits.ts can be ported line by line. Pure Kotlin: the real drawing is done by a [Gfx]
+ * (Compose canvas on the phone, a recorder in the tests, which compare it with the TypeScript original).
+ */
+
+/** A colour as the browser reads it: channels 0..255, alpha 0..1. */
+data class Rgba(val r: Double, val g: Double, val b: Double, val a: Double)
+
+sealed interface Style
+data class Solid(val c: Rgba) : Style
+data class Stop(val offset: Double, val c: Rgba)
+data class LinearGradient(val x0: Double, val y0: Double, val x1: Double, val y1: Double, val stops: List<Stop>) : Style
+data class RadialGradient(val x: Double, val y: Double, val r0: Double, val r1: Double, val stops: List<Stop>) : Style
+
+enum class Cap { BUTT, ROUND }
+enum class Join { MITER, ROUND }
+
+/** CSS colours as used by the outfits: #RGB, #RRGGBB, rgb() and rgba(). Anything else is a programming error. */
+object Css {
+ private val cache = HashMap<String, Rgba>()
+
+ fun parse(s: String): Rgba = cache.getOrPut(s) { parseUncached(s) }
+
+ private fun parseUncached(s: String): Rgba {
+ val t = s.trim()
+ if (t.startsWith("#")) {
+ val h = t.drop(1)
+ return when (h.length) {
+ 3 -> Rgba(h.substring(0, 1).repeat(2).toInt(16).toDouble(), h.substring(1, 2).repeat(2).toInt(16).toDouble(), h.substring(2, 3).repeat(2).toInt(16).toDouble(), 1.0)
+ 6 -> Rgba(h.substring(0, 2).toInt(16).toDouble(), h.substring(2, 4).toInt(16).toDouble(), h.substring(4, 6).toInt(16).toDouble(), 1.0)
+ else -> throw IllegalArgumentException("colour $s")
+ }
+ }
+ val open = t.indexOf('(')
+ require(open > 0 && t.endsWith(")")) { "colour $s" }
+ val parts = t.substring(open + 1, t.length - 1).split(',').map { it.trim().toDouble() }
+ return when (t.substring(0, open)) {
+ "rgb" -> { require(parts.size == 3); Rgba(parts[0], parts[1], parts[2], 1.0) }
+ "rgba" -> { require(parts.size == 4); Rgba(parts[0], parts[1], parts[2], parts[3]) }
+ else -> throw IllegalArgumentException("colour $s")
+ }
+ }
+}
+
+/** What a path is made of, kept as the browser was told (so a recorder can compare it with the original). */
+sealed interface Seg {
+ data class MoveTo(val x: Double, val y: Double) : Seg
+ data class LineTo(val x: Double, val y: Double) : Seg
+ data class QuadTo(val cx: Double, val cy: Double, val x: Double, val y: Double) : Seg
+ data class CubicTo(val c1x: Double, val c1y: Double, val c2x: Double, val c2y: Double, val x: Double, val y: Double) : Seg
+ data class ArcTo(val x1: Double, val y1: Double, val x2: Double, val y2: Double, val r: Double) : Seg
+ data class Arc(val x: Double, val y: Double, val r: Double, val a0: Double, val a1: Double) : Seg
+ data class Ellipse(val x: Double, val y: Double, val rx: Double, val ry: Double, val rot: Double, val a0: Double, val a1: Double) : Seg
+ data class Rect(val x: Double, val y: Double, val w: Double, val h: Double) : Seg
+ data object Close : Seg
+}
+
+class Path2D {
+ val segs = ArrayList<Seg>()
+ fun moveTo(x: Double, y: Double) { segs.add(Seg.MoveTo(x, y)) }
+ fun lineTo(x: Double, y: Double) { segs.add(Seg.LineTo(x, y)) }
+ fun quadraticCurveTo(cx: Double, cy: Double, x: Double, y: Double) { segs.add(Seg.QuadTo(cx, cy, x, y)) }
+ fun bezierCurveTo(c1x: Double, c1y: Double, c2x: Double, c2y: Double, x: Double, y: Double) { segs.add(Seg.CubicTo(c1x, c1y, c2x, c2y, x, y)) }
+ fun arcTo(x1: Double, y1: Double, x2: Double, y2: Double, r: Double) { segs.add(Seg.ArcTo(x1, y1, x2, y2, r)) }
+ fun arc(x: Double, y: Double, r: Double, a0: Double, a1: Double) { segs.add(Seg.Arc(x, y, r, a0, a1)) }
+ fun ellipse(x: Double, y: Double, rx: Double, ry: Double, rot: Double, a0: Double, a1: Double) { segs.add(Seg.Ellipse(x, y, rx, ry, rot, a0, a1)) }
+ fun rect(x: Double, y: Double, w: Double, h: Double) { segs.add(Seg.Rect(x, y, w, h)) }
+ fun closePath() { segs.add(Seg.Close) }
+ fun addPath(p: Path2D) { segs.addAll(p.segs) }
+}
+
+/** The drawing surface: transforms, clips and filled or stroked paths, plus one translucent layer. */
+interface Gfx {
+ fun save()
+ fun restore()
+ fun translate(x: Double, y: Double)
+ fun scale(x: Double, y: Double)
+ fun rotate(angle: Double)
+ fun clip(path: Path2D, evenOdd: Boolean)
+ fun fill(path: Path2D, style: Style)
+ fun stroke(path: Path2D, style: Style, width: Double, cap: Cap, join: Join)
+ /** Draws what [block] draws as one picture at [alpha], so overlapping parts do not show through each other. */
+ fun layer(alpha: Double, block: () -> Unit)
+}
+
+class Ctx2D(private val gfx: Gfx) {
+ private class State(val fill: Style, val stroke: Style, val width: Double, val cap: Cap, val join: Join)
+
+ var fillStyle: Style = Solid(Rgba(0.0, 0.0, 0.0, 1.0))
+ var strokeStyle: Style = Solid(Rgba(0.0, 0.0, 0.0, 1.0))
+ var lineWidth = 1.0
+ var lineCap = Cap.BUTT
+ var lineJoin = Join.MITER
+ private var current = Path2D()
+ private val stack = ArrayList<State>()
+
+ fun fillStyle(css: String) { fillStyle = Solid(Css.parse(css)) }
+ fun strokeStyle(css: String) { strokeStyle = Solid(Css.parse(css)) }
+
+ fun save() { stack.add(State(fillStyle, strokeStyle, lineWidth, lineCap, lineJoin)); gfx.save() }
+ fun restore() {
+ val s = stack.removeLastOrNull() ?: return
+ fillStyle = s.fill; strokeStyle = s.stroke; lineWidth = s.width; lineCap = s.cap; lineJoin = s.join
+ gfx.restore()
+ }
+ fun translate(x: Double, y: Double) = gfx.translate(x, y)
+ fun scale(x: Double, y: Double) = gfx.scale(x, y)
+ fun rotate(a: Double) = gfx.rotate(a)
+
+ // The current path, as the browser keeps one between beginPath() and fill() or stroke().
+ fun beginPath() { current = Path2D() }
+ fun moveTo(x: Double, y: Double) = current.moveTo(x, y)
+ fun lineTo(x: Double, y: Double) = current.lineTo(x, y)
+ fun quadraticCurveTo(cx: Double, cy: Double, x: Double, y: Double) = current.quadraticCurveTo(cx, cy, x, y)
+ fun bezierCurveTo(c1x: Double, c1y: Double, c2x: Double, c2y: Double, x: Double, y: Double) = current.bezierCurveTo(c1x, c1y, c2x, c2y, x, y)
+ fun arcTo(x1: Double, y1: Double, x2: Double, y2: Double, r: Double) = current.arcTo(x1, y1, x2, y2, r)
+ fun arc(x: Double, y: Double, r: Double, a0: Double, a1: Double) = current.arc(x, y, r, a0, a1)
+ fun ellipse(x: Double, y: Double, rx: Double, ry: Double, rot: Double, a0: Double, a1: Double) = current.ellipse(x, y, rx, ry, rot, a0, a1)
+ fun closePath() = current.closePath()
+
+ fun fill(path: Path2D = current) = gfx.fill(path, fillStyle)
+ fun stroke(path: Path2D = current) = gfx.stroke(path, strokeStyle, lineWidth, lineCap, lineJoin)
+ fun clip(path: Path2D, evenOdd: Boolean = false) = gfx.clip(path, evenOdd)
+ fun fillRect(x: Double, y: Double, w: Double, h: Double) = gfx.fill(Path2D().also { it.rect(x, y, w, h) }, fillStyle)
+
+ fun createLinearGradient(x0: Double, y0: Double, x1: Double, y1: Double, stops: List<Pair<Double, String>>): Style =
+ LinearGradient(x0, y0, x1, y1, stops.map { Stop(it.first, Css.parse(it.second)) })
+
+ fun createRadialGradient(x: Double, y: Double, r0: Double, r1: Double, stops: List<Pair<Double, String>>): Style =
+ RadialGradient(x, y, r0, r1, stops.map { Stop(it.first, Css.parse(it.second)) })
+
+ /** Draws [fn] at [alpha] as one layer (a plain save/restore when it is practically opaque). */
+ fun withLayer(alpha: Double, fn: (Ctx2D) -> Unit) {
+ if (alpha >= 0.999) {
+ save(); fn(this); restore()
+ return
+ }
+ gfx.layer(alpha) { save(); fn(this); restore() }
+ }
+}
+
+/**
+ * The browser's arcTo(): where the line from the current point stops, the circle's centre and its sweep.
+ * Null when the three points are in line or the radius is zero: the browser then just draws a line to (x1, y1).
+ */
+object ArcToMath {
+ class Arc(val startX: Double, val startY: Double, val endX: Double, val endY: Double, val cx: Double, val cy: Double, val r: Double, val startAngle: Double, val sweep: Double)
+
+ fun compute(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double, r: Double): Arc? {
+ if (r <= 0) return null
+ val ax = x0 - x1
+ val ay = y0 - y1
+ val bx = x2 - x1
+ val by = y2 - y1
+ val la = hypot(ax, ay)
+ val lb = hypot(bx, by)
+ if (la < 1e-12 || lb < 1e-12) return null
+ val cross = ax * by - ay * bx
+ if (abs(cross) < 1e-12 * la * lb) return null
+ val dot = ax * bx + ay * by
+ val angle = atan2(abs(cross), dot) // angle at the corner, 0..PI
+ val t = r / tan(angle / 2)
+ val sx = x1 + ax / la * t
+ val sy = y1 + ay / la * t
+ val ex = x1 + bx / lb * t
+ val ey = y1 + by / lb * t
+ // The centre lies on the bisector, at distance r from both tangent points.
+ val mx = (ax / la + bx / lb)
+ val my = (ay / la + by / lb)
+ val ml = hypot(mx, my)
+ val d = r / kotlin.math.sin(angle / 2)
+ val cx = x1 + mx / ml * d
+ val cy = y1 + my / ml * d
+ val a0 = atan2(sy - cy, sx - cx)
+ var sweep = atan2(ey - cy, ex - cx) - a0
+ // Take the short way round.
+ while (sweep > PI) sweep -= 2 * PI
+ while (sweep < -PI) sweep += 2 * PI
+ return Arc(sx, sy, ex, ey, cx, cy, r, a0, sweep)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitDrawing.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitDrawing.kt
new file mode 100644
index 00000000..2a7873e6
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitDrawing.kt
@@ -0,0 +1,94 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.core.Ease
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.floor
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+
+/**
+ * Mochi's outfits, a line-by-line port of windows/src/mochi/outfits.ts (itself a port of the Mac's
+ * MochiOutfitDrawing.swift). Coordinates are the body space of [Head]. Every function keeps the order of
+ * its drawing calls, because a test records them and compares with the TypeScript original.
+ */
+internal typealias Stops = List<Pair<Double, String>>
+
+internal fun Ctx2D.lin(x0: Double, y0: Double, x1: Double, y1: Double, stops: Stops) = createLinearGradient(x0, y0, x1, y1, stops)
+internal fun Ctx2D.rad(x: Double, y: Double, r0: Double, r1: Double, stops: Stops) = createRadialGradient(x, y, r0, max(0.001, r1), stops)
+
+internal fun Ctx2D.polyline(pts: List<Pt2>) {
+ beginPath()
+ pts.forEachIndexed { i, q -> if (i > 0) lineTo(q.x, q.y) else moveTo(q.x, q.y) }
+}
+
+internal fun Ctx2D.roundRect(x: Double, y: Double, w: Double, h: Double, r: Double) {
+ val rr = max(0.0, min(r, min(w / 2, h / 2)))
+ beginPath()
+ moveTo(x + rr, y)
+ arcTo(x + w, y, x + w, y + h, rr)
+ arcTo(x + w, y + h, x, y + h, rr)
+ arcTo(x, y + h, x, y, rr)
+ arcTo(x, y, x + w, y, rr)
+ closePath()
+}
+
+internal fun Ctx2D.fillAll(h: Head) = fillRect(-h.rx * 4, -h.ry * 4, h.rx * 8, h.ry * 8)
+
+internal fun List<P3>.pts() = map { Pt2(it.x, it.y) }
+
+// ── Soft bits ─────────────────────────────────────────────────────────────────
+
+internal fun pompom(ctx: Ctx2D, x: Double, y: Double, r: Double, base: String = "#FFFFFF", shade: String = "#D5D9E2") {
+ ctx.save()
+ ctx.translate(x, y)
+ val n = 11
+ for (i in 0 until n) {
+ val a = i.toDouble() / n * PI * 2
+ val br = r * (0.34 + 0.06 * sin(i * 2.3))
+ val bx = cos(a) * r * 0.78
+ val by = sin(a) * r * 0.78
+ ctx.fillStyle = ctx.rad(bx - br * 0.4, by - br * 0.5, 0.0, br * 1.3, listOf(0.0 to base, 1.0 to shade))
+ ctx.beginPath()
+ ctx.arc(bx, by, br, 0.0, PI * 2)
+ ctx.fill()
+ }
+ ctx.fillStyle = ctx.rad(-r * 0.3, -r * 0.35, 0.0, r * 1.05, listOf(0.0 to base, 0.7 to base, 1.0 to shade))
+ ctx.beginPath()
+ ctx.arc(0.0, 0.0, r * 0.86, 0.0, PI * 2)
+ ctx.fill()
+ ctx.restore()
+}
+
+/** Fuzzy band along a polyline (the Santa hat's trim). */
+internal fun fuzzyBand(ctx: Ctx2D, arc: List<Pt2>, thick: Double, base: String = "#FFFFFF", shade: String = "#DADDE4") {
+ if (arc.size < 2) return
+ ctx.save()
+ ctx.lineJoin = Join.ROUND
+ ctx.lineCap = Cap.ROUND
+ ctx.polyline(arc)
+ ctx.strokeStyle(shade)
+ ctx.lineWidth = thick
+ ctx.stroke()
+ ctx.polyline(arc)
+ ctx.strokeStyle(base)
+ ctx.lineWidth = thick * 0.78
+ ctx.stroke()
+ val step = max(2, floor(arc.size / 16.0).toInt())
+ var i = 0
+ while (i < arc.size) {
+ val q = arc[i]
+ val r = thick * (0.32 + 0.1 * sin(i * 1.7))
+ ctx.fillStyle = ctx.rad(q.x - r * 0.3, q.y - thick * 0.35 - r * 0.3, 0.0, r * 1.2, listOf(0.0 to base, 1.0 to shade))
+ ctx.beginPath()
+ ctx.arc(q.x, q.y - thick * 0.32, r, 0.0, PI * 2)
+ ctx.fill()
+ i += step
+ }
+ ctx.restore()
+}
+
+// ── Beanie ────────────────────────────────────────────────────────────────────
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitGeometry.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitGeometry.kt
new file mode 100644
index 00000000..18a3f2ec
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitGeometry.kt
@@ -0,0 +1,156 @@
+package com.coucou.android.mochi.outfit
+
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sign
+import kotlin.math.sin
+
+/**
+ * The head's 3D helpers of windows/src/mochi/outfits.ts. Body space: origin at the body centre, y down,
+ * R = width x 0.3, rx = 1.14 R, ry = 0.88 R. The head is a superellipsoid, so its silhouette matches Mochi's body.
+ */
+const val EXP = 2.7
+const val VIEW_TILT = -0.3
+const val ACC_PITCH = 0.4
+const val EYE_W = 0.25
+const val EYE_H = 0.27
+const val EYE_SP = 0.37
+const val EYE_P = -0.12
+
+/** Below this radius the small details (ribs, dots, gems) are left out. */
+const val SIMPLIFY_BELOW_R = 16.0
+
+data class Vec3(val x: Double, val y: Double, val z: Double)
+data class P3(val x: Double, val y: Double, val z: Double)
+data class Pt2(val x: Double, val y: Double)
+
+/** Head geometry plus the spring lag of the soft parts (-1..1, in head units). */
+data class Head(val R: Double, val rx: Double, val ry: Double, val yaw: Double, val pitch: Double, val physDx: Double, val physDy: Double)
+
+fun makeHead(R: Double, yaw: Double = 0.0, pitch: Double = 0.0, physDx: Double = 0.0, physDy: Double = 0.0) =
+ Head(R, R * 1.14, R * 0.88, yaw, pitch, physDx, physDy)
+
+/** Radius of the horizontal ring of the head at height y. */
+fun ringR(y: Double): Double {
+ val a = min(1.0, abs(y))
+ return (1 - a.pow(EXP)).pow(1 / EXP)
+}
+
+/** Head-local point (x right, y up, z toward the viewer) to body space, with depth. */
+fun proj(h: Head, x: Double, y: Double, z: Double): P3 {
+ val cy = cos(h.yaw)
+ val sy = sin(h.yaw)
+ val x1 = x * cy + z * sy
+ val z1 = -x * sy + z * cy
+ val pitch = VIEW_TILT + h.pitch * ACC_PITCH
+ val cp = cos(pitch)
+ val sp = sin(pitch)
+ val y2 = y * cp + z1 * sp
+ val z2 = -y * sp + z1 * cp
+ return P3(x1 * h.rx, -y2 * h.ry, z2)
+}
+
+fun proj(h: Head, v: Vec3) = proj(h, v.x, v.y, v.z)
+
+/** Point on the head surface at height y, longitude lon (0 = facing the viewer), scaled by s. */
+fun surf(y: Double, lon: Double, s: Double = 1.0): Vec3 {
+ val r = ringR(y) * s
+ return Vec3(r * sin(lon), y, r * cos(lon))
+}
+
+/** The visible half of a projected closed ring, left to right, cut at its silhouette. */
+fun frontSilhouette(pts: List<P3>): List<P3> {
+ val n = pts.size
+ if (n < 2) return pts
+ var minI = 0
+ var maxI = 0
+ for (i in 1 until n) {
+ if (pts[i].x < pts[minI].x) minI = i
+ if (pts[i].x > pts[maxI].x) maxI = i
+ }
+ if (minI == maxI) return listOf(pts[minI])
+ fun walk(step: Int): List<P3> {
+ val out = ArrayList<P3>()
+ var i = minI
+ while (true) {
+ out.add(pts[i])
+ if (i == maxI || out.size > n) break
+ i = (i + step + n) % n
+ }
+ return out
+ }
+ val a = walk(1)
+ val b = walk(-1)
+ val za = a.sumOf { it.z } / a.size
+ val zb = b.sumOf { it.z } / b.size
+ return if (za >= zb) a else b
+}
+
+fun ring(h: Head, y: Double, s: Double, n: Int = 120): List<P3> =
+ (0 until n).map { i -> proj(h, surf(y, -PI + i.toDouble() / n * 2 * PI, s)) }
+
+/** Front arc of the ring at height y, ordered left to right. */
+fun frontArc(h: Head, y: Double, s: Double): List<P3> = frontSilhouette(ring(h, y, s))
+
+/** The part of the head above the front arc of ring y: what a cap covers. */
+fun capClip(h: Head, y: Double, s: Double, extraTop: Double = 3.0): Path2D {
+ val arc = frontArc(h, y, s)
+ val p = Path2D()
+ if (arc.isEmpty()) return p
+ p.moveTo(arc[0].x - h.rx, arc[0].y)
+ for (q in arc) p.lineTo(q.x, q.y)
+ val last = arc[arc.size - 1]
+ p.lineTo(last.x + h.rx, last.y)
+ p.lineTo(h.rx * 2, -h.ry * extraTop)
+ p.lineTo(-h.rx * 2, -h.ry * extraTop)
+ p.closePath()
+ return p
+}
+
+/** Everything but [p], for an even-odd clip. */
+fun invert(p: Path2D, h: Head): Path2D {
+ val q = Path2D()
+ q.rect(-h.rx * 4, -h.ry * 4, h.rx * 8, h.ry * 8)
+ q.addPath(p)
+ return q
+}
+
+/** Mochi's body outline, the same superellipse as the engine. */
+fun bodyOutline(rx: Double, ry: Double): Path2D {
+ val p = Path2D()
+ val n = 96
+ val e = 2 / EXP
+ for (i in 0..n) {
+ val a = i.toDouble() / n * PI * 2
+ val ca = cos(a)
+ val sa = sin(a)
+ val x = rx * sign(ca) * abs(ca).pow(e)
+ val y = ry * sign(sa) * abs(sa).pow(e)
+ if (i == 0) p.moveTo(x, y) else p.lineTo(x, y)
+ }
+ p.closePath()
+ return p
+}
+
+data class EyeFrame(val sd: Double, val x: Double, val y: Double, val fx: Double, val fy: Double, val visible: Boolean, val w: Double, val h: Double)
+
+/** Where the engine draws the eyes: the glasses sit on these. */
+fun eyeFrames(h: Head): List<EyeFrame> = listOf(-1.0, 1.0).map { sd ->
+ val eyeYaw = sd * EYE_SP + h.yaw
+ val eyePitch = EYE_P + h.pitch
+ val cp = cos(eyePitch)
+ EyeFrame(
+ sd = sd,
+ visible = cos(eyeYaw) * cp > 0.04,
+ x = sin(eyeYaw) * cp * h.rx,
+ y = -sin(eyePitch) * h.ry,
+ fx = max(0.18, cos(eyeYaw)),
+ fy = max(0.18, cp),
+ w = h.R * EYE_W,
+ h = h.R * EYE_H,
+ )
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitHats.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitHats.kt
new file mode 100644
index 00000000..f0f37bab
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitHats.kt
@@ -0,0 +1,395 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.core.Ease
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.floor
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+
+// Beanie, Santa hat, party hat, crown, witch hat: parts of the port in Outfits.kt.
+
+internal fun beanie(ctx: Ctx2D, h: Head, body: Path2D, simple: Boolean) {
+ val s = 1.035
+ val yEdge = 0.42
+ val yCuff = 0.58
+ val head = bodyOutline(h.rx * s, h.ry * s)
+
+ // shadow on the head under the cuff
+ ctx.save()
+ ctx.clip(body)
+ ctx.clip(capClip(h, yEdge - 0.12, 1.0))
+ ctx.fillStyle("rgba(30,40,70,0.10)")
+ ctx.fillAll(h)
+ ctx.restore()
+
+ // knit body
+ ctx.save()
+ ctx.clip(capClip(h, yCuff, s))
+ ctx.fillStyle = ctx.lin(h.rx * 0.5, -h.ry * 1.1, -h.rx * 0.6, h.ry * 0.2, listOf(0.0 to "#7DB6FF", 1.0 to "#2F6FE0"))
+ ctx.fill(head)
+ if (!simple) {
+ ctx.clip(head)
+ ctx.strokeStyle("rgba(20,50,140,0.16)")
+ ctx.lineWidth = h.R * 0.045
+ ctx.lineCap = Cap.ROUND
+ for (k in -6..6) {
+ val lon = k * 0.24
+ val pts = ArrayList<P3>()
+ for (i in 0..16) {
+ val q = proj(h, surf(yCuff + (1.05 - yCuff) * i / 16, lon, s))
+ if (q.z > 0) pts.add(q)
+ }
+ if (pts.size < 2) continue
+ ctx.polyline(pts.pts())
+ ctx.stroke()
+ }
+ }
+ ctx.restore()
+
+ // cuff: the band between yEdge and yCuff
+ val cuffHead = bodyOutline(h.rx * s * 1.04, h.ry * s * 1.04)
+ ctx.save()
+ ctx.clip(capClip(h, yEdge, s * 1.04))
+ ctx.clip(invert(capClip(h, yCuff, s * 1.04), h), true)
+ ctx.fillStyle = ctx.lin(0.0, -h.ry * 0.6, 0.0, -h.ry * 0.2, listOf(0.0 to "#3C7BEA", 1.0 to "#2257C4"))
+ ctx.fill(cuffHead)
+ ctx.clip(cuffHead)
+ ctx.strokeStyle("rgba(10,30,100,0.22)")
+ ctx.lineWidth = h.R * 0.035
+ for (k in -14..14) {
+ val lon = k * 0.115
+ val a = proj(h, surf(yEdge, lon, s * 1.04))
+ val b = proj(h, surf(yCuff, lon, s * 1.04))
+ if (a.z < 0) continue
+ ctx.beginPath()
+ ctx.moveTo(a.x, a.y)
+ ctx.lineTo(b.x, b.y)
+ ctx.stroke()
+ }
+ ctx.restore()
+
+ // top highlight
+ ctx.save()
+ ctx.clip(capClip(h, yCuff, s))
+ ctx.clip(head)
+ ctx.fillStyle = ctx.rad(h.rx * 0.3, -h.ry * 0.85, 0.0, h.R * 0.45, listOf(0.0 to "rgba(255,255,255,0.35)", 1.0 to "rgba(255,255,255,0)"))
+ ctx.fill(head)
+ ctx.restore()
+
+ // pompom on a short spring
+ val top = proj(h, 0.0, 1.08 * s, 0.0)
+ pompom(ctx, top.x + h.physDx * h.rx * 0.25, top.y - h.R * 0.12 + h.physDy * h.ry * 0.15, h.R * 0.24)
+}
+
+// ── Santa hat ─────────────────────────────────────────────────────────────────
+
+internal fun santaHat(ctx: Ctx2D, h: Head, body: Path2D) {
+ val s = 1.05
+ val yEdge = 0.52
+ val arc = frontArc(h, yEdge, s)
+ if (arc.isEmpty()) return
+ val l = arc[0]
+ val rt = arc[arc.size - 1]
+ val crown = proj(h, 0.0, 1.05, 0.0)
+ // the tip flops to the right and down, plus the spring lag
+ val tip = Pt2(crown.x + h.rx * (0.95 + h.physDx * 0.35), crown.y + h.ry * (0.05 + h.physDy * 0.2))
+ val peak = Pt2(crown.x + h.rx * 0.25, crown.y - h.ry * 0.62)
+ val bag = Path2D()
+ bag.moveTo(l.x, l.y)
+ bag.bezierCurveTo(l.x - h.rx * 0.05, l.y - h.ry * 0.7, peak.x - h.rx * 0.55, peak.y - h.ry * 0.05, peak.x, peak.y)
+ bag.quadraticCurveTo(tip.x - h.rx * 0.05, peak.y - h.ry * 0.02, tip.x, tip.y)
+ bag.quadraticCurveTo(tip.x - h.rx * 0.12, tip.y - h.ry * 0.22, peak.x + h.rx * 0.18, peak.y + h.ry * 0.32)
+ bag.bezierCurveTo(rt.x + h.rx * 0.05, peak.y + h.ry * 0.45, rt.x + h.rx * 0.08, rt.y - h.ry * 0.35, rt.x, rt.y)
+ for (i in arc.indices.reversed()) bag.lineTo(arc[i].x, arc[i].y)
+ bag.closePath()
+
+ ctx.save()
+ ctx.clip(body)
+ ctx.clip(capClip(h, yEdge - 0.14, 1.0))
+ ctx.fillStyle("rgba(120,10,10,0.10)")
+ ctx.fillAll(h)
+ ctx.restore()
+
+ ctx.fillStyle = ctx.lin(-h.rx * 0.6, -h.ry * 1.6, h.rx * 0.7, -h.ry * 0.3, listOf(0.0 to "#FF6B6B", 0.55 to "#E53935", 1.0 to "#B71C1C"))
+ ctx.fill(bag)
+
+ // folds following the flop
+ ctx.save()
+ ctx.clip(bag)
+ ctx.lineCap = Cap.ROUND
+ ctx.strokeStyle("rgba(90,0,0,0.20)")
+ for ((a, b, w) in listOf(Triple(0.15, 0.55, 0.1), Triple(0.45, 0.85, 0.08))) {
+ ctx.beginPath()
+ ctx.moveTo(peak.x - h.rx * 0.1 + (rt.x - l.x) * a * 0.3, peak.y + h.ry * 0.15)
+ ctx.quadraticCurveTo(peak.x + h.rx * 0.35, peak.y + h.ry * (0.05 + a * 0.3), tip.x - h.rx * (0.45 - b * 0.3), tip.y - h.ry * 0.12)
+ ctx.lineWidth = h.R * w
+ ctx.stroke()
+ }
+ ctx.fillStyle = ctx.rad(peak.x - h.rx * 0.25, peak.y + h.ry * 0.05, 0.0, h.R * 0.5, listOf(0.0 to "rgba(255,255,255,0.32)", 1.0 to "rgba(255,255,255,0)"))
+ ctx.fill(bag)
+ ctx.restore()
+
+ fuzzyBand(ctx, arc.pts(), h.R * 0.3)
+ pompom(ctx, tip.x, tip.y + h.R * 0.04, h.R * 0.22)
+}
+
+// ── Party hat ─────────────────────────────────────────────────────────────────
+
+internal fun partyHat(ctx: Ctx2D, h: Head, simple: Boolean) {
+ val baseY = 0.82
+ val baseR = 0.42
+ val lean = -0.24 + h.physDx * 0.12
+ val c = proj(h, 0.16, baseY + 0.06, 0.0)
+ val rim = ArrayList<P3>()
+ for (i in 0..48) {
+ val a = i.toDouble() / 48 * PI * 2
+ rim.add(proj(h, 0.16 + baseR * sin(a), baseY + 0.06, baseR * cos(a)))
+ }
+ val left = rim.reduce { m, q -> if (q.x < m.x) q else m }
+ val right = rim.reduce { m, q -> if (q.x > m.x) q else m }
+ val hh = h.ry * 1.6
+ val apex = Pt2(c.x + sin(lean) * hh, c.y - cos(lean) * hh)
+ val front = frontSilhouette(rim)
+
+ val cone = Path2D()
+ cone.moveTo(left.x, left.y)
+ cone.quadraticCurveTo((left.x + apex.x) / 2 - h.rx * 0.06, (left.y + apex.y) / 2, apex.x - h.R * 0.05, apex.y + h.R * 0.06)
+ cone.quadraticCurveTo(apex.x, apex.y - h.R * 0.03, apex.x + h.R * 0.05, apex.y + h.R * 0.06)
+ cone.quadraticCurveTo((right.x + apex.x) / 2 + h.rx * 0.06, (right.y + apex.y) / 2, right.x, right.y)
+ for (i in front.indices.reversed()) cone.lineTo(front[i].x, front[i].y)
+ cone.closePath()
+ ctx.fillStyle = ctx.lin(left.x, apex.y, right.x, left.y, listOf(0.0 to "#FF9BD0", 0.5 to "#F15BAE", 1.0 to "#C2187A"))
+ ctx.fill(cone)
+
+ ctx.save()
+ ctx.clip(cone)
+ if (!simple) {
+ ctx.fillStyle("rgba(255,255,255,0.92)")
+ val dots = listOf(
+ 0.25 to -0.35, 0.3 to 0.3, 0.55 to -0.05, 0.72 to 0.28, 0.8 to -0.3, 0.45 to 0.6, 0.48 to -0.65,
+ )
+ for ((t, u) in dots) {
+ val bx = left.x + (right.x - left.x) * (0.5 + u * 0.5)
+ val by = left.y + (right.y - left.y) * (0.5 + u * 0.5)
+ val x = bx + (apex.x - bx) * (1 - t)
+ val y = by + (apex.y - by) * (1 - t)
+ val r = h.R * 0.075 * (0.6 + t * 0.5)
+ ctx.beginPath()
+ ctx.ellipse(x, y, r, r * 0.9, 0.0, 0.0, PI * 2)
+ ctx.fill()
+ }
+ }
+ ctx.fillStyle = ctx.lin(left.x, 0.0, right.x, 0.0, listOf(0.0 to "rgba(255,255,255,0.28)", 0.35 to "rgba(255,255,255,0)", 1.0 to "rgba(80,0,40,0.18)"))
+ ctx.fill(cone)
+ ctx.restore()
+
+ if (front.size > 1) {
+ ctx.polyline(front.pts())
+ ctx.strokeStyle("#FFD84D")
+ ctx.lineWidth = h.R * 0.07
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+ }
+ pompom(ctx, apex.x, apex.y - h.R * 0.04, h.R * 0.16, "#FFE27A", "#F2B705")
+}
+
+// ── Crown ─────────────────────────────────────────────────────────────────────
+
+private const val CROWN_YB = 0.46
+
+private class CrownSeg(val b: P3, val tt: P3, val z: Double)
+
+/** side -1: the back half, behind the head; +1: the front half. */
+internal fun crownPart(ctx: Ctx2D, h: Head, side: Int, simple: Boolean) {
+ val s = 1.06
+ val yb = CROWN_YB
+ val yt = 0.66
+ val n = 8
+ val spikeH = 0.42
+ val bigN = 120
+ val seg = ArrayList<CrownSeg>()
+ for (i in 0..bigN) {
+ val lon = -PI + i.toDouble() / bigN * 2 * PI
+ val b = proj(h, surf(yb, lon, s))
+ val phase = (lon + PI) / (2 * PI) * n
+ val f = phase - floor(phase)
+ val spike = max(0.0, 1 - abs(f - 0.5) * 2).pow(1.6)
+ val sp = surf(yt, lon, s)
+ val tt = proj(h, sp.x * (1 - 0.08 * spike), yt + spikeH * spike, sp.z * (1 - 0.08 * spike))
+ seg.add(CrownSeg(b, tt, b.z))
+ }
+ val keep = seg.filter { q -> if (side > 0) q.z >= 0 else q.z < 0.02 }.sortedBy { it.b.x }
+ if (keep.size < 2) return
+ val shape = Path2D()
+ keep.forEachIndexed { i, q -> if (i > 0) shape.lineTo(q.tt.x, q.tt.y) else shape.moveTo(q.tt.x, q.tt.y) }
+ for (i in keep.indices.reversed()) shape.lineTo(keep[i].b.x, keep[i].b.y)
+ shape.closePath()
+
+ val dark = side < 0
+ ctx.fillStyle = ctx.lin(
+ 0.0, -h.ry * 1.05, 0.0, -h.ry * 0.45,
+ if (dark) listOf(0.0 to "#C98A12", 1.0 to "#8A5A06") else listOf(0.0 to "#FFE58A", 0.5 to "#FBBF24", 1.0 to "#D08A0B"),
+ )
+ ctx.fill(shape)
+ if (dark) return
+
+ ctx.save()
+ ctx.clip(shape)
+ ctx.fillStyle = ctx.lin(
+ -h.rx, 0.0, h.rx, 0.0,
+ listOf(0.0 to "rgba(120,70,0,0.25)", 0.45 to "rgba(255,255,255,0)", 0.62 to "rgba(255,255,255,0.35)", 1.0 to "rgba(120,70,0,0.25)"),
+ )
+ ctx.fill(shape)
+ ctx.restore()
+ if (simple) return
+
+ val gems = listOf("#EF4444", "#3B82F6", "#22C55E", "#A855F7")
+ for (k in 0 until n) {
+ val lon = -PI + (k + 0.5) / n * 2 * PI
+ val sp = surf(yt, lon, s)
+ val tipP = proj(h, sp.x * 0.92, yt + spikeH, sp.z * 0.92)
+ val mid = proj(h, surf((yb + yt) / 2, lon, s * 1.01))
+ if (mid.z <= 0.12) continue
+ val r = h.R * 0.055
+ ctx.beginPath()
+ ctx.arc(tipP.x, tipP.y - r * 0.5, r, 0.0, PI * 2)
+ ctx.fillStyle = ctx.rad(tipP.x - r * 0.3, tipP.y - r, 0.0, r * 1.2, listOf(0.0 to "#FFF6CC", 1.0 to "#E0A21A"))
+ ctx.fill()
+ val gr = h.R * 0.075
+ ctx.beginPath()
+ ctx.ellipse(mid.x, mid.y, gr * max(0.35, mid.z), gr, 0.0, 0.0, PI * 2)
+ ctx.fillStyle(gems[k % gems.size])
+ ctx.fill()
+ ctx.beginPath()
+ ctx.arc(mid.x - gr * 0.25 * mid.z, mid.y - gr * 0.35, gr * 0.28, 0.0, PI * 2)
+ ctx.fillStyle("rgba(255,255,255,0.75)")
+ ctx.fill()
+ }
+}
+
+internal fun crownFront(ctx: Ctx2D, h: Head, body: Path2D, simple: Boolean) {
+ // shadow of the band on the head
+ ctx.save()
+ ctx.clip(body)
+ ctx.clip(capClip(h, CROWN_YB - 0.1, 1.0))
+ ctx.clip(invert(capClip(h, CROWN_YB, 1.0), h), true)
+ ctx.fillStyle("rgba(80,50,0,0.12)")
+ ctx.fillAll(h)
+ ctx.restore()
+ crownPart(ctx, h, 1, simple)
+}
+
+// ── Witch hat ─────────────────────────────────────────────────────────────────
+
+internal fun witchBrim(h: Head): List<P3> {
+ val y = 0.7
+ val rr = 1.42
+ val pts = ArrayList<P3>()
+ for (i in 0..120) {
+ val a = -PI + i.toDouble() / 120 * 2 * PI
+ val wob = 1 + 0.035 * sin(a * 3 + 0.6)
+ val droop = -0.1 * abs(sin(a)).pow(2) // the edges droop a little
+ pts.add(proj(h, rr * wob * sin(a), y + droop, rr * wob * cos(a)))
+ }
+ return pts
+}
+
+internal fun closedPath(pts: List<Pt2>): Path2D {
+ val p = Path2D()
+ pts.forEachIndexed { i, q -> if (i > 0) p.lineTo(q.x, q.y) else p.moveTo(q.x, q.y) }
+ p.closePath()
+ return p
+}
+
+/** The whole brim, behind the head; the front draws its front half again. */
+internal fun witchHatBack(ctx: Ctx2D, h: Head) {
+ ctx.fillStyle = ctx.lin(0.0, -h.ry, 0.0, -h.ry * 0.4, listOf(0.0 to "#2A0A4F", 1.0 to "#3B0F6B"))
+ ctx.fill(closedPath(witchBrim(h).pts()))
+}
+
+internal fun witchHatFront(ctx: Ctx2D, h: Head, body: Path2D) {
+ val all = witchBrim(h)
+ val brim = closedPath(all.pts())
+ val fr = all.filter { it.z >= 0 }.sortedBy { it.x }
+
+ ctx.save()
+ ctx.clip(body)
+ ctx.clip(capClip(h, 0.5, 1.0))
+ ctx.fillStyle("rgba(40,0,70,0.10)")
+ ctx.fillAll(h)
+ ctx.restore()
+
+ ctx.fillStyle = ctx.lin(0.0, -h.ry * 0.9, 0.0, -h.ry * 0.3, listOf(0.0 to "#5B21B6", 1.0 to "#3B0764"))
+ ctx.fill(brim)
+ if (fr.size > 1) {
+ ctx.polyline(fr.pts())
+ ctx.strokeStyle("rgba(190,150,255,0.35)")
+ ctx.lineWidth = h.R * 0.035
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+ }
+
+ // cone: base ring r = 0.62 at y = 0.74, tall apex, the tip bends over
+ val baseR = 0.62
+ val by = 0.74
+ val bl = proj(h, -baseR, by, 0.0)
+ val br = proj(h, baseR, by, 0.0)
+ val c = proj(h, 0.0, by, 0.0)
+ val lean = 0.1 + h.physDx * 0.15
+ val top = Pt2(c.x + h.rx * 0.18 + sin(lean) * h.ry * 0.3, c.y - h.ry * 1.25)
+ val tip = Pt2(top.x + h.rx * (0.45 + h.physDx * 0.25), top.y + h.ry * (0.22 + h.physDy * 0.1))
+ val capFront = frontArc(h, by, baseR / ringR(by)).filter { it.x >= bl.x - 1 && it.x <= br.x + 1 }
+ val cone = Path2D()
+ cone.moveTo(bl.x, bl.y)
+ cone.bezierCurveTo(bl.x + h.rx * 0.12, bl.y - h.ry * 0.5, top.x - h.rx * 0.28, top.y + h.ry * 0.25, top.x - h.rx * 0.02, top.y - h.ry * 0.02)
+ cone.quadraticCurveTo(top.x + h.rx * 0.25, top.y - h.ry * 0.08, tip.x, tip.y)
+ cone.quadraticCurveTo(top.x + h.rx * 0.22, top.y + h.ry * 0.08, top.x + h.rx * 0.14, top.y + h.ry * 0.22)
+ cone.bezierCurveTo(br.x - h.rx * 0.18, c.y - h.ry * 0.45, br.x - h.rx * 0.02, br.y - h.ry * 0.2, br.x, br.y)
+ for (i in capFront.indices.reversed()) cone.lineTo(capFront[i].x, capFront[i].y)
+ cone.closePath()
+ ctx.fillStyle = ctx.lin(bl.x, top.y, br.x, bl.y, listOf(0.0 to "#7C3AED", 0.55 to "#4C1D95", 1.0 to "#2E1065"))
+ ctx.fill(cone)
+
+ ctx.save()
+ ctx.clip(cone)
+ ctx.fillStyle = ctx.lin(bl.x, 0.0, br.x, 0.0, listOf(0.0 to "rgba(255,255,255,0.22)", 0.4 to "rgba(255,255,255,0)", 1.0 to "rgba(0,0,0,0.15)"))
+ ctx.fill(cone)
+ // crease where the tip bends
+ ctx.beginPath()
+ ctx.moveTo(top.x - h.rx * 0.05, top.y + h.ry * 0.05)
+ ctx.quadraticCurveTo(top.x + h.rx * 0.1, top.y + h.ry * 0.12, top.x + h.rx * 0.2, top.y + h.ry * 0.06)
+ ctx.strokeStyle("rgba(20,0,40,0.35)")
+ ctx.lineWidth = h.R * 0.05
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+ // orange band, just above the base
+ val fc = proj(h, 0.0, by, baseR)
+ val lift = h.ry * 0.11
+ ctx.beginPath()
+ ctx.moveTo(bl.x - 2, bl.y - lift)
+ ctx.quadraticCurveTo(fc.x, 2 * (fc.y - lift) - (bl.y + br.y) / 2, br.x + 2, br.y - lift)
+ ctx.strokeStyle("#F97316")
+ ctx.lineWidth = h.ry * 0.17
+ ctx.lineCap = Cap.BUTT
+ ctx.stroke()
+ ctx.restore()
+
+ // buckle
+ val bw = h.R * 0.2
+ val bh = h.R * 0.16
+ ctx.save()
+ ctx.translate(fc.x, fc.y - h.ry * 0.11)
+ ctx.roundRect(-bw / 2, -bh / 2, bw, bh, bh * 0.25)
+ ctx.fillStyle("#FCD34D")
+ ctx.fill()
+ ctx.roundRect(-bw / 2 + bw * 0.24, -bh / 2 + bh * 0.28, bw * 0.52, bh * 0.44, bh * 0.1)
+ ctx.fillStyle("#C2410C")
+ ctx.fill()
+ ctx.restore()
+}
+
+// ── Glasses (pinned to the real eye positions) ────────────────────────────────
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitWear.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitWear.kt
new file mode 100644
index 00000000..5d2404b1
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/OutfitWear.kt
@@ -0,0 +1,320 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.core.Ease
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.floor
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+
+// Glasses, scarf, pumpkin, bow, bunny ears: parts of the port in Outfits.kt.
+
+internal fun sunglasses(ctx: Ctx2D, h: Head, body: Path2D) {
+ val eyes = eyeFrames(h)
+ val w = h.R * 0.62
+ val hh = h.R * 0.46
+ ctx.save()
+ ctx.clip(body)
+ ctx.strokeStyle("#111317")
+ ctx.lineCap = Cap.ROUND
+ val l = eyes[0]
+ val r = eyes[1]
+ if (l.visible && r.visible) {
+ ctx.beginPath()
+ ctx.moveTo(l.x + (w / 2) * l.fx * 0.9, l.y - hh * 0.18)
+ ctx.quadraticCurveTo((l.x + r.x) / 2, (l.y + r.y) / 2 - hh * 0.42, r.x - (w / 2) * r.fx * 0.9, r.y - hh * 0.18)
+ ctx.lineWidth = h.R * 0.07
+ ctx.stroke()
+ }
+ ctx.lineWidth = h.R * 0.06
+ for (e in eyes) {
+ if (!e.visible) continue
+ ctx.beginPath()
+ ctx.moveTo(e.x + (e.sd * w) / 2 * e.fx, e.y - hh * 0.2)
+ ctx.lineTo(e.sd * h.rx * 1.05, e.y - hh * 0.35)
+ ctx.stroke()
+ }
+ for (e in eyes) {
+ if (!e.visible) continue
+ ctx.save()
+ ctx.translate(e.x, e.y)
+ ctx.scale(e.fx, e.fy)
+ ctx.roundRect(-w / 2, -hh / 2, w, hh, hh * 0.42)
+ ctx.fillStyle("rgba(17,19,23,0.82)")
+ ctx.fill()
+ ctx.lineWidth = h.R * 0.05
+ ctx.strokeStyle("#0B0C0F")
+ ctx.stroke()
+ ctx.beginPath()
+ ctx.moveTo(-w * 0.28, -hh * 0.05)
+ ctx.lineTo(-w * 0.05, -hh * 0.3)
+ ctx.strokeStyle("rgba(255,255,255,0.45)")
+ ctx.stroke()
+ ctx.restore()
+ }
+ ctx.restore()
+}
+
+internal fun roundGlasses(ctx: Ctx2D, h: Head, body: Path2D) {
+ val eyes = eyeFrames(h)
+ val d = h.R * 0.56
+ ctx.save()
+ ctx.clip(body)
+ ctx.strokeStyle("#8A4B12")
+ ctx.lineCap = Cap.ROUND
+ val l = eyes[0]
+ val r = eyes[1]
+ if (l.visible && r.visible) {
+ ctx.beginPath()
+ ctx.moveTo(l.x + (d / 2) * l.fx, l.y - d * 0.08)
+ ctx.quadraticCurveTo((l.x + r.x) / 2, (l.y + r.y) / 2 - d * 0.3, r.x - (d / 2) * r.fx, r.y - d * 0.08)
+ ctx.lineWidth = h.R * 0.055
+ ctx.stroke()
+ }
+ ctx.lineWidth = h.R * 0.05
+ for (e in eyes) {
+ if (!e.visible) continue
+ ctx.beginPath()
+ ctx.moveTo(e.x + (e.sd * d) / 2 * e.fx, e.y - d * 0.1)
+ ctx.lineTo(e.sd * h.rx * 1.05, e.y - d * 0.25)
+ ctx.stroke()
+ }
+ for (e in eyes) {
+ if (!e.visible) continue
+ ctx.save()
+ ctx.translate(e.x, e.y)
+ ctx.scale(e.fx, e.fy)
+ ctx.beginPath()
+ ctx.arc(0.0, 0.0, d / 2, 0.0, PI * 2)
+ ctx.fillStyle("rgba(190,225,255,0.18)")
+ ctx.fill()
+ ctx.lineWidth = h.R * 0.065
+ ctx.strokeStyle("#9A5A1A")
+ ctx.stroke()
+ ctx.beginPath()
+ ctx.arc(0.0, 0.0, d / 2 - h.R * 0.03, PI * 1.1, PI * 1.45)
+ ctx.strokeStyle("rgba(255,255,255,0.55)")
+ ctx.lineWidth = h.R * 0.03
+ ctx.stroke()
+ ctx.restore()
+ }
+ ctx.restore()
+}
+
+// ── Scarf ─────────────────────────────────────────────────────────────────────
+
+internal fun scarf(ctx: Ctx2D, h: Head) {
+ val s = 1.05
+ val y0 = -0.34
+ val y1 = -0.66
+ val top = frontArc(h, y0, s)
+ val bot = frontArc(h, y1, s)
+ if (top.isEmpty() || bot.isEmpty()) return
+ val band = Path2D()
+ top.forEachIndexed { i, q -> if (i > 0) band.lineTo(q.x, q.y) else band.moveTo(q.x, q.y) }
+ for (i in bot.indices.reversed()) band.lineTo(bot[i].x, bot[i].y)
+ band.closePath()
+
+ ctx.save()
+ ctx.clip(bodyOutline(h.rx * s, h.ry * s))
+ ctx.fillStyle = ctx.lin(0.0, -h.ry * 0.2, 0.0, h.ry * 0.7, listOf(0.0 to "#F87171", 1.0 to "#B91C1C"))
+ ctx.fill(band)
+ ctx.save()
+ ctx.clip(band)
+ ctx.strokeStyle("rgba(255,255,255,0.85)")
+ ctx.lineCap = Cap.ROUND
+ for (lon in listOf(-1.0, -0.45, 0.1, 0.65, 1.2)) {
+ val a = proj(h, surf(y0, lon, s))
+ val b = proj(h, surf(y1, lon, s))
+ if (a.z < 0) continue
+ ctx.beginPath()
+ ctx.moveTo(a.x, a.y - 4)
+ ctx.lineTo(b.x, b.y + 4)
+ ctx.lineWidth = h.R * 0.09 * max(0.3, a.z)
+ ctx.stroke()
+ }
+ ctx.restore()
+ ctx.fillStyle = ctx.lin(0.0, -h.ry * 0.5, 0.0, h.ry * 0.3, listOf(0.0 to "rgba(255,255,255,0.18)", 1.0 to "rgba(0,0,0,0.1)"))
+ ctx.fill(band)
+ ctx.restore()
+
+ // the hanging end, from the knot
+ val k = proj(h, surf((y0 + y1) / 2, -0.55, s * 1.03))
+ if (k.z <= 0) return
+ val sw = h.physDx * h.rx * 0.12
+ val end = Path2D()
+ end.moveTo(k.x - h.R * 0.16, k.y)
+ end.quadraticCurveTo(k.x - h.R * 0.24 + sw, k.y + h.ry * 0.35, k.x - h.R * 0.2 + sw * 1.4, k.y + h.ry * 0.62)
+ end.lineTo(k.x + h.R * 0.06 + sw * 1.4, k.y + h.ry * 0.6)
+ end.quadraticCurveTo(k.x + h.R * 0.02 + sw, k.y + h.ry * 0.3, k.x + h.R * 0.12, k.y)
+ end.closePath()
+ ctx.fillStyle = ctx.lin(0.0, k.y, 0.0, k.y + h.ry * 0.6, listOf(0.0 to "#EF4444", 1.0 to "#B91C1C"))
+ ctx.fill(end)
+ ctx.save()
+ ctx.clip(end)
+ ctx.fillStyle("rgba(255,255,255,0.85)")
+ for (t in listOf(0.35, 0.7)) ctx.fillRect(k.x - h.R * 0.4 + sw, k.y + h.ry * 0.62 * t, h.R * 0.8, h.R * 0.07)
+ ctx.restore()
+ // fringe
+ ctx.strokeStyle("#DC2626")
+ ctx.lineWidth = h.R * 0.035
+ ctx.lineCap = Cap.ROUND
+ for (i in 0 until 4) {
+ val fx = k.x - h.R * 0.17 + sw * 1.4 + i * h.R * 0.075
+ ctx.beginPath()
+ ctx.moveTo(fx, k.y + h.ry * 0.6)
+ ctx.lineTo(fx, k.y + h.ry * 0.72)
+ ctx.stroke()
+ }
+ // knot
+ ctx.beginPath()
+ ctx.ellipse(k.x, k.y, h.R * 0.17, h.R * 0.14, 0.2, 0.0, PI * 2)
+ ctx.fillStyle = ctx.rad(k.x - h.R * 0.05, k.y - h.R * 0.05, 0.0, h.R * 0.2, listOf(0.0 to "#F87171", 1.0 to "#B91C1C"))
+ ctx.fill()
+}
+
+// ── Pumpkin (the body colours come from the engine) ───────────────────────────
+
+val PUMPKIN_BODY: Pair<String, String> = "#FFA94D" to "#E8590C"
+
+internal fun pumpkin(ctx: Ctx2D, h: Head, body: Path2D, simple: Boolean) {
+ if (!simple) {
+ ctx.save()
+ ctx.clip(body)
+ ctx.lineCap = Cap.ROUND
+ for (lon in listOf(-1.15, -0.55, 0.0, 0.55, 1.15)) {
+ val pts = ArrayList<P3>()
+ for (i in 0..30) {
+ val q = proj(h, surf(-0.98 + 1.96 * i / 30, lon, 1.0))
+ if (q.z > 0) pts.add(q)
+ }
+ if (pts.size < 2) continue
+ val zz = pts[floor(pts.size / 2.0).toInt()].z
+ ctx.polyline(pts.pts())
+ ctx.strokeStyle("rgba(150,50,0,${0.22 * zz})")
+ ctx.lineWidth = h.R * 0.12
+ ctx.stroke()
+ ctx.polyline(pts.map { Pt2(it.x + h.R * 0.07, it.y) })
+ ctx.strokeStyle("rgba(255,220,170,${0.18 * zz})")
+ ctx.lineWidth = h.R * 0.04
+ ctx.stroke()
+ }
+ ctx.restore()
+ }
+ val t = proj(h, 0.02, 1.0, 0.0)
+ // stem
+ ctx.beginPath()
+ ctx.moveTo(t.x - h.R * 0.09, t.y + h.R * 0.04)
+ ctx.quadraticCurveTo(t.x - h.R * 0.08, t.y - h.R * 0.22, t.x + h.R * 0.08, t.y - h.R * 0.3)
+ ctx.lineTo(t.x + h.R * 0.13, t.y - h.R * 0.22)
+ ctx.quadraticCurveTo(t.x + h.R * 0.04, t.y - h.R * 0.15, t.x + h.R * 0.08, t.y + h.R * 0.04)
+ ctx.closePath()
+ ctx.fillStyle = ctx.lin(t.x - h.R * 0.1, 0.0, t.x + h.R * 0.1, 0.0, listOf(0.0 to "#65A30D", 1.0 to "#3F6212"))
+ ctx.fill()
+ // leaf
+ ctx.save()
+ ctx.translate(t.x - h.R * 0.06, t.y - h.R * 0.02)
+ ctx.rotate(-0.5)
+ ctx.beginPath()
+ ctx.moveTo(0.0, 0.0)
+ ctx.quadraticCurveTo(-h.R * 0.18, -h.R * 0.2, -h.R * 0.38, -h.R * 0.02)
+ ctx.quadraticCurveTo(-h.R * 0.18, h.R * 0.1, 0.0, 0.0)
+ ctx.fillStyle = ctx.lin(0.0, -h.R * 0.15, -h.R * 0.3, 0.0, listOf(0.0 to "#84CC16", 1.0 to "#4D7C0F"))
+ ctx.fill()
+ ctx.beginPath()
+ ctx.moveTo(-h.R * 0.02, -h.R * 0.01)
+ ctx.quadraticCurveTo(-h.R * 0.18, -h.R * 0.08, -h.R * 0.32, -h.R * 0.03)
+ ctx.strokeStyle("rgba(30,60,0,0.4)")
+ ctx.lineWidth = h.R * 0.02
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+ ctx.restore()
+ if (simple) return
+ // curly tendril
+ ctx.beginPath()
+ ctx.moveTo(t.x + h.R * 0.1, t.y - h.R * 0.12)
+ ctx.bezierCurveTo(t.x + h.R * 0.3, t.y - h.R * 0.25, t.x + h.R * 0.35, t.y - h.R * 0.02, t.x + h.R * 0.22, t.y - h.R * 0.06)
+ ctx.strokeStyle("#4D7C0F")
+ ctx.lineWidth = h.R * 0.03
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+}
+
+// ── Bow (anchored in 3D, turns with the head) ─────────────────────────────────
+
+internal fun bow(ctx: Ctx2D, h: Head) {
+ val a = proj(h, surf(0.86, 0.55, 1.02))
+ if (a.z < -0.2) return
+ val s = h.R * 0.26
+ val sq = max(0.45, cos(0.55 + h.yaw))
+ ctx.save()
+ ctx.translate(a.x, a.y)
+ ctx.rotate(0.35 + h.yaw * 0.3)
+ ctx.scale(sq, 1.0)
+ for (sd in listOf(-1.0, 1.0)) {
+ ctx.beginPath()
+ ctx.moveTo(0.0, 0.0)
+ ctx.bezierCurveTo(sd * s * 0.6, -s * 0.85, sd * s * 1.35, -s * 0.55, sd * s * 1.15, 0.0)
+ ctx.bezierCurveTo(sd * s * 1.35, s * 0.55, sd * s * 0.6, s * 0.85, 0.0, 0.0)
+ ctx.fillStyle = ctx.lin(0.0, -s, 0.0, s, listOf(0.0 to "#FF8CC6", 1.0 to "#DB2777"))
+ ctx.fill()
+ ctx.beginPath()
+ ctx.moveTo(sd * s * 0.25, -s * 0.05)
+ ctx.quadraticCurveTo(sd * s * 0.7, -s * 0.15, sd * s * 0.95, -s * 0.05)
+ ctx.strokeStyle("rgba(140,10,70,0.35)")
+ ctx.lineWidth = s * 0.08
+ ctx.lineCap = Cap.ROUND
+ ctx.stroke()
+ }
+ ctx.beginPath()
+ ctx.ellipse(0.0, 0.0, s * 0.24, s * 0.3, 0.0, 0.0, PI * 2)
+ ctx.fillStyle = ctx.rad(-s * 0.06, -s * 0.1, 0.0, s * 0.35, listOf(0.0 to "#FFB3D9", 1.0 to "#C2185B"))
+ ctx.fill()
+ ctx.restore()
+}
+
+// ── Bunny ears (always behind the head) ───────────────────────────────────────
+
+internal fun bunnyEars(ctx: Ctx2D, h: Head) {
+ val r = h.R
+ val earH = r * 0.85
+ for (sd in listOf(-1.0, 1.0)) {
+ val root = proj(h, sd * 0.45, 0.92, 0.0)
+ val rootL = proj(h, sd * 0.45 - 0.22, 0.92, 0.0)
+ val rootR = proj(h, sd * 0.45 + 0.22, 0.92, 0.0)
+ val hw = max(r * 0.04, abs(rootR.x - rootL.x) / 2)
+ ctx.save()
+ ctx.translate(root.x, root.y - earH * 0.15)
+ ctx.beginPath()
+ ctx.ellipse(0.0, 0.0, hw, earH / 2, 0.0, 0.0, PI * 2)
+ ctx.fillStyle("#F9F0F0")
+ ctx.fill()
+ ctx.strokeStyle("rgba(0,0,0,0.06)")
+ ctx.lineWidth = 0.8
+ ctx.stroke()
+ ctx.beginPath()
+ ctx.ellipse(0.0, -earH / 2 + r * 0.1 + earH * 0.325, hw * 0.5, earH * 0.325, 0.0, 0.0, PI * 2)
+ ctx.fillStyle("rgba(252,165,165,0.7)")
+ ctx.fill()
+ ctx.restore()
+ }
+}
+
+// ── Layers and transitions ────────────────────────────────────────────────────
+
+/** What Mochi can wear. The raw values are the Mac's and the PC's (stored in the preferences), keep them stable. */
+enum class Outfit(val id: String) {
+ NONE("none"), PARTY_HAT("partyHat"), BEANIE("beanie"), CROWN("crown"), SUNGLASSES("sunglasses"),
+ ROUND_GLASSES("roundGlasses"), BOW("bow"), SCARF("scarf"), WITCH_HAT("witchHat"), PUMPKIN("pumpkin"),
+ SANTA_HAT("santaHat"), BUNNY_EARS("bunnyEars");
+}
+
+/** Glasses, bow, scarf and pumpkin are on the face: behind the head once it has turned away. */
+internal val ON_FACE = setOf(Outfit.SUNGLASSES, Outfit.ROUND_GLASSES, Outfit.BOW, Outfit.SCARF, Outfit.PUMPKIN)
+internal val HATS = setOf(Outfit.BEANIE, Outfit.SANTA_HAT, Outfit.PARTY_HAT, Outfit.CROWN, Outfit.WITCH_HAT)
+
+/** [presence] 0 = gone, 1 = fully on (animated by the engine); [morph] is Mochi's mailbox morph: outfits fade as he turns into a box. */
+data class OutfitState(val presence: Double, val morph: Double)
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Outfits.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Outfits.kt
new file mode 100644
index 00000000..a7d48272
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Outfits.kt
@@ -0,0 +1,136 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.core.Ease
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.floor
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.sin
+
+/** Which outfit is drawn behind and in front of Mochi. The drawing of each is in OutfitHats.kt and OutfitWear.kt, the shared helpers in OutfitDrawing.kt. */
+
+private fun faceTurnedAway(h: Head) = proj(h, 0.0, 0.0, 1.0).z < 0
+
+private fun drawFace(ctx: Ctx2D, outfit: Outfit, h: Head, body: Path2D, simple: Boolean) {
+ when (outfit) {
+ Outfit.SUNGLASSES -> sunglasses(ctx, h, body)
+ Outfit.ROUND_GLASSES -> roundGlasses(ctx, h, body)
+ Outfit.SCARF -> scarf(ctx, h)
+ Outfit.PUMPKIN -> pumpkin(ctx, h, body, simple)
+ Outfit.BOW -> bow(ctx, h)
+ else -> {}
+ }
+}
+
+fun layerAlpha(st: OutfitState): Double {
+ val morphFade = 1 - min(1.0, max(0.0, (st.morph - 0.3) / 0.2))
+ return morphFade * min(1.0, st.presence * 2.5)
+}
+
+/** The parts behind Mochi's body. [ctx] is in body space (translated to the body centre, tilted and squashed like the body). */
+fun drawOutfitBehind(ctx: Ctx2D, outfit: Outfit, h: Head, st: OutfitState) {
+ if (outfit == Outfit.NONE) return
+ val alpha = layerAlpha(st)
+ if (alpha <= 0.005) return
+ val simple = h.R < SIMPLIFY_BELOW_R
+ val body = bodyOutline(h.rx, h.ry)
+
+ if (outfit in ON_FACE) {
+ if (faceTurnedAway(h)) ctx.withLayer(alpha) { l -> drawFace(l, outfit, h, body, simple) }
+ return
+ }
+ val posP = Ease.back(st.presence)
+ val hatScale = 0.85 + 0.15 * posP
+ ctx.save()
+ ctx.translate(0.0, -(1 - posP) * h.ry)
+ ctx.scale(hatScale, hatScale)
+ ctx.withLayer(alpha) { l ->
+ when (outfit) {
+ Outfit.BUNNY_EARS -> bunnyEars(l, h)
+ Outfit.CROWN -> crownPart(l, h, -1, simple)
+ Outfit.WITCH_HAT -> witchHatBack(l, h)
+ else -> {}
+ }
+ }
+ ctx.restore()
+}
+
+/** The parts in front of Mochi, drawn after the body and the eyes. */
+fun drawOutfitFront(ctx: Ctx2D, outfit: Outfit, h: Head, st: OutfitState) {
+ if (outfit == Outfit.NONE || outfit == Outfit.BUNNY_EARS) return
+ if (outfit in ON_FACE && faceTurnedAway(h)) return
+ val alpha = layerAlpha(st)
+ if (alpha <= 0.005) return
+ val simple = h.R < SIMPLIFY_BELOW_R
+ val body = bodyOutline(h.rx, h.ry)
+ val p = st.presence
+ val posP = Ease.back(p)
+
+ ctx.save()
+ if (outfit in HATS) {
+ // hats drop onto the head and settle
+ val hatScale = 0.85 + 0.15 * posP
+ ctx.translate(0.0, -(1 - posP) * h.ry)
+ ctx.scale(hatScale, hatScale)
+ } else if (outfit == Outfit.SUNGLASSES || outfit == Outfit.ROUND_GLASSES) {
+ ctx.translate(0.0, (1 - p) * 0.25 * h.ry)
+ } else if (outfit == Outfit.SCARF) {
+ ctx.translate(0.0, (1 - p) * 0.3 * h.ry)
+ } else if (outfit == Outfit.BOW) {
+ ctx.scale(max(0.001, posP), max(0.001, posP))
+ }
+ ctx.withLayer(alpha) { l ->
+ when (outfit) {
+ Outfit.BEANIE -> beanie(l, h, body, simple)
+ Outfit.SANTA_HAT -> santaHat(l, h, body)
+ Outfit.PARTY_HAT -> partyHat(l, h, simple)
+ Outfit.CROWN -> crownFront(l, h, body, simple)
+ Outfit.WITCH_HAT -> witchHatFront(l, h, body)
+ else -> drawFace(l, outfit, h, body, simple)
+ }
+ }
+ ctx.restore()
+}
+
+// ── Wardrobe icons ────────────────────────────────────────────────────────────
+
+private const val INK = "rgb(26,20,18)"
+
+/** A little Mochi wearing [outfit], centred in a [size] x [size] icon (the PC's iconMochi). */
+fun drawIconMochi(ctx: Ctx2D, size: Double, outfit: Outfit) {
+ val r = 10.0
+ val h = makeHead(r)
+ val cx = size / 2
+ val cy = size / 2 + r * 0.62
+ val st = OutfitState(1.0, 0.0)
+ ctx.save()
+ ctx.translate(cx, cy)
+ drawOutfitBehind(ctx, outfit, h, st)
+ val body = bodyOutline(h.rx, h.ry)
+ val (top, bottom) = if (outfit == Outfit.PUMPKIN) PUMPKIN_BODY else ("rgb(237,237,239)" to "rgb(196,197,202)")
+ ctx.fillStyle = ctx.lin(h.rx * 0.7, -h.ry * 0.85, -h.rx * 0.8, h.ry * 0.9, listOf(0.0 to top, 1.0 to bottom))
+ ctx.fill(body)
+ ctx.fillStyle = ctx.rad(0.0, 0.0, r * 0.15, r * 1.25, listOf(0.0 to "rgba(0,0,0,0)", 0.6 to "rgba(0,0,0,0)", 1.0 to "rgba(0,0,0,0.2)"))
+ ctx.fill(body)
+ ctx.fillStyle = ctx.rad(h.rx * 0.34, -h.ry * 0.46, 0.0, r * 0.42, listOf(0.0 to "rgba(255,255,255,0.55)", 1.0 to "rgba(255,255,255,0)"))
+ ctx.fill(body)
+ ctx.save()
+ ctx.clip(body)
+ ctx.fillStyle(INK)
+ for (e in eyeFrames(h)) {
+ if (!e.visible) continue
+ ctx.save()
+ ctx.translate(e.x, e.y)
+ ctx.scale(e.fx, e.fy)
+ val hh = max(e.h, e.w * 0.3)
+ ctx.roundRect(-e.w / 2, -hh / 2, e.w, hh, min(e.w / 2, hh / 2))
+ ctx.fill()
+ ctx.restore()
+ }
+ ctx.restore()
+ drawOutfitFront(ctx, outfit, h, st)
+ ctx.restore()
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Wardrobe.kt b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Wardrobe.kt
new file mode 100644
index 00000000..7c3b32fb
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/mochi/outfit/Wardrobe.kt
@@ -0,0 +1,76 @@
+package com.coucou.android.mochi.outfit
+
+import java.time.LocalDate
+import java.time.temporal.ChronoUnit
+
+/**
+ * Mochi's wardrobe logic, a port of windows/src/mochi/wardrobe.ts: what is stored ("auto" or an outfit),
+ * and which outfit "auto" means on a given day. The raw values are the Mac's and the PC's: keep them stable.
+ */
+object Wardrobe {
+ /** Order of the wardrobe: "auto" (dress for the season), "none", then the outfits. */
+ val SELECTIONS: List<String> = listOf(
+ "auto", "none", "partyHat", "beanie", "crown", "sunglasses", "roundGlasses",
+ "bow", "scarf", "witchHat", "pumpkin", "santaHat", "bunnyEars",
+ )
+ const val AUTO = "auto"
+ const val DEFAULT = AUTO
+ /** The phone's own choice when it does not pick an outfit itself: wear what the computer says. */
+ const val FOLLOW = "computer"
+
+ /** A phone-local choice read from the preferences: "computer", "auto" or an outfit; anything else follows the computer. */
+ fun parseLocal(raw: String?): String = if (raw != null && (raw == FOLLOW || raw in SELECTIONS)) raw else FOLLOW
+
+ /** What is worn, as a selection: the phone's own choice, or the computer's when the phone follows it. */
+ fun choose(local: String, computer: String): String = if (local == FOLLOW) parse(computer) else parseLocal(local)
+
+ /** The names shown to the user (the PC's English names). */
+ val LABELS: Map<String, String> = mapOf(
+ "auto" to "Auto (seasons)", "none" to "None", "partyHat" to "Party hat", "beanie" to "Beanie", "crown" to "Crown",
+ "sunglasses" to "Sunglasses", "roundGlasses" to "Round glasses", "bow" to "Bow", "scarf" to "Scarf",
+ "witchHat" to "Witch hat", "pumpkin" to "Pumpkin", "santaHat" to "Santa hat", "bunnyEars" to "Bunny ears",
+ )
+
+ /** A stored value, or one received from the computer, to a selection; anything unknown means "auto" (like the Mac). */
+ fun parse(raw: String?): String = if (raw != null && raw in SELECTIONS) raw else DEFAULT
+
+ fun outfitOf(id: String): Outfit = Outfit.entries.firstOrNull { it.id == id } ?: Outfit.NONE
+
+ /** Easter Sunday of [year] (Meeus/Jones/Butcher) as month 1..12 and day. */
+ fun easterDate(year: Int): Pair<Int, Int> {
+ val a = year % 19
+ val b = year / 100
+ val c = year % 100
+ val d = b / 4
+ val e = b % 4
+ val f = (b + 8) / 25
+ val g = (b - f + 1) / 3
+ val h = (19 * a + b - d - g + 15) % 30
+ val i = c / 4
+ val k = c % 4
+ val l = (32 + 2 * e + 2 * i - h - k) % 7
+ val m = (a + 11 * h + 22 * l) / 451
+ val month = (h + l - 7 * m + 114) / 31
+ val day = (h + l - 7 * m + 114) % 31 + 1
+ return month to day
+ }
+
+ /** The seasonal outfit for [date] in the user's calendar. Priority: party hat, Santa hat, witch hat, bunny ears, sunglasses, none. */
+ fun seasonal(date: LocalDate): Outfit {
+ val day = date.dayOfMonth
+ val month = date.monthValue
+ val year = date.year
+ if ((month == 12 && day == 31) || (month == 1 && day <= 2)) return Outfit.PARTY_HAT // Dec 31 - Jan 2
+ if (month == 12 && day <= 26) return Outfit.SANTA_HAT // Dec 1-26
+ if (month == 10 || (month == 11 && day == 1)) return Outfit.WITCH_HAT // Oct 1 - Nov 1
+ // Two days before Easter to the day after.
+ val (em, ed) = easterDate(year)
+ val delta = ChronoUnit.DAYS.between(LocalDate.of(year, em, ed), date)
+ if (delta in -2..1) return Outfit.BUNNY_EARS
+ if ((month == 6 && day >= 21) || month == 7 || month == 8) return Outfit.SUNGLASSES // Jun 21 - Aug 31
+ return Outfit.NONE
+ }
+
+ /** "auto" means the season's outfit; anything else is worn as chosen. */
+ fun resolve(selection: String, date: LocalDate): Outfit = if (selection == AUTO) seasonal(date) else outfitOf(selection)
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/scan/QrDecoder.kt b/android/app/src/main/kotlin/com/coucou/android/scan/QrDecoder.kt
new file mode 100644
index 00000000..eb22f270
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/scan/QrDecoder.kt
@@ -0,0 +1,45 @@
+package com.coucou.android.scan
+
+import com.google.zxing.BarcodeFormat
+import com.google.zxing.BinaryBitmap
+import com.google.zxing.DecodeHintType
+import com.google.zxing.LuminanceSource
+import com.google.zxing.MultiFormatReader
+import com.google.zxing.PlanarYUVLuminanceSource
+import com.google.zxing.ReaderException
+import com.google.zxing.common.HybridBinarizer
+
+/**
+ * Reads a QR code out of one camera frame (zxing-core, pure Java, offline). Only the brightness plane of the
+ * frame is looked at, and nothing is kept: the bytes are not stored, logged or sent anywhere. Not thread-safe:
+ * one analyzer thread owns one decoder.
+ */
+class QrDecoder {
+ private val reader = MultiFormatReader().apply {
+ setHints(
+ mapOf(
+ DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
+ DecodeHintType.TRY_HARDER to true,
+ ),
+ )
+ }
+
+ /**
+ * [luma]: the brightness of the frame, [rowStride] bytes per row (it can be wider than [width]),
+ * [height] rows. Null when there is no QR code in it. A light code on a dark background is read too.
+ */
+ fun decode(luma: ByteArray, rowStride: Int, width: Int, height: Int): String? {
+ if (width <= 0 || height <= 0 || rowStride < width || luma.size < rowStride * (height - 1) + width) return null
+ val source = PlanarYUVLuminanceSource(luma, rowStride, height, 0, 0, width, height, false)
+ return read(source) ?: read(source.invert())
+ }
+
+ private fun read(source: LuminanceSource): String? =
+ try {
+ reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text
+ } catch (_: ReaderException) {
+ null
+ } finally {
+ reader.reset()
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/sound/SoundPlayer.kt b/android/app/src/main/kotlin/com/coucou/android/sound/SoundPlayer.kt
new file mode 100644
index 00000000..bab51d1a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/sound/SoundPlayer.kt
@@ -0,0 +1,66 @@
+package com.coucou.android.sound
+
+import android.content.Context
+import android.media.AudioAttributes
+import android.media.SoundPool
+import com.coucou.android.R
+import com.coucou.android.mochi.SoundSink
+
+/**
+ * Plays Mochi's sounds (the .wav files in res/raw, (c) Louis Raillé, used with permission) through a
+ * SoundPool. Short clips, no streaming; a sound that is not found is silently ignored.
+ */
+class SoundPlayer(private val context: Context) : SoundSink {
+ var enabled = true
+ var volume = SoundVolume.DEFAULT
+ set(v) { field = SoundVolume.clamp(v) }
+
+ private val pool: SoundPool = SoundPool.Builder()
+ .setMaxStreams(4)
+ .setAudioAttributes(
+ AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
+ .build(),
+ )
+ .build()
+ private val ids = HashMap<String, Int>()
+ private val ready = HashSet<Int>()
+
+ init {
+ pool.setOnLoadCompleteListener { _, id, status -> if (status == 0) ready.add(id) }
+ }
+
+ private fun load(name: String): Int? = ids.getOrPut(name) {
+ val res = RAW[name] ?: return null
+ pool.load(context, res, 1)
+ }
+
+ override fun play(name: String) {
+ if (!enabled || volume <= 0f) return
+ val id = load(name) ?: return
+ if (id in ready) pool.play(id, volume, volume, 1, 0, 1f)
+ }
+
+ fun release() = pool.release()
+
+ private companion object {
+ /** Every bundled sound, by file name (an explicit table: no resource reflection). */
+ val RAW: Map<String, Int> = mapOf(
+ "annoyed" to R.raw.annoyed,
+ "approval" to R.raw.approval,
+ "dizzy" to R.raw.dizzy,
+ "error" to R.raw.error,
+ "finish" to R.raw.finish,
+ "greet" to R.raw.greet,
+ "love" to R.raw.love,
+ "question" to R.raw.question,
+ "rate" to R.raw.rate,
+ "search" to R.raw.search,
+ "slap" to R.raw.slap,
+ "sleep" to R.raw.sleep,
+ "think" to R.raw.think,
+ "work" to R.raw.work,
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/sound/SoundVolume.kt b/android/app/src/main/kotlin/com/coucou/android/sound/SoundVolume.kt
new file mode 100644
index 00000000..14b02a5a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/sound/SoundVolume.kt
@@ -0,0 +1,8 @@
+package com.coucou.android.sound
+
+/** Volume rules from docs/SPEC.md: default 0.12 and the slider never goes above 0.2. */
+object SoundVolume {
+ const val DEFAULT = 0.12f
+ const val MAX = 0.2f
+ fun clamp(v: Float): Float = v.coerceIn(0f, MAX)
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/BottomBar.kt b/android/app/src/main/kotlin/com/coucou/android/ui/BottomBar.kt
new file mode 100644
index 00000000..501a88a3
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/BottomBar.kt
@@ -0,0 +1,79 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.IntrinsicSize
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.core.BarFit
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.Tab
+import com.coucou.android.core.TypeScale
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiConst
+
+private fun Tab.icon() = when (this) {
+ Tab.HOME -> IconKind.HOME
+ Tab.CHAT -> IconKind.CHAT
+ Tab.SETTINGS -> IconKind.SLIDERS
+}
+
+private fun Tab.label() = when (this) {
+ Tab.HOME -> R.string.tab_home
+ Tab.CHAT -> R.string.tab_chat
+ Tab.SETTINGS -> R.string.tab_settings
+}
+
+/**
+ * The floating bar: a black pill with Home, Chat (only when offered) and Settings. Labels are always
+ * shown; the open tab has a lighter pill behind it. [alert] puts the approval colour's dot on Home when
+ * a request is waiting. Every item is at least 48 dp high and announces itself as a tab.
+ */
+@Composable
+fun BottomBar(tabs: List<Tab>, selected: Tab?, onSelect: (Tab) -> Unit, alert: Boolean, modifier: Modifier = Modifier) {
+ val t = tokens()
+ Row(
+ // At least 64 dp, taller when the font is large, so labels are never cut.
+ modifier.fillMaxWidth().padding(horizontal = 24.dp).height(IntrinsicSize.Min).heightIn(min = 64.dp)
+ .clip(CircleShape).background(t.panel.c()).border(1.dp, t.line.c(), CircleShape).padding(6.dp),
+ horizontalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ for (tab in tabs) {
+ val on = tab == selected
+ Box(
+ Modifier.weight(1f).fillMaxHeight().clip(CircleShape).background(if (on) t.panel2.c() else Color.Transparent)
+ .selectable(selected = on, role = Role.Tab, onClick = { onSelect(tab) }),
+ contentAlignment = Alignment.Center,
+ ) {
+ Column(Modifier.padding(horizontal = BarFit.ITEM_SIDE_PADDING_DP.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ CoucouIcon(tab.icon(), tint = if (on) t.text.c() else t.textDim.c(), size = 22.dp)
+ Text(stringResource(tab.label()), style = TypeScale.LABEL.style(if (on) t.text.c() else t.textDim.c()), maxLines = 1, softWrap = false)
+ }
+ if (alert && tab == Tab.HOME) {
+ val amber = MochiConst.STATES[BotState.APPROVAL]?.color?.let(::rgbColor) ?: Color(0xFFF5A524)
+ Box(Modifier.align(Alignment.TopCenter).padding(start = 22.dp, top = 4.dp).size(9.dp).clip(CircleShape).background(amber).border(2.dp, t.panel.c(), CircleShape))
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/ChatScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/ChatScreen.kt
new file mode 100644
index 00000000..26f0522b
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/ChatScreen.kt
@@ -0,0 +1,389 @@
+package com.coucou.android.ui
+
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.material3.OutlinedTextFieldDefaults
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.SpanStyle
+import androidx.compose.ui.text.buildAnnotatedString
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.text.withStyle
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.ChatMessage
+import com.coucou.android.core.ChatReasons
+import com.coucou.android.core.ChatTab
+import com.coucou.android.core.ChatTabState
+import com.coucou.android.core.Screen
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+import com.coucou.android.core.ChatRole
+import com.coucou.android.core.ChatSession
+import com.coucou.android.core.ChatStatus
+import com.coucou.android.core.MarkdownLite
+import com.coucou.android.core.MdBlock
+import com.coucou.android.core.MdSpan
+import com.coucou.android.link.Protocol
+
+/** The words for a code the computer (or this app) gives when an answer did not complete. */
+@Composable
+private fun reasonText(code: String?): String = stringResource(
+ when (ChatReasons.key(code)) {
+ "off" -> R.string.chat_err_off
+ "not_allowed" -> R.string.chat_err_not_allowed
+ "busy" -> R.string.chat_err_busy
+ "rate" -> R.string.chat_err_rate
+ "too_long" -> R.string.chat_err_too_long
+ "empty" -> R.string.chat_err_empty
+ "no_key" -> R.string.chat_err_no_key
+ "unreachable" -> R.string.chat_err_unreachable
+ "auth" -> R.string.chat_err_auth
+ "provider" -> R.string.chat_err_provider
+ "canceled" -> R.string.chat_err_canceled
+ "connection" -> R.string.chat_err_connection
+ "interrupted" -> R.string.chat_err_interrupted
+ else -> R.string.chat_err_internal
+ },
+)
+
+internal fun chatStateTitle(state: ChatTabState): Int = when (state) {
+ ChatTabState.NOT_PAIRED -> R.string.chat_off_not_paired_title
+ ChatTabState.NOT_CONNECTED -> R.string.chat_off_offline_title
+ ChatTabState.CHAT_OFF -> R.string.chat_off_title
+ ChatTabState.NO_MODELS -> R.string.chat_nomodel_title
+ ChatTabState.READY -> R.string.chat_title
+}
+
+internal fun chatStateBody(state: ChatTabState): Int = when (state) {
+ ChatTabState.NOT_PAIRED -> R.string.chat_off_not_paired_body
+ ChatTabState.NOT_CONNECTED -> R.string.chat_off_offline_body
+ ChatTabState.CHAT_OFF, ChatTabState.NO_MODELS -> R.string.chat_off_hint
+ ChatTabState.READY -> R.string.chat_title
+}
+
+/** The Chat tab with nothing to chat with: a sleeping Mochi, what is wrong in plain words, and the one button that helps (if any). */
+@Composable
+private fun ChatEmpty(state: ChatTabState, onHome: () -> Unit, onSettings: () -> Unit) {
+ val t = tokens()
+ val engine = remember { MochiEngine({ android.os.SystemClock.elapsedRealtimeNanos() / 1e6 }).apply { setState(BotState.SLEEPING, force = true) } }
+ Column(Modifier.fillMaxSize().padding(horizontal = Gutter)) {
+ ScreenTitle(stringResource(R.string.chat_title), null)
+ Column(
+ Modifier.weight(1f).fillMaxWidth().padding(horizontal = 8.dp),
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
+ ) {
+ MochiView(engine, Modifier.size(120.dp))
+ Text(
+ stringResource(chatStateTitle(state)), Modifier.padding(top = 16.dp),
+ style = TypeScale.TITLE.style(t.text.c()).copy(textAlign = TextAlign.Center),
+ )
+ Text(
+ stringResource(chatStateBody(state)), Modifier.padding(top = 8.dp, bottom = 20.dp),
+ style = TypeScale.BODY.style(t.textDim.c()).copy(textAlign = TextAlign.Center),
+ )
+ when (ChatTab.action(state)) {
+ Screen.HOME -> PillButton(stringResource(R.string.chat_go_pair), onHome, Modifier.fillMaxWidth(), PillKind.PRIMARY)
+ Screen.SETTINGS -> PillButton(stringResource(R.string.chat_go_settings), onSettings, Modifier.fillMaxWidth(), PillKind.PRIMARY)
+ else -> {}
+ }
+ }
+ }
+}
+
+/**
+ * Chat with the computer's AI providers, like the PC's chat panel: your messages on the right, the
+ * answers as plain light Markdown, three dots while waiting, the model above the box. The computer's
+ * API key is used on the computer; this screen only ever has text.
+ */
+@Composable
+fun ChatScreen(model: AppModel, onHome: () -> Unit, onSettings: () -> Unit) {
+ var text by rememberSaveable { mutableStateOf("") }
+ var refusal by remember { mutableStateOf<ChatSession.Refusal?>(null) }
+ var confirmClear by remember { mutableStateOf(false) }
+ val listState = rememberLazyListState()
+ val messages = model.chatMessages
+
+ LaunchedEffect(Unit) { model.chatRefreshModels() }
+ // Follow the answer as it grows.
+ val lastLength = messages.lastOrNull()?.text?.length ?: 0
+ LaunchedEffect(messages.size, lastLength) {
+ if (messages.isNotEmpty()) listState.scrollToItem(messages.size - 1)
+ }
+
+ val tabState = model.chatTabState
+ // Nothing to chat with and nothing to read: say why, calmly, with the one thing to do about it.
+ if (tabState != ChatTabState.READY && messages.isEmpty()) {
+ ChatEmpty(tabState, onHome, onSettings)
+ return
+ }
+
+ Column(Modifier.fillMaxSize().padding(horizontal = Gutter)) {
+ ScreenTitle(
+ stringResource(R.string.chat_title), null,
+ trailing = {
+ if (messages.isNotEmpty()) {
+ Text(
+ stringResource(R.string.chat_clear),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button) { confirmClear = true }.padding(horizontal = 12.dp, vertical = 14.dp),
+ style = TypeScale.LABEL.style(tokens().textDim.c()), maxLines = 1,
+ )
+ }
+ },
+ )
+ Text(
+ stringResource(R.string.chat_note), Modifier.padding(horizontal = 4.dp, vertical = 4.dp),
+ style = TypeScale.SECONDARY.style(tokens().textDim.c()),
+ )
+ if (!model.chatAvailable) {
+ // The conversation stays readable; the reason sits above it.
+ Panel(Modifier.padding(vertical = 4.dp)) {
+ Column(Modifier.padding(Gutter), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(stringResource(chatStateTitle(tabState)), style = TypeScale.HEADLINE.style(tokens().text.c()))
+ Text(stringResource(chatStateBody(tabState)), style = TypeScale.SECONDARY.style(tokens().textDim.c()))
+ }
+ }
+ }
+ Box(Modifier.weight(1f).fillMaxWidth()) {
+ if (messages.isEmpty()) {
+ Text(
+ stringResource(R.string.chat_empty), Modifier.align(Alignment.Center).padding(Gutter),
+ style = TypeScale.BODY.style(tokens().textDim.c()).copy(textAlign = TextAlign.Center),
+ )
+ } else {
+ LazyColumn(state = listState, modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(Gap)) {
+ items(messages, key = { it.id }) { m -> Bubble(m) }
+ }
+ }
+ }
+ Composer(
+ model, text, refusal,
+ onText = { text = it; refusal = null },
+ onSend = {
+ val r = model.chatSend(text)
+ if (r == null) { text = ""; refusal = null } else refusal = r
+ },
+ )
+ }
+
+ if (confirmClear) {
+ AlertDialog(
+ onDismissRequest = { confirmClear = false },
+ title = { Text(stringResource(R.string.chat_clear_title)) },
+ text = { Text(stringResource(R.string.chat_clear_body)) },
+ confirmButton = {
+ TextButton(onClick = { confirmClear = false; model.chatClear() }) {
+ Text(stringResource(R.string.chat_clear), color = MaterialTheme.colorScheme.error)
+ }
+ },
+ dismissButton = { TextButton(onClick = { confirmClear = false }) { Text(stringResource(R.string.action_cancel)) } },
+ )
+ }
+}
+
+@Composable
+private fun Bubble(m: ChatMessage) {
+ if (m.role == ChatRole.USER) {
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
+ SelectionContainer {
+ Text(
+ m.text,
+ Modifier.widthIn(max = 300.dp)
+ .clip(RoundedCornerShape(18.dp, 18.dp, 6.dp, 18.dp))
+ .background(tokens().panel2.c())
+ .padding(horizontal = 14.dp, vertical = 10.dp),
+ style = TypeScale.BODY.style(tokens().text.c()),
+ )
+ }
+ }
+ return
+ }
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (m.text.isEmpty() && m.status == ChatStatus.STREAMING) TypingDots()
+ else if (m.text.isNotEmpty()) SelectionContainer { MarkdownText(m.text) }
+ if (m.status == ChatStatus.FAILED) {
+ Text(reasonText(m.reason), style = TypeScale.SECONDARY.style(tokens().danger.c()))
+ }
+ }
+}
+
+/** The three dots of the PC's chat; they only move while this is on screen. */
+@Composable
+private fun TypingDots() {
+ val transition = rememberInfiniteTransition(label = "typing")
+ val phase by transition.animateFloat(
+ initialValue = 0f, targetValue = 3f,
+ animationSpec = infiniteRepeatable(tween(1200, easing = LinearEasing), RepeatMode.Restart), label = "dots",
+ )
+ Row(Modifier.padding(vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ repeat(3) { i ->
+ val on = phase.toInt() == i
+ Box(
+ Modifier.size(8.dp).clip(CircleShape)
+ .background(tokens().textDim.c().copy(alpha = if (on) 1f else 0.35f)),
+ )
+ }
+ }
+}
+
+@Composable
+private fun MarkdownText(text: String) {
+ val blocks = remember(text) { MarkdownLite.parse(text) }
+ val t = tokens()
+ val code = t.panel2.c()
+ val body = TypeScale.BODY.style(t.text.c())
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (b in blocks) {
+ when (b) {
+ is MdBlock.Para -> Text(styled(b.spans, code), style = body)
+ is MdBlock.Bullet -> Row {
+ Text("• ", style = body)
+ Text(styled(b.spans, code), Modifier.weight(1f), style = body)
+ }
+ is MdBlock.Code -> Text(
+ b.text,
+ Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(code)
+ .border(1.dp, t.line.c(), RoundedCornerShape(12.dp)).padding(12.dp),
+ style = TypeScale.MONO.style(t.text.c()).copy(fontFamily = FontFamily.Monospace),
+ )
+ }
+ }
+ }
+}
+
+private fun styled(spans: List<MdSpan>, codeBackground: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {
+ for (s in spans) {
+ val style = SpanStyle(
+ fontWeight = if (s.bold) FontWeight.Bold else null,
+ fontFamily = if (s.code) FontFamily.Monospace else null,
+ background = if (s.code) codeBackground else androidx.compose.ui.graphics.Color.Unspecified,
+ )
+ withStyle(style) { append(s.text) }
+ }
+}
+
+@Composable
+private fun Composer(model: AppModel, text: String, refusal: ChatSession.Refusal?, onText: (String) -> Unit, onSend: () -> Unit) {
+ val limit = Protocol.CHAT_MAX_TEXT
+ val length = text.trim().length
+ val t = tokens()
+ Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ ModelChip(model)
+ Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedTextField(
+ value = text, onValueChange = { onText(it.take(limit + 200)) }, modifier = Modifier.weight(1f),
+ placeholder = { Text(stringResource(R.string.chat_placeholder), color = t.textFaint.c()) },
+ maxLines = 4, shape = RoundedCornerShape(26.dp), enabled = model.chatAvailable,
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedContainerColor = t.panel.c(), unfocusedContainerColor = t.panel.c(), disabledContainerColor = t.panel.c(),
+ focusedBorderColor = t.textDim.c(), unfocusedBorderColor = t.line.c(), disabledBorderColor = t.line.c(),
+ focusedTextColor = t.text.c(), unfocusedTextColor = t.text.c(), cursorColor = t.text.c(),
+ ),
+ )
+ if (model.chatBusy) {
+ PillButton(stringResource(R.string.chat_stop), { model.chatCancel() }, Modifier.height(56.dp))
+ } else {
+ val canSend = model.chatAvailable && length in 1..limit
+ val send = stringResource(R.string.chat_send)
+ Box(
+ Modifier.alpha(if (canSend) 1f else 0.4f).size(56.dp).clip(CircleShape).background(t.primaryButton.c())
+ .clickable(enabled = model.chatAvailable && length in 1..limit, role = Role.Button, onClick = onSend)
+ .semantics { contentDescription = send },
+ contentAlignment = Alignment.Center,
+ ) { CoucouIcon(IconKind.SEND, tint = t.onPrimaryButton.c(), size = 22.dp) }
+ }
+ }
+ val note = when {
+ refusal == ChatSession.Refusal.TOO_LONG || length > limit -> stringResource(R.string.chat_ref_too_long)
+ refusal == ChatSession.Refusal.NO_MODEL -> stringResource(R.string.chat_ref_no_model)
+ refusal == ChatSession.Refusal.BUSY -> stringResource(R.string.chat_ref_busy)
+ refusal == ChatSession.Refusal.OFFLINE -> stringResource(R.string.chat_ref_offline)
+ else -> null
+ }
+ if (note != null) Text(note, style = TypeScale.SECONDARY.style(t.danger.c()))
+ else if (length > limit * 9 / 10) {
+ Text(stringResource(R.string.chat_count, length, limit), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ }
+}
+
+/** The model above the box, like the PC's: tap to pick another of the ones the computer allows. */
+@Composable
+private fun ModelChip(model: AppModel) {
+ var open by remember { mutableStateOf(false) }
+ val models = model.chatModels
+ val current = models.firstOrNull { it.id == model.chatModel }
+ val t = tokens()
+ Box {
+ Row(
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clip(CircleShape).background(t.panel2.c())
+ .clickable(enabled = models.size > 1, role = Role.Button) { open = true }.padding(horizontal = 14.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(stringResource(R.string.chat_model, current?.label ?: "—"), style = TypeScale.LABEL.style(t.text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (models.size > 1) CoucouIcon(IconKind.CHEVRON, tint = t.textDim.c(), size = 16.dp, modifier = Modifier.rotate(90f))
+ }
+ DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
+ for (m in models) {
+ DropdownMenuItem(
+ text = { Text(m.label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ onClick = { model.chatSelect(m.id); open = false },
+ )
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/ConnectionHelp.kt b/android/app/src/main/kotlin/com/coucou/android/ui/ConnectionHelp.kt
new file mode 100644
index 00000000..bb606d93
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/ConnectionHelp.kt
@@ -0,0 +1,85 @@
+package com.coucou.android.ui
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.provider.Settings
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.produceState
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.BatteryHint
+import com.coucou.android.link.LinkHealthText
+import com.coucou.android.link.LinkState
+import kotlinx.coroutines.delay
+
+/**
+ * Shown on Home while the link is down after having worked: what happened and how long ago ("Connection lost 2 min ago,
+ * reconnecting"), why in one sentence, and the way to "Can't connect?". The time is refreshed while this is on screen, never in the background.
+ */
+@Composable
+fun LinkHealthPanel(model: AppModel, onHelp: () -> Unit) {
+ val now by produceState(System.currentTimeMillis()) {
+ while (true) {
+ delay(15_000)
+ value = System.currentTimeMillis()
+ }
+ }
+ val lines = LinkHealthText.lines(model.linkState == LinkState.CONNECTED, model.health, now) ?: return
+ val t = tokens()
+ Panel {
+ Column(Modifier.padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(lines.first, style = TypeScale.BODY.style(t.text.c()))
+ if (lines.second.isNotEmpty()) Text(lines.second, style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ RowDivider()
+ ListRow(stringResource(R.string.diag_title), onClick = onHelp, trailing = { CoucouIcon(IconKind.CHEVRON, tint = t.textDim.c(), size = 20.dp) })
+ }
+}
+
+/**
+ * A calm suggestion, shown only when the link ended on its own after the screen had been off and Android still restricts the app. It
+ * opens Android's own screen (the app cannot change the setting by itself) and says where it is on Samsung phones.
+ */
+@Composable
+fun BatteryCard(model: AppModel) {
+ val context = LocalContext.current
+ val t = tokens()
+ Panel {
+ Column(Modifier.padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(stringResource(R.string.battery_title), style = TypeScale.HEADLINE.style(t.text.c()))
+ Text(stringResource(R.string.battery_body), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ model.batterySteps.forEachIndexed { i, step ->
+ Text("${i + 1}. $step", style = TypeScale.SECONDARY.style(t.text.c()))
+ }
+ Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ PillButton(stringResource(R.string.battery_not_now), { model.snoozeBatteryHint() }, Modifier.weight(1f))
+ PillButton(stringResource(R.string.battery_open), { openBatterySettings(context) }, Modifier.weight(1f), PillKind.PRIMARY)
+ }
+ }
+ }
+}
+
+/** Samsung's own steps start in the app's page; elsewhere the list of battery-optimised apps is the direct way. */
+private fun openBatterySettings(context: Context) {
+ val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
+ val list = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
+ val order = if (BatteryHint.isSamsung(android.os.Build.MANUFACTURER)) listOf(details, list) else listOf(list, details)
+ for (intent in order) {
+ if (runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess) return
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DesignControls.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DesignControls.kt
new file mode 100644
index 00000000..bc4a8f11
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DesignControls.kt
@@ -0,0 +1,111 @@
+package com.coucou.android.ui
+
+import androidx.compose.animation.core.snap
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.gestures.detectHorizontalDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.sizeIn
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.selection.toggleable
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.ProgressBarRangeInfo
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.progressBarRangeInfo
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.setProgress
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import com.coucou.android.core.Spacing
+import kotlin.math.roundToInt
+
+private val TRACK_W = 52.dp
+private val TRACK_H = 30.dp
+private val KNOB = 22.dp
+
+/**
+ * The on/off switch: a 52 x 30 pill with a white knob that springs across, green when on. The hit area
+ * is 48 dp high. It is a real toggle for TalkBack (role Switch, with its state), unlike a plain box.
+ */
+@Composable
+fun CoucouSwitch(checked: Boolean, onChange: (Boolean) -> Unit, modifier: Modifier = Modifier, label: String? = null, enabled: Boolean = true) {
+ val t = tokens()
+ val reduced = reducedMotion()
+ val knobX by animateDpAsState(if (checked) 22.dp else 0.dp, if (reduced) snap() else spring(dampingRatio = 0.72f, stiffness = 400f), label = "knob")
+ Box(
+ modifier.alpha(if (enabled) 1f else 0.4f).sizeIn(minWidth = TRACK_W, minHeight = Spacing.MIN_TOUCH.dp)
+ .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onChange)
+ .semantics { if (label != null) contentDescription = label },
+ contentAlignment = Alignment.Center,
+ ) {
+ Box(
+ Modifier.size(TRACK_W, TRACK_H).clip(CircleShape)
+ .background(if (checked) t.online.c() else t.panel2.c())
+ .border(1.dp, if (checked) Color.Transparent else t.line.c(), CircleShape),
+ ) {
+ Box(Modifier.offset(x = 3.dp + knobX, y = 3.dp).size(KNOB).clip(CircleShape).background(Color.White))
+ }
+ }
+}
+
+/**
+ * The slider: a 4 dp rail, the part before the knob in the text colour, and a 22 dp white round knob.
+ * Tap or drag; TalkBack can step it through its progress action. 48 dp high so it is easy to hit.
+ */
+@Composable
+fun CoucouSlider(
+ value: Float, onChange: (Float) -> Unit, modifier: Modifier = Modifier,
+ valueRange: ClosedFloatingPointRange<Float> = 0f..1f, enabled: Boolean = true, label: String = "",
+) {
+ val t = tokens()
+ val latest by rememberUpdatedState(onChange)
+ val density = LocalDensity.current
+ BoxWithConstraints(modifier.alpha(if (enabled) 1f else 0.4f).fillMaxWidth().height(Spacing.MIN_TOUCH.dp)) {
+ val widthPx = constraints.maxWidth.toFloat()
+ val knobPx = with(density) { KNOB.toPx() }
+ val usable = (widthPx - knobPx).coerceAtLeast(1f)
+ val span = valueRange.endInclusive - valueRange.start
+ val fraction = if (span <= 0f) 0f else ((value - valueRange.start) / span).coerceIn(0f, 1f)
+ fun fromX(x: Float): Float = valueRange.start + ((x - knobPx / 2f) / usable).coerceIn(0f, 1f) * span
+ Box(
+ Modifier.fillMaxSize()
+ .pointerInput(enabled, valueRange) { if (enabled) detectTapGestures { latest(fromX(it.x)) } }
+ .pointerInput(enabled, valueRange) { if (enabled) detectHorizontalDragGestures { change, _ -> latest(fromX(change.position.x)) } }
+ .semantics {
+ contentDescription = label
+ progressBarRangeInfo = ProgressBarRangeInfo(value.coerceIn(valueRange), valueRange)
+ setProgress { target -> latest(target.coerceIn(valueRange)); true }
+ },
+ ) {
+ Box(Modifier.align(Alignment.CenterStart).fillMaxWidth().height(4.dp).clip(CircleShape).background(t.panel2.c()))
+ Box(
+ Modifier.align(Alignment.CenterStart).height(4.dp).clip(CircleShape).background(t.text.c())
+ .width(with(density) { (knobPx / 2f + fraction * usable).toDp() }),
+ )
+ Box(
+ Modifier.align(Alignment.CenterStart).offset { IntOffset((fraction * usable).roundToInt(), 0) }
+ .size(KNOB).clip(CircleShape).background(Color.White).border(1.dp, Color.Black.copy(alpha = 0.25f), CircleShape),
+ )
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DesignIcons.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DesignIcons.kt
new file mode 100644
index 00000000..4588da8a
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DesignIcons.kt
@@ -0,0 +1,51 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IconShape
+import com.coucou.android.core.IconSpec
+
+/** Draws an icon from core/IconSpec.kt: stroked, round ends and joins, scaled from the 24 grid to [size]. No icon library. */
+@Composable
+fun CoucouIcon(kind: IconKind, modifier: Modifier = Modifier, tint: Color = tokens().text.c(), size: Dp = 24.dp) {
+ Canvas(modifier.size(size)) { drawIcon(kind, tint) }
+}
+
+private fun DrawScope.drawIcon(kind: IconKind, tint: Color) {
+ val k = (size.minDimension / IconSpec.GRID.toFloat())
+ val stroke = Stroke(width = IconSpec.STROKE.toFloat() * k, cap = StrokeCap.Round, join = StrokeJoin.Round)
+ fun p(v: Double) = v.toFloat() * k
+ for (s in IconSpec.shapes(kind)) when (s) {
+ is IconShape.Poly -> {
+ val path = Path()
+ for (i in 0 until s.points.size / 2) {
+ val x = p(s.points[2 * i])
+ val y = p(s.points[2 * i + 1])
+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
+ }
+ drawPath(path, tint, style = stroke)
+ }
+ is IconShape.Circle -> drawCircle(tint, radius = p(s.r), center = Offset(p(s.cx), p(s.cy)), style = stroke)
+ is IconShape.RoundRect -> drawRoundRect(
+ tint, topLeft = Offset(p(s.x), p(s.y)), size = Size(p(s.w), p(s.h)), cornerRadius = CornerRadius(p(s.r)), style = stroke,
+ )
+ is IconShape.Arc -> drawArc(
+ tint, startAngle = s.start.toFloat(), sweepAngle = s.sweep.toFloat(), useCenter = false,
+ topLeft = Offset(p(s.cx - s.r), p(s.cy - s.r)), size = Size(p(2 * s.r), p(2 * s.r)), style = stroke,
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DesignSystem.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DesignSystem.kt
new file mode 100644
index 00000000..a672fa7f
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DesignSystem.kt
@@ -0,0 +1,193 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.ReadOnlyComposable
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.MotionSpec
+import com.coucou.android.core.Radii
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+import com.coucou.android.core.TypeStep
+
+// The app's building blocks: panels, pill buttons, the hero panel, the tokens of the (dark) theme.
+
+/** The tokens of the current theme; CoucouTheme provides them. */
+val LocalTokens = staticCompositionLocalOf { Tokens.DARK }
+
+@Composable
+@ReadOnlyComposable
+fun tokens(): Tokens = LocalTokens.current
+
+internal fun Long.c() = Color(this)
+
+/** True when the user turned animations off (Android's "Remove animations"): springs and slides become plain fades or jumps. */
+@Composable
+fun reducedMotion(): Boolean {
+ val resolver = androidx.compose.ui.platform.LocalContext.current.contentResolver
+ return MotionSpec.isReduced(android.provider.Settings.Global.getFloat(resolver, android.provider.Settings.Global.ANIMATOR_DURATION_SCALE, 1f))
+}
+
+/** A step of the type scale as a Compose style. */
+fun TypeStep.style(color: Color = Color.Unspecified) =
+ TextStyle(fontSize = sizeSp.sp, lineHeight = lineSp.sp, fontWeight = FontWeight(weight), color = color)
+
+/**
+ * The island panel: `panel` colour, a thin border, radius 20. With [wash], a soft glow of that colour
+ * rises from the bottom edge (the PC's `.wash`). No shadow: depth comes from the border and the glow.
+ */
+@Composable
+fun Panel(modifier: Modifier = Modifier, wash: Color? = null, content: @Composable ColumnScope.() -> Unit) {
+ val t = tokens()
+ val shape = RoundedCornerShape(Radii.PANEL.dp)
+ Column(
+ modifier.fillMaxWidth().clip(shape).background(t.panel.c()).border(1.dp, t.line.c(), shape)
+ .then(if (wash != null) Modifier.drawBehind { drawWash(wash, t.washAlpha.toFloat()) } else Modifier),
+ content = content,
+ )
+}
+
+/** The glow: [color] at [alpha] under the bottom edge, gone by about 70% of the way up. */
+internal fun DrawScope.drawWash(color: Color, alpha: Float) {
+ drawRect(
+ Brush.radialGradient(
+ 0f to color.copy(alpha = alpha), 1f to Color.Transparent,
+ center = Offset(size.width / 2f, size.height * 1.3f), radius = size.width * 0.85f,
+ ),
+ )
+}
+
+/** The hero panel at the top of Home: black, hanging from the screen's top edge. */
+@Composable
+fun HeroPanel(modifier: Modifier = Modifier, wash: Color? = null, content: @Composable ColumnScope.() -> Unit) {
+ val shape = RoundedCornerShape(bottomStart = Radii.HERO_BOTTOM.dp, bottomEnd = Radii.HERO_BOTTOM.dp)
+ Column(
+ modifier.fillMaxWidth().clip(shape).background(IslandSurface.HERO.c())
+ .border(1.dp, Color.White.copy(alpha = 0.06f), shape)
+ .then(if (wash != null) Modifier.drawBehind { drawWash(wash, 0.5f) } else Modifier),
+ content = content,
+ )
+}
+
+enum class PillKind { PRIMARY, SECONDARY, DANGER }
+
+/**
+ * The PC's buttons: one white (dark theme) pill for the main action, grey pills for the rest, and a
+ * grey pill with a red label for what is destructive. 48 dp high, whatever the font size.
+ */
+@Composable
+fun PillButton(
+ text: String, onClick: () -> Unit, modifier: Modifier = Modifier, kind: PillKind = PillKind.SECONDARY,
+ enabled: Boolean = true, onDark: Boolean = false, icon: (@Composable () -> Unit)? = null,
+) {
+ val t = tokens()
+ // [onDark]: on the always-black hero panel and island, whatever the theme.
+ val bg = when {
+ onDark -> if (kind == PillKind.PRIMARY) IslandSurface.TEXT else IslandSurface.BUTTON
+ kind == PillKind.PRIMARY -> t.primaryButton
+ else -> t.secondaryButton
+ }
+ val fg = when {
+ kind == PillKind.DANGER -> t.danger
+ onDark -> if (kind == PillKind.PRIMARY) IslandSurface.ON_PRIMARY else IslandSurface.TEXT
+ kind == PillKind.PRIMARY -> t.onPrimaryButton
+ else -> t.text
+ }
+ Row(
+ modifier.alpha(if (enabled) 1f else 0.4f).heightIn(min = Spacing.MIN_TOUCH.dp).clip(CircleShape).background(bg.c())
+ .clickable(enabled = enabled, role = Role.Button, onClick = onClick).padding(horizontal = 22.dp),
+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ icon?.invoke()
+ Text(text, style = TypeScale.BODY.style(fg.c()).copy(fontWeight = FontWeight.SemiBold), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** A small read-only label: the project folder, a model name. Not a button. */
+@Composable
+fun Chip(text: String, modifier: Modifier = Modifier, tint: Color? = null) {
+ val t = tokens()
+ Row(
+ modifier.heightIn(min = 28.dp).clip(CircleShape).background(tint?.copy(alpha = 0.16f) ?: t.panel2.c()).padding(horizontal = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(text, style = TypeScale.LABEL.style(tint ?: t.text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** The small heading above a panel, in sentence case. */
+@Composable
+fun SectionHeading(text: String, modifier: Modifier = Modifier) {
+ Text(
+ text, modifier.padding(start = 4.dp, top = 8.dp), style = TypeScale.LABEL.style(tokens().textDim.c()),
+ maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+}
+
+/** A row inside a panel: a title, an optional hint under it, something at the end. Tappable when [onClick] is given. */
+@Composable
+fun ListRow(
+ title: String, modifier: Modifier = Modifier, hint: String? = null, onClick: (() -> Unit)? = null,
+ trailing: (@Composable RowScope.() -> Unit)? = null,
+) {
+ val t = tokens()
+ Row(
+ modifier.fillMaxWidth().heightIn(min = 56.dp)
+ .then(if (onClick != null) Modifier.clickable(role = Role.Button, onClick = onClick) else Modifier)
+ .padding(horizontal = Spacing.INSIDE.dp, vertical = Spacing.SCALE[2].dp),
+ horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = TypeScale.BODY.style(t.text.c()).copy(fontWeight = FontWeight.SemiBold))
+ if (hint != null) Text(hint, style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ trailing?.invoke(this)
+ }
+}
+
+/** The thin line between two rows of one panel. */
+@Composable
+fun RowDivider() {
+ Box(Modifier.fillMaxWidth().height(1.dp).background(tokens().line.c()))
+}
+
+/** The coloured dot of an agent or a connection. */
+@Composable
+fun StateDot(color: Color, modifier: Modifier = Modifier) {
+ Box(modifier.size(8.dp).clip(CircleShape).background(color))
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DiagnosticsScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DiagnosticsScreen.kt
new file mode 100644
index 00000000..87be85ba
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DiagnosticsScreen.kt
@@ -0,0 +1,96 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.DiagResult
+import com.coucou.android.link.DiagStep
+
+/**
+ * Settings > Computer > "Can't connect?": runs the checks one after another (Wi-Fi, the saved address, discovery, the pinned
+ * certificate, the pairing code and version, the relay) and says which one fails and what to try. The report it copies hides the
+ * pairing code, the certificate fingerprint, the computer's name and the full address.
+ */
+@Composable
+fun DiagnosticsScreen(model: AppModel, onBack: () -> Unit) {
+ val t = tokens()
+ val clipboard = LocalClipboardManager.current
+ var copied by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) { if (model.diagResults.isEmpty() && !model.diagRunning) model.runDiagnostics() }
+ LazyColumn(
+ Modifier.padding(horizontal = Gutter), contentPadding = PaddingValues(bottom = BarClearance),
+ verticalArrangement = Arrangement.spacedBy(Gap),
+ ) {
+ item { ScreenTitle(stringResource(R.string.diag_title), onBack) }
+ item { Text(stringResource(R.string.diag_intro), Modifier.padding(horizontal = 4.dp), style = TypeScale.SECONDARY.style(t.textDim.c())) }
+ item {
+ Panel {
+ model.diagResults.forEachIndexed { i, (step, result) ->
+ if (i > 0) RowDivider()
+ DiagRow(step, result)
+ }
+ if (model.diagRunning) Text(stringResource(R.string.diag_running), Modifier.padding(Spacing.INSIDE.dp), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ }
+ item {
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ PillButton(stringResource(R.string.diag_run), { copied = false; model.runDiagnostics() }, Modifier.weight(1f), enabled = !model.diagRunning)
+ PillButton(
+ stringResource(R.string.diag_copy),
+ { clipboard.setText(AnnotatedString(model.diagnosticsReport())); copied = true },
+ Modifier.weight(1f), PillKind.PRIMARY, enabled = model.diagResults.isNotEmpty() && !model.diagRunning,
+ )
+ }
+ }
+ if (copied) item { Text(stringResource(R.string.diag_copied), Modifier.padding(horizontal = 4.dp), style = TypeScale.SECONDARY.style(t.textDim.c())) }
+ }
+}
+
+/** One check: a dot, its name with a word (so colour is not the only signal), what was found, and what to try. */
+@Composable
+private fun DiagRow(step: DiagStep, result: DiagResult) {
+ val t = tokens()
+ val word: String
+ val dot: Color
+ val detail: String
+ var hint = ""
+ when (result) {
+ is DiagResult.Ok -> { word = stringResource(R.string.diag_ok); dot = StatusColors.online; detail = result.detail }
+ is DiagResult.Problem -> { word = stringResource(R.string.diag_problem); dot = Color(t.danger); detail = result.problem; hint = result.hint }
+ is DiagResult.Skipped -> { word = stringResource(R.string.diag_skipped); dot = Color(t.textFaint); detail = result.why }
+ }
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = Spacing.INSIDE.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.Top,
+ ) {
+ StateDot(dot, Modifier.padding(top = 6.dp))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text("${step.title} · $word", style = TypeScale.BODY.style(t.text.c()))
+ Text(detail, style = TypeScale.SECONDARY.style(t.textDim.c()))
+ if (hint.isNotEmpty()) Text(hint, style = TypeScale.SECONDARY.style(t.text.c()))
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DiffSheet.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DiffSheet.kt
new file mode 100644
index 00000000..bbf6570f
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DiffSheet.kt
@@ -0,0 +1,104 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.DiffState
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.DiffRow
+
+/** What the file-change sheet draws a row in: the colour of its text and of the tint behind it. */
+internal object DiffLook {
+ val ADDED = Color(0xFF34D399)
+ val REMOVED = Color(0xFFFF8D97)
+
+ fun text(kind: Char): Color = when (kind) {
+ '+' -> ADDED
+ '-' -> REMOVED
+ '@' -> Color(IslandSurface.TEXT_DIM)
+ else -> Color(IslandSurface.TEXT)
+ }
+
+ fun tint(kind: Char): Color = when (kind) {
+ '+' -> ADDED.copy(alpha = 0.12f)
+ '-' -> REMOVED.copy(alpha = 0.12f)
+ else -> Color.Transparent
+ }
+
+ /** What is said besides the colour, so the change is not carried by colour alone. */
+ fun marker(kind: Char): String = when (kind) {
+ '+' -> "+"
+ '-' -> "−"
+ '@' -> ""
+ else -> " "
+ }
+}
+
+/**
+ * What an agent changed in one file, as the computer sent it when asked: up to 200 lines, added and removed lines
+ * coloured and also marked with + and −. Held in memory while this is open; nothing is stored.
+ */
+@Composable
+fun DiffSheet(model: AppModel) {
+ val state = model.diffState
+ if (state is DiffState.Idle) return
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ BottomSheetHost(onDismiss = { model.closeDiff() }) {
+ val name = when (state) {
+ is DiffState.Loading -> state.name
+ is DiffState.Ready -> state.diff.name
+ is DiffState.Failed -> state.name
+ DiffState.Idle -> ""
+ }
+ Text(name, style = TypeScale.TITLE.style(white), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ when (state) {
+ is DiffState.Loading -> Text(stringResource(R.string.file_loading), Modifier.padding(vertical = 16.dp), style = TypeScale.BODY.style(dim))
+ is DiffState.Failed -> Text(stringResource(R.string.file_failed), Modifier.padding(vertical = 16.dp), style = TypeScale.BODY.style(dim))
+ is DiffState.Ready -> {
+ val d = state.diff
+ Text(stringResource(R.string.file_summary, d.added, d.removed), Modifier.padding(top = 2.dp, bottom = 10.dp), style = TypeScale.SECONDARY.style(dim))
+ val note = when {
+ d.gone -> R.string.file_gone
+ d.tooLarge -> R.string.file_too_large
+ d.rows.isEmpty() -> R.string.file_empty
+ else -> null
+ }
+ if (note != null) Text(stringResource(note), Modifier.padding(bottom = 12.dp), style = TypeScale.BODY.style(dim))
+ else {
+ LazyColumn(Modifier.fillMaxWidth().heightIn(max = 420.dp)) {
+ itemsIndexed(d.rows) { _, row -> DiffLine(row) }
+ }
+ if (d.truncated) Text(stringResource(R.string.file_truncated), Modifier.padding(top = 8.dp), style = TypeScale.SECONDARY.style(dim))
+ }
+ }
+ DiffState.Idle -> {}
+ }
+ PillButton(stringResource(R.string.file_close), { model.closeDiff() }, Modifier.fillMaxWidth().padding(top = 12.dp), onDark = true)
+ }
+}
+
+@Composable
+private fun DiffLine(row: DiffRow) {
+ val mono = TypeScale.MONO.style(DiffLook.text(row.kind))
+ Row(Modifier.fillMaxWidth().background(DiffLook.tint(row.kind)).padding(horizontal = 6.dp, vertical = 1.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(DiffLook.marker(row.kind), style = mono.copy(fontFamily = FontFamily.Monospace))
+ Text(row.text, Modifier.weight(1f), style = mono.copy(fontFamily = FontFamily.Monospace))
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/DiscoveryHint.kt b/android/app/src/main/kotlin/com/coucou/android/ui/DiscoveryHint.kt
new file mode 100644
index 00000000..2c4d6202
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/DiscoveryHint.kt
@@ -0,0 +1,75 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.OutlinedTextFieldDefaults
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+
+/**
+ * Shown on Home when the saved address failed and a search of about 15 seconds found nothing. Calm, with the usual
+ * reasons (same Wi-Fi? asleep? firewall? client isolation) and two ways out: pair again, or type the address.
+ */
+@Composable
+fun DiscoveryHint(onPairAgain: () -> Unit, onEnterAddress: () -> Unit) {
+ val t = tokens()
+ Panel {
+ Column(Modifier.padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(stringResource(R.string.discovery_title), style = TypeScale.HEADLINE.style(t.text.c()))
+ Text(stringResource(R.string.discovery_body), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ PillButton(stringResource(R.string.discovery_pair_again), onPairAgain, Modifier.weight(1f))
+ PillButton(stringResource(R.string.discovery_enter_address), onEnterAddress, Modifier.weight(1f))
+ }
+ }
+ }
+}
+
+/** The computer's address typed by hand ("192.168.1.20" or "192.168.1.20:47821"). Only the address changes: the pairing and the certificate stay. */
+@Composable
+fun AddressSheet(model: AppModel, onDismiss: () -> Unit) {
+ var text by remember { mutableStateOf("") }
+ var bad by remember { mutableStateOf(false) }
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ BottomSheetHost(onDismiss) {
+ Text(stringResource(R.string.address_title), style = TypeScale.TITLE.style(white))
+ Text(stringResource(R.string.address_hint), Modifier.padding(top = 4.dp, bottom = 12.dp), style = TypeScale.SECONDARY.style(dim))
+ OutlinedTextField(
+ text, { text = it; bad = false }, Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(14.dp),
+ placeholder = { Text("192.168.1.20:47821", color = Color(Tokens.DARK.textFaint)) },
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedTextColor = white, unfocusedTextColor = white, cursorColor = white,
+ focusedBorderColor = white, unfocusedBorderColor = Color.White.copy(alpha = 0.25f),
+ ),
+ )
+ if (bad) Text(stringResource(R.string.address_bad), Modifier.padding(top = 8.dp), style = TypeScale.SECONDARY.style(Color(Tokens.DARK.danger)))
+ PillButton(
+ stringResource(R.string.address_save),
+ { if (model.setAddress(text)) onDismiss() else bad = true },
+ Modifier.fillMaxWidth().padding(top = 16.dp), PillKind.PRIMARY, enabled = text.isNotBlank(), onDark = true,
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/HomePanel.kt b/android/app/src/main/kotlin/com/coucou/android/ui/HomePanel.kt
new file mode 100644
index 00000000..f919aec8
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/HomePanel.kt
@@ -0,0 +1,209 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.windowInsetsPadding
+import androidx.compose.foundation.border
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.core.Decision
+import com.coucou.android.core.HistoryDays
+import com.coucou.android.core.HomePanel
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.Pills
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiConst
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+import com.coucou.android.mochi.Rgb
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
+
+internal fun stateLabel(state: BotState): Int = when (state) {
+ BotState.IDLE -> R.string.state_ready
+ BotState.WORKING -> R.string.state_working
+ BotState.THINKING -> R.string.state_thinking
+ BotState.SEARCHING -> R.string.state_searching
+ BotState.APPROVAL -> R.string.state_approval
+ BotState.QUESTION -> R.string.state_question
+ BotState.ERROR -> R.string.state_error
+ BotState.FINISHED -> R.string.state_finished
+ BotState.RATELIMIT -> R.string.state_ratelimit
+ BotState.SLEEPING -> R.string.state_sleeping
+ BotState.DIZZY -> R.string.state_dizzy
+}
+
+internal fun rgbColor(c: Rgb) = Color(c.r.toFloat(), c.g.toFloat(), c.b.toFloat())
+
+
+/** The colour of an agent's state (Louis's state colours), for dots and glows. */
+internal fun stateColor(state: BotState): Color =
+ if (state == BotState.IDLE) StatusColors.online else MochiConst.STATES[state]?.color?.let(::rgbColor) ?: StatusColors.offline
+
+/**
+ * The hero of Home: Louis's island grown to full width and hanging from the top edge of the screen. It
+ * holds the agent that matters most, with its own Mochi in its own colour (the one you chose on the
+ * computer), its name, one plain sentence, and at most two buttons. Black, with a soft
+ * glow in the state's colour. No step counter: the computer cannot know how many steps are left.
+ */
+@Composable
+fun HeroCard(
+ focus: SessionInfo?, engine: MochiEngine, touch: Modifier, link: HomePanel.Link, running: Int,
+ linkDot: Color, linkText: String, onLink: () -> Unit, onDetails: (() -> Unit)?,
+ /** Opens the question sheet; non-null only while the agent has a question. */
+ onQuestion: (() -> Unit)? = null,
+ /** The phone can answer this question here (the `answers` capability): the button says so. */
+ canAnswer: Boolean = false,
+) {
+ val state = focus?.state ?: BotState.SLEEPING
+ val wash = MochiConst.STATES[state]?.color?.let(::rgbColor)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ val white = Color(IslandSurface.TEXT)
+ HeroPanel(wash = wash) {
+ Column(
+ Modifier.windowInsetsPadding(WindowInsets.statusBars).padding(start = Spacing.INSIDE.dp, end = Spacing.INSIDE.dp, top = 12.dp, bottom = 18.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ StateDot(linkDot)
+ Spacer(Modifier.width(8.dp))
+ Text(linkText, Modifier.weight(1f), style = TypeScale.LABEL.style(dim), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (running > 0) Text(stringResource(R.string.home_running, running), style = TypeScale.LABEL.style(dim), maxLines = 1)
+ }
+ if (focus == null) {
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ MochiView(engine, Modifier.size(112.dp).then(touch))
+ Text(stringResource(R.string.home_empty_title), style = TypeScale.TITLE.style(white))
+ Text(stringResource(R.string.home_empty_hint), style = TypeScale.SECONDARY.style(dim), maxLines = 3)
+ }
+ } else {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ MochiView(engine, Modifier.size(108.dp).then(touch))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ val pillName = Pills.byId(focus.pillId)?.name.orEmpty()
+ val name = focus.agent.ifBlank { pillName }.ifBlank { stringResource(R.string.app_name) }
+ Text(name, style = TypeScale.TITLE.style(white), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ Text(
+ if (pillName.isNotBlank() && pillName != name) pillName else stringResource(R.string.agent_kind),
+ style = TypeScale.SECONDARY.style(dim), maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ HomeText.line(focus) ?: stringResource(stateLabel(state)), Modifier.padding(top = 4.dp),
+ style = TypeScale.HEADLINE.style(white), maxLines = 3, overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ }
+ if (link != HomePanel.Link.NONE || onDetails != null || onQuestion != null) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (link != HomePanel.Link.NONE) {
+ PillButton(
+ stringResource(if (link == HomePanel.Link.PAIR) R.string.link_pair else R.string.link_approval), onLink,
+ kind = PillKind.PRIMARY, onDark = true,
+ )
+ }
+ if (onQuestion != null) PillButton(stringResource(if (canAnswer) R.string.question_see_answer else R.string.question_see), onQuestion, kind = PillKind.PRIMARY, onDark = true)
+ if (onDetails != null) {
+ PillButton(
+ stringResource(R.string.session_details), onDetails, onDark = true,
+ icon = { CoucouIcon(IconKind.CHEVRON, tint = white, size = 18.dp) },
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+/** The other agents, one full-width row each: its small Mochi in its colour, its name and one plain line. Tap to make it the main one. */
+@Composable
+fun AgentRows(others: List<SessionInfo>, engineFor: (SessionInfo) -> MochiEngine, onPick: (SessionInfo) -> Unit) {
+ val t = tokens()
+ Panel {
+ others.forEachIndexed { i, s ->
+ if (i > 0) RowDivider()
+ val name = s.agent.ifBlank { Pills.byId(s.pillId)?.name.orEmpty() }
+ val state = stringResource(stateLabel(s.state))
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 64.dp).clickable(role = Role.Button) { onPick(s) }
+ .padding(horizontal = Spacing.INSIDE.dp, vertical = 12.dp).semantics(mergeDescendants = true) {},
+ horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ MochiView(engineFor(s), Modifier.size(40.dp))
+ Column(Modifier.weight(1f)) {
+ Text(name, style = TypeScale.BODY.style(t.text.c()).copy(fontWeight = FontWeight.SemiBold), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(HomeText.line(s) ?: state, style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ StateDot(stateColor(s.state))
+ }
+ }
+ }
+}
+
+/** The last few things you allowed or denied, in plain words, with "See all" to the full list. */
+@Composable
+fun RecentPanel(decisions: List<Decision>, onAll: () -> Unit) {
+ if (decisions.isEmpty()) return
+ val t = tokens()
+ val zone = androidx.compose.runtime.remember { ZoneId.systemDefault() }
+ val timeFormat = androidx.compose.runtime.remember { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) }
+ val dateFormat = androidx.compose.runtime.remember { DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT) }
+ val now = System.currentTimeMillis()
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ SectionHeading(stringResource(R.string.recent_title), Modifier.weight(1f))
+ Text(
+ stringResource(R.string.recent_all),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button, onClick = onAll).padding(horizontal = 4.dp, vertical = 12.dp),
+ style = TypeScale.LABEL.style(t.textDim.c()),
+ )
+ }
+ Panel {
+ decisions.take(2).forEachIndexed { i, d ->
+ if (i > 0) RowDivider()
+ val (day, date) = HistoryDays.classify(d.atMs, now, zone)
+ val whenText = when (day) {
+ HistoryDays.Day.TODAY -> timeFormat.format(Instant.ofEpochMilli(d.atMs).atZone(zone).toLocalTime())
+ HistoryDays.Day.YESTERDAY -> stringResource(R.string.history_yesterday)
+ HistoryDays.Day.OTHER -> dateFormat.format(date)
+ }
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(role = Role.Button, onClick = onAll).padding(horizontal = Spacing.INSIDE.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ StateDot(if (d.allowed) StatusColors.online else t.danger.c())
+ Text(HomeText.recent(d.allowed, d.tool), Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(whenText, style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1)
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/IslandOverlay.kt b/android/app/src/main/kotlin/com/coucou/android/ui/IslandOverlay.kt
new file mode 100644
index 00000000..698c37a5
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/IslandOverlay.kt
@@ -0,0 +1,442 @@
+package com.coucou.android.ui
+
+import android.content.Context
+import android.graphics.PixelFormat
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import android.util.Log
+import android.view.Gravity
+import android.view.WindowInsets
+import android.view.WindowManager
+import androidx.compose.foundation.background
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.MotionSpec
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.requiredWidth
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.LifecycleRegistry
+import androidx.lifecycle.ViewModelStore
+import androidx.lifecycle.ViewModelStoreOwner
+import androidx.lifecycle.setViewTreeLifecycleOwner
+import androidx.lifecycle.setViewTreeViewModelStoreOwner
+import androidx.savedstate.SavedStateRegistry
+import androidx.savedstate.SavedStateRegistryController
+import androidx.savedstate.SavedStateRegistryOwner
+import androidx.savedstate.setViewTreeSavedStateRegistryOwner
+import com.coucou.android.R
+import com.coucou.android.core.IslandBox
+import com.coucou.android.core.IslandGeometry
+import com.coucou.android.core.IslandSpec
+import com.coucou.android.core.IslandTimeline
+import com.coucou.android.core.OverlayPolicy
+import com.coucou.android.core.PxRect
+import com.coucou.android.core.Tracked
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+
+/**
+ * The notch of the desktop, for the phone: a black island hanging from the top of the screen,
+ * centred on the camera cut-out, over whatever app is open. It drops while an agent works, shows
+ * how it ended for 10 s, then goes back up with the PC's motion (spring when it grows, a 340 ms
+ * curve when it shrinks). A permission request or a question keeps it open.
+ *
+ * When it opens and closes is decided by [IslandTimeline] (pure, tested); this class only draws it
+ * and keeps one timer, for the next deadline. Nothing exists while it is hidden: the window is added
+ * when it opens and removed when it has gone up, so there is no timer and no frame loop.
+ * Needs the user's one-time "display over other apps" permission.
+ */
+class IslandOverlay(
+ private val context: Context,
+ private val clock: () -> Double,
+ private val onAllow: (fingerprint: String) -> Unit,
+ private val onDeny: (fingerprint: String) -> Unit,
+ private val onOpen: () -> Unit,
+) {
+ private val wm = context.getSystemService(WindowManager::class.java)
+ private val main = Handler(Looper.getMainLooper())
+ private val timeline = IslandTimeline(clock)
+
+ private var view: ComposeView? = null
+ private var owner: Owner? = null
+ private var box: IslandBox? = null
+ private var shownAt = 0.0
+
+ private var spec by mutableStateOf<IslandSpec?>(null)
+ private val width = Tracked(0.0)
+ private val height = Tracked(0.0)
+ private val radius = Tracked(0.0)
+ /** Bumped whenever a new target is set, to (re)start the frame loop that only runs while moving. */
+ private var motionKey by mutableIntStateOf(0)
+
+ private val deadline = Runnable { safely { timeline.tick(); sync() } }
+
+ fun permitted(): Boolean = Settings.canDrawOverlays(context)
+
+ /** Something is going on right now: an agent works, a question waits, a request waits. Null: nothing. */
+ fun setActive(next: IslandSpec?) = safely {
+ timeline.setActive(next)
+ sync()
+ }
+
+ /** An agent finished, failed or hit a limit: shown for 10 s, then the island goes up. */
+ fun flash(next: IslandSpec) = safely {
+ timeline.flash(next)
+ sync()
+ }
+
+ /** Close at once, without animation (Coucou came to the front, the switch went off, the link dropped). */
+ fun hide() = safely {
+ timeline.dismiss()
+ removeView()
+ }
+
+ /** True when the island is on screen showing a request: the notification can then stay quiet. */
+ fun isShowingRequest(): Boolean =
+ view != null && timeline.phase == IslandTimeline.Phase.OPEN && timeline.current?.kind == IslandSpec.Kind.APPROVAL &&
+ seenByUser()
+
+ /** The island is a window of its own: nobody sees it with the screen off, in a screen saver or behind the lock screen. */
+ private fun seenByUser(): Boolean = runCatching {
+ context.getSystemService(android.os.PowerManager::class.java).isInteractive &&
+ !context.getSystemService(android.app.KeyguardManager::class.java).isKeyguardLocked
+ }.getOrDefault(false)
+
+ /** The island is a nicety on top of the app: nothing that goes wrong with the window may reach the caller. */
+ private inline fun safely(block: () -> Unit) {
+ try {
+ block()
+ } catch (e: Exception) {
+ Log.w(TAG, "island failed: ${e.javaClass.simpleName}")
+ runCatching { timeline.dismiss(); removeView() }
+ }
+ }
+
+ // ── From the timeline to the window ──────────────────────────────────────
+
+ private fun sync() {
+ main.removeCallbacks(deadline)
+ val phase = timeline.phase
+ val current = timeline.current
+ Log.d(TAG, "phase=$phase content=${current?.kind}")
+ if (phase == IslandTimeline.Phase.HIDDEN || current == null) {
+ removeView()
+ return
+ }
+ val opening = view == null
+ if (!ensureView()) return
+ val b = box ?: return
+ if (spec?.kind != current.kind || spec?.fingerprint != current.fingerprint) shownAt = clock()
+ spec = current
+ val now = clock()
+ if (opening) {
+ width.jump(b.notchWidth.toDouble()); height.jump(0.0); radius.jump(b.cornerSmall.toDouble())
+ }
+ val reduced = MotionSpec.isReduced(Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f))
+ if (phase == IslandTimeline.Phase.OPEN) {
+ val (w, h) = IslandGeometry.sizeFor(b, current.kind)
+ val corner = (if (current.kind == IslandSpec.Kind.WORKING) b.cornerSmall else b.cornerLarge).toDouble()
+ // "Remove animations": no spring, the island simply appears at its size.
+ if (reduced) { width.jump(w.toDouble()); height.jump(h.toDouble()); radius.jump(corner) }
+ else { width.goTo(w.toDouble(), now); height.goTo(h.toDouble(), now); radius.goTo(corner, now) }
+ } else if (reduced) {
+ width.jump(b.notchWidth.toDouble()); height.jump(0.0); radius.jump(b.cornerSmall.toDouble())
+ } else {
+ // Back up into the notch: same curve as the PC.
+ width.curveTowards(b.notchWidth.toDouble(), now); height.curveTowards(0.0, now); radius.curveTowards(b.cornerSmall.toDouble(), now)
+ }
+ motionKey++
+ timeline.nextDeadline()?.let { main.postDelayed(deadline, (it - clock()).toLong().coerceAtLeast(0)) }
+ }
+
+ private fun removeView() {
+ main.removeCallbacks(deadline)
+ view?.let { runCatching { wm.removeView(it) } }
+ view = null
+ owner?.destroy()
+ owner = null
+ spec = null
+ }
+
+ private fun measure(): IslandBox {
+ val density = context.resources.displayMetrics.density
+ val metrics = wm.currentWindowMetrics
+ val insets = metrics.windowInsets
+ val cutout = insets.displayCutout?.boundingRectTop?.let { PxRect(it.left, it.top, it.right, it.bottom) }
+ val statusBar = insets.getInsetsIgnoringVisibility(WindowInsets.Type.statusBars()).top
+ .takeIf { it > 0 } ?: (24 * density).toInt()
+ return IslandGeometry.place(metrics.bounds.width(), density, cutout, statusBar)
+ }
+
+ private fun ensureView(): Boolean {
+ if (view != null) return true
+ val b = measure()
+ box = b
+ val params = WindowManager.LayoutParams(
+ WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+ // Not focusable and not modal: touches outside the island go to the app underneath. It may
+ // extend into the display cut-out so its black merges with the camera hole.
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
+ PixelFormat.TRANSLUCENT,
+ ).apply {
+ gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
+ x = b.centerOffsetX
+ y = 0
+ layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
+ }
+ val lifecycleOwner = Owner()
+ val v = ComposeView(context).apply {
+ setViewTreeLifecycleOwner(lifecycleOwner)
+ setViewTreeSavedStateRegistryOwner(lifecycleOwner)
+ setViewTreeViewModelStoreOwner(lifecycleOwner)
+ setContent { Island() }
+ }
+ return try {
+ wm.addView(v, params)
+ owner = lifecycleOwner
+ view = v
+ true
+ } catch (e: Exception) {
+ Log.w(TAG, "cannot add the window: ${e.javaClass.simpleName}") // permission taken away meanwhile
+ lifecycleOwner.destroy()
+ false
+ }
+ }
+
+ /** Every tap goes through here: one made in the first moments is ignored (see OverlayPolicy). */
+ private fun tap(what: String, action: () -> Unit) {
+ if (!OverlayPolicy.tapAccepted(shownAt, clock())) {
+ Log.d(TAG, "ignored an early tap on $what")
+ return
+ }
+ action()
+ }
+
+ // ── What is drawn ────────────────────────────────────────────────────────
+
+ // The island is black: it is the camera hole grown. Colours are the shared always-dark ones.
+ private val ink = Color(IslandSurface.BLACK)
+ private val dim = Color(IslandSurface.TEXT_DIM)
+
+ @Composable
+ private fun Island() {
+ var frame by remember { mutableLongStateOf(0L) }
+ // Runs only while something is moving; when it stops, nothing redraws and nothing is scheduled.
+ LaunchedEffect(motionKey) {
+ var last = 0L
+ while (width.animating || height.animating || radius.animating) {
+ androidx.compose.runtime.withFrameNanos { ns ->
+ val dt = if (last == 0L) 1.0 / 60 else ((ns - last) / 1e9).coerceIn(0.0, 0.1)
+ last = ns
+ val now = clock()
+ width.step(dt, now); height.step(dt, now); radius.step(dt, now)
+ frame = ns
+ }
+ }
+ if (timeline.phase == IslandTimeline.Phase.RETRACTING) {
+ timeline.retractFinished()
+ removeView()
+ }
+ }
+ frame // read, so the island redraws as it moves
+ val b = box ?: return
+ val s = spec ?: return
+ val density = LocalDensity.current
+ fun px(v: Double): Dp = with(density) { v.toFloat().toDp() }
+ val topInset = px(b.topInset.toDouble())
+ val (targetW, targetH) = IslandGeometry.sizeFor(b, s.kind)
+ // The content fades in as the island opens and out as it goes up.
+ val open = ((height.value / targetH.toDouble()) - 0.35) / 0.55
+ val corner = px(radius.value)
+ val ear = IslandGeometry.EAR_DP.dp
+ CompositionLocalProvider(LocalTokens provides Tokens.DARK) {
+ // The island plus a concave flare on each side: its top is flush with the screen's edge and
+ // merges with the camera hole, instead of hanging as a bar below it.
+ Box(Modifier.width(px(width.value) + ear * 2).height(px(height.value))) {
+ Canvas(Modifier.matchParentSize()) { drawFlares(ear.toPx().coerceAtMost(size.height), ink) }
+ Box(
+ Modifier.align(Alignment.TopCenter).width(px(width.value)).fillMaxHeight()
+ .clip(RoundedCornerShape(bottomStart = corner, bottomEnd = corner)).background(ink),
+ ) {
+ Box(
+ Modifier.fillMaxWidth().padding(top = topInset).alpha(open.coerceIn(0.0, 1.0).toFloat()),
+ contentAlignment = Alignment.TopCenter,
+ ) {
+ Box(Modifier.requiredWidth(px(targetW.toDouble())).wrapContentHeight(Alignment.Top, unbounded = true)) {
+ when (s.kind) {
+ IslandSpec.Kind.WORKING -> WorkingStrip(s)
+ IslandSpec.Kind.APPROVAL -> RequestCard(s)
+ else -> ResultCard(s)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /** The two flares: each is the square beside the island minus a quarter circle, so the black curves out to the screen's top edge. */
+ private fun DrawScope.drawFlares(e: Float, color: Color) {
+ if (e <= 0f) return
+ val w = size.width
+ val left = Path().apply {
+ moveTo(0f, 0f); lineTo(e, 0f); lineTo(e, e)
+ arcTo(Rect(Offset(0f, e), e), 0f, -90f, false)
+ close()
+ }
+ val right = Path().apply {
+ moveTo(w, 0f); lineTo(w - e, 0f); lineTo(w - e, e)
+ arcTo(Rect(Offset(w, e), e), 180f, 90f, false)
+ close()
+ }
+ drawPath(left, color)
+ drawPath(right, color)
+ }
+
+ @Composable
+ private fun WorkingStrip(s: IslandSpec) {
+ val engine = remember(s.state) { MochiEngine(clock).apply { setState(s.state, force = true) } }
+ Row(
+ Modifier.fillMaxWidth().clickable { tap("the working strip") { onOpen() } }.padding(horizontal = 18.dp, vertical = 6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ MochiView(engine, Modifier.size(34.dp))
+ Spacer(Modifier.width(10.dp))
+ Column(Modifier.weight(1f)) {
+ Text(s.agent, color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (s.text.isNotBlank()) Text(s.text, color = dim, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
+
+ @Composable
+ private fun ResultCard(s: IslandSpec) {
+ val engine = remember(s.state) { MochiEngine(clock).apply { setState(s.state, force = true) } }
+ val label = when (s.kind) {
+ IslandSpec.Kind.ERROR -> R.string.notif_error
+ IslandSpec.Kind.RATELIMIT -> R.string.notif_ratelimit
+ IslandSpec.Kind.QUESTION -> R.string.notif_question
+ else -> R.string.notif_finished
+ }
+ Row(
+ Modifier.fillMaxWidth().clickable { tap("the result card") { onOpen() } }.padding(horizontal = 18.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ MochiView(engine, Modifier.size(52.dp))
+ Spacer(Modifier.width(12.dp))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(s.agent, color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
+ Spacer(Modifier.width(8.dp))
+ Text(stringResource(label), color = dim, fontSize = 12.sp, maxLines = 1)
+ }
+ val text = if (s.kind == IslandSpec.Kind.QUESTION) stringResource(R.string.island_answer_on_pc) else s.text
+ if (text.isNotBlank()) Text(text, color = Color.White, fontSize = 13.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
+
+ @Composable
+ private fun RequestCard(s: IslandSpec) {
+ val engine = remember { MochiEngine(clock).apply { setState(BotState.APPROVAL, force = true) } }
+ val fingerprint = s.fingerprint ?: return
+ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(Modifier.clickable { tap("the request header") { onOpen() } }, verticalAlignment = Alignment.CenterVertically) {
+ MochiView(engine, Modifier.size(40.dp))
+ Spacer(Modifier.width(10.dp))
+ Column(Modifier.weight(1f)) {
+ Text(s.agent, style = TypeScale.SECONDARY.style(dim), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ // What kind of action, never the command: the exact text is in the app and in the lock prompt.
+ Text(stringResource(R.string.approval_wants, s.text), style = TypeScale.HEADLINE.style(Color.White), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ PillButton(stringResource(R.string.action_deny), { tap("Deny") { onDeny(fingerprint) } }, Modifier.weight(1f), onDark = true)
+ if (s.canAllow) {
+ PillButton(
+ stringResource(R.string.action_allow), { tap("Allow") { onAllow(fingerprint) } }, Modifier.weight(1f), PillKind.PRIMARY, onDark = true,
+ icon = { CoucouIcon(IconKind.LOCK, tint = Color(IslandSurface.ON_PRIMARY), size = 18.dp) },
+ )
+ }
+ }
+ Text(stringResource(if (s.canAllow) R.string.approval_hint else R.string.approval_on_computer), style = TypeScale.LABEL.style(dim), maxLines = 2)
+ }
+ }
+
+ /** A window outside any activity has no lifecycle of its own: Compose needs one to run. */
+ private class Owner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner {
+ override val viewModelStore = ViewModelStore()
+ private val registry = LifecycleRegistry(this)
+ private val controller = SavedStateRegistryController.create(this)
+ override val lifecycle: Lifecycle get() = registry
+ override val savedStateRegistry: SavedStateRegistry get() = controller.savedStateRegistry
+
+ init {
+ controller.performAttach()
+ controller.performRestore(null)
+ registry.currentState = Lifecycle.State.RESUMED
+ }
+
+ fun destroy() {
+ registry.currentState = Lifecycle.State.DESTROYED
+ viewModelStore.clear()
+ }
+ }
+
+ private companion object { const val TAG = "CoucouIsland" }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/LicencesScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/LicencesScreen.kt
new file mode 100644
index 00000000..921f5db2
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/LicencesScreen.kt
@@ -0,0 +1,43 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.core.Licences
+import com.coucou.android.core.TypeScale
+
+/**
+ * Settings > About > Licences: who made what, the full MIT text of Coucou's code, the notice for the artwork, and the Apache 2.0 text with
+ * the libraries it covers. The words are legal text in files under assets/licenses, shown as they are (nothing here is translated).
+ */
+@Composable
+fun LicencesScreen(onBack: () -> Unit) {
+ val t = tokens()
+ val assets = LocalContext.current.assets
+ val paragraphs = remember {
+ Licences.FILES.joinToString("\n\n") { name ->
+ runCatching { assets.open("licenses/$name").bufferedReader().use { it.readText() } }.getOrDefault("")
+ }.let(Licences::paragraphs)
+ }
+ LazyColumn(
+ Modifier.padding(horizontal = Gutter), contentPadding = PaddingValues(bottom = BarClearance),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ item { ScreenTitle(stringResource(R.string.licences_title), onBack) }
+ item { Text(stringResource(R.string.licences_intro), Modifier.padding(horizontal = 4.dp), style = TypeScale.SECONDARY.style(t.textDim.c())) }
+ items(paragraphs) { p ->
+ Text(p, Modifier.padding(horizontal = 4.dp), style = TypeScale.SECONDARY.style(t.text.c()).copy(fontFamily = FontFamily.Monospace))
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/LinkStatus.kt b/android/app/src/main/kotlin/com/coucou/android/ui/LinkStatus.kt
new file mode 100644
index 00000000..7c81df8d
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/LinkStatus.kt
@@ -0,0 +1,31 @@
+package com.coucou.android.ui
+
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.app.Mode
+import com.coucou.android.link.DiscoveryState
+import com.coucou.android.link.LinkState
+
+/** The line under the title ("Connected · My PC") and the colour of its dot, shared by Home and Settings. */
+@Composable
+fun linkStatusText(model: AppModel): String = when (model.mode) {
+ Mode.NONE -> stringResource(R.string.status_not_connected)
+ Mode.DEMO -> stringResource(R.string.demo_mode)
+ Mode.PAIRED -> when (model.linkState) {
+ LinkState.CONNECTED -> "${stringResource(R.string.status_connected)} · ${model.desktopName.orEmpty()}"
+ LinkState.CONNECTING, LinkState.DISCONNECTED ->
+ // The saved address failed and the network is being searched: say so, calmly.
+ if (model.discovery == DiscoveryState.LOOKING) stringResource(R.string.status_looking)
+ else stringResource(if (model.linkState == LinkState.CONNECTING) R.string.status_connecting else R.string.status_not_connected)
+ }
+}
+
+fun linkDotColor(model: AppModel): Color = when {
+ model.mode == Mode.DEMO -> StatusColors.busy
+ model.mode == Mode.PAIRED && model.linkState == LinkState.CONNECTED -> StatusColors.online
+ model.mode == Mode.PAIRED && (model.linkState == LinkState.CONNECTING || model.discovery == DiscoveryState.LOOKING) -> StatusColors.busy
+ else -> StatusColors.offline
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/MochiTouch.kt b/android/app/src/main/kotlin/com/coucou/android/ui/MochiTouch.kt
new file mode 100644
index 00000000..e06766ee
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/MochiTouch.kt
@@ -0,0 +1,54 @@
+package com.coucou.android.ui
+
+import android.os.Handler
+import android.os.Looper
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.input.pointer.pointerInput
+import com.coucou.android.mochi.BotEmote
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.SoundSink
+
+/**
+ * What a finger does to Mochi, as on the computer: a tap is a slap (three quick ones make him dizzy
+ * for a few seconds), a long press is a pet (hearts). The sounds go through [sound], so the sound
+ * switch in Settings silences them too.
+ */
+class MochiTouch(
+ private val engine: MochiEngine,
+ private val sound: SoundSink,
+ private val stateNow: () -> BotState,
+) {
+ private val main = Handler(Looper.getMainLooper())
+
+ /** While true the screen must not reset Mochi's state: he is dizzy on purpose. */
+ var dizzy = false
+ private set
+
+ init {
+ engine.onDizzy = {
+ dizzy = true
+ engine.setState(BotState.DIZZY, force = true)
+ sound.play("dizzy")
+ main.postDelayed({
+ dizzy = false
+ engine.setState(stateNow(), force = true)
+ }, DIZZY_MS)
+ }
+ }
+
+ val modifier: Modifier = Modifier.pointerInput(engine) {
+ detectTapGestures(
+ onTap = { if (!dizzy) engine.slap() },
+ onLongPress = {
+ if (!dizzy) {
+ engine.triggerEmote(BotEmote.LOVE)
+ sound.play("love")
+ }
+ },
+ )
+ }
+
+ private companion object { const val DIZZY_MS = 3_300L }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/PairConfirm.kt b/android/app/src/main/kotlin/com/coucou/android/ui/PairConfirm.kt
new file mode 100644
index 00000000..21c304aa
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/PairConfirm.kt
@@ -0,0 +1,36 @@
+package com.coucou.android.ui
+
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.res.stringResource
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.link.PairingPayload
+
+/**
+ * Asked before a scanned code, or a link opened from the camera app, pairs anything. It names the computer and
+ * its address on the network (and the relay's host when the link has one), never a secret in the link, and says when it replaces the current computer.
+ */
+@Composable
+fun PairConfirm(model: AppModel, link: String) {
+ val p = PairingPayload.parse(link)
+ if (p == null) { model.cancelPairing(); return }
+ AlertDialog(
+ onDismissRequest = { model.cancelPairing() },
+ title = { Text(stringResource(R.string.pair_confirm_title, p.desktopName.ifBlank { p.host })) },
+ text = {
+ Text(
+ stringResource(R.string.pair_confirm_body, p.host, p.port) +
+ // The relay's host is shown too: a code that points somewhere else is visible before anything is stored.
+ (p.relay?.relayUrl()?.host?.let { "\n\n" + stringResource(R.string.pair_confirm_relay, it) } ?: "") +
+ if (model.isPaired) "\n\n" + stringResource(R.string.pair_confirm_replace) else "",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ },
+ confirmButton = { TextButton(onClick = { model.confirmPairing() }) { Text(stringResource(R.string.pair_confirm_ok)) } },
+ dismissButton = { TextButton(onClick = { model.cancelPairing() }) { Text(stringResource(R.string.action_cancel)) } },
+ )
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/PairingScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/PairingScreen.kt
new file mode 100644
index 00000000..93ee2713
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/PairingScreen.kt
@@ -0,0 +1,142 @@
+package com.coucou.android.ui
+
+import android.os.SystemClock
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.windowInsetsPadding
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.OutlinedTextFieldDefaults
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.PairingPayload
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+
+/**
+ * The first thing a new user sees: one clear action. A sleeping Mochi, a sentence, "Scan QR code" as the main
+ * pill, and two quiet ones: paste the link (in a sheet, so no field sits on the screen) and try the demo.
+ */
+@Composable
+fun PairingScreen(model: AppModel, onScan: () -> Unit, onAbout: () -> Unit) {
+ val t = tokens()
+ var pasteOpen by remember { mutableStateOf(false) }
+ val engine = remember { MochiEngine({ SystemClock.elapsedRealtimeNanos() / 1e6 }).apply { setState(BotState.SLEEPING, force = true) } }
+ Column(
+ Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.statusBars).verticalScroll(rememberScrollState())
+ .padding(start = Gutter + 8.dp, end = Gutter + 8.dp, bottom = BarClearance),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Spacer(Modifier.size(48.dp))
+ MochiView(engine, Modifier.size(132.dp))
+ Spacer(Modifier.size(24.dp))
+ Text(stringResource(R.string.pairing_headline), style = TypeScale.DISPLAY.style(t.text.c()).copy(textAlign = TextAlign.Center))
+ Text(
+ stringResource(R.string.pairing_help), Modifier.padding(top = 10.dp, bottom = 28.dp),
+ style = TypeScale.BODY.style(t.textDim.c()).copy(textAlign = TextAlign.Center),
+ )
+ model.message?.let { MessagePanel(it) { model.message = null }; Spacer(Modifier.size(Gap)) }
+ PillButton(
+ stringResource(R.string.scan_button), onScan, Modifier.fillMaxWidth(), PillKind.PRIMARY,
+ icon = { CoucouIcon(IconKind.SCAN, tint = t.onPrimaryButton.c(), size = 20.dp) },
+ )
+ Spacer(Modifier.size(Gap))
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(Gap)) {
+ PillButton(stringResource(R.string.pair_paste_short), { pasteOpen = true }, Modifier.weight(1f))
+ PillButton(stringResource(R.string.demo_try), { model.startDemo() }, Modifier.weight(1f))
+ }
+ Spacer(Modifier.size(32.dp))
+ Text(stringResource(R.string.pairing_footer), style = TypeScale.SECONDARY.style(t.textFaint.c()).copy(textAlign = TextAlign.Center))
+ Text(
+ stringResource(R.string.pairing_about),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button, onClick = onAbout).padding(horizontal = 16.dp, vertical = 14.dp),
+ style = TypeScale.SECONDARY.style(t.textDim.c()).copy(textDecoration = TextDecoration.Underline),
+ )
+ }
+ if (pasteOpen) PasteSheet(model, onDismiss = { pasteOpen = false })
+}
+
+/** The pairing link as text, for people who cannot scan. A link that is not a Coucou one is refused here, with the same words as everywhere. */
+@Composable
+private fun PasteSheet(model: AppModel, onDismiss: () -> Unit) {
+ var text by remember { mutableStateOf("") }
+ var bad by remember { mutableStateOf(false) }
+ val clipboard = LocalClipboardManager.current
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ fun pairWith(link: String) {
+ if (PairingPayload.parse(link) != null) { model.pair(link); onDismiss() } else bad = true
+ }
+ BottomSheetHost(onDismiss) {
+ Text(stringResource(R.string.paste_title), style = TypeScale.TITLE.style(white))
+ Text(stringResource(R.string.paste_hint), Modifier.padding(top = 4.dp, bottom = 12.dp), style = TypeScale.SECONDARY.style(dim))
+ OutlinedTextField(
+ text, { text = it; bad = false }, Modifier.fillMaxWidth(), singleLine = true, shape = RoundedCornerShape(14.dp),
+ placeholder = { Text("coucou://pair?…", color = Color(Tokens.DARK.textFaint)) },
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedTextColor = white, unfocusedTextColor = white, cursorColor = white,
+ focusedBorderColor = white, unfocusedBorderColor = Color.White.copy(alpha = 0.25f),
+ ),
+ )
+ if (bad) Text(stringResource(R.string.msg_bad_link), Modifier.padding(top = 8.dp), style = TypeScale.SECONDARY.style(Color(Tokens.DARK.danger)))
+ Row(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ PillButton(
+ stringResource(R.string.pair_clipboard),
+ { text = clipboard.getText()?.text.orEmpty().trim(); bad = false }, Modifier.weight(1f), onDark = true,
+ )
+ PillButton(stringResource(R.string.pair_button), { pairWith(text.trim()) }, Modifier.weight(1f), PillKind.PRIMARY, enabled = text.isNotBlank(), onDark = true)
+ }
+ }
+}
+
+/** A short notice with a Close button, in a panel. */
+@Composable
+fun MessagePanel(text: String, onClose: () -> Unit) {
+ val t = tokens()
+ Panel {
+ Row(Modifier.padding(start = Spacing.INSIDE.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(text, Modifier.weight(1f).padding(vertical = 12.dp), style = TypeScale.BODY.style(t.text.c()))
+ Text(
+ stringResource(R.string.action_close),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button, onClick = onClose).padding(horizontal = 16.dp, vertical = 14.dp),
+ style = TypeScale.LABEL.style(t.textDim.c()),
+ )
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/ScanScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/ScanScreen.kt
new file mode 100644
index 00000000..085d1e23
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/ScanScreen.kt
@@ -0,0 +1,275 @@
+package com.coucou.android.ui
+
+import android.Manifest
+import android.app.Activity
+import android.content.Context
+import android.content.ContextWrapper
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.provider.Settings
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.camera.core.CameraSelector
+import androidx.camera.core.ImageAnalysis
+import androidx.camera.core.ImageProxy
+import androidx.camera.core.Preview
+import androidx.camera.core.resolutionselector.ResolutionSelector
+import androidx.camera.core.resolutionselector.ResolutionStrategy
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.camera.view.PreviewView
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.windowInsetsPadding
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import com.coucou.android.R
+import com.coucou.android.core.ScanPermission
+import com.coucou.android.scan.QrDecoder
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.delay
+
+private const val ASKED_KEY = "camera_asked"
+
+private tailrec fun Context.activity(): Activity? = when (this) {
+ is Activity -> this
+ is ContextWrapper -> baseContext.activity()
+ else -> null
+}
+
+/**
+ * Reads the pairing QR code with the camera. The camera is asked for only here, used only while this screen is
+ * showing (it is released when the screen is left, paused, or a code was accepted), and no picture is kept or
+ * sent: each frame is looked at for a code and dropped. [onText] gets the text of a code and says whether it was
+ * a Coucou pairing code; anything else is ignored with a short hint.
+ */
+@Composable
+fun ScanScreen(onBack: () -> Unit, onText: (String) -> Boolean) {
+ val context = LocalContext.current
+ val owner = LocalLifecycleOwner.current
+ val prefs = remember { context.getSharedPreferences("coucou_ui", Context.MODE_PRIVATE) }
+ fun hasCamera() = context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
+ var granted by remember { mutableStateOf(hasCamera()) }
+ var asked by remember { mutableStateOf(prefs.getBoolean(ASKED_KEY, false)) }
+ var cameraFailed by remember { mutableStateOf(false) }
+ var wrong by remember { mutableStateOf(false) }
+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { ok ->
+ asked = true
+ prefs.edit().putBoolean(ASKED_KEY, true).apply()
+ granted = ok
+ }
+ // Back from Android's settings: the user may have allowed it there.
+ DisposableEffect(owner) {
+ val obs = LifecycleEventObserver { _, e -> if (e == Lifecycle.Event.ON_RESUME) granted = hasCamera() }
+ owner.lifecycle.addObserver(obs)
+ onDispose { owner.lifecycle.removeObserver(obs) }
+ }
+ LaunchedEffect(wrong) { if (wrong) { delay(2_500); wrong = false } }
+
+ val state = ScanPermission.state(
+ granted, asked, canExplain = context.activity()?.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) == true,
+ )
+
+ val backLabel = stringResource(R.string.action_back)
+ // A camera screen: black, edge to edge, with light text.
+ Column(
+ Modifier.fillMaxSize().background(Color(IslandSurface.BLACK)).windowInsetsPadding(WindowInsets.statusBars).padding(horizontal = Gutter),
+ verticalArrangement = Arrangement.spacedBy(Gap),
+ ) {
+ Row(Modifier.padding(top = 4.dp), verticalAlignment = Alignment.CenterVertically) {
+ Box(
+ Modifier.size(Spacing.MIN_TOUCH.dp).clip(CircleShape).clickable(role = Role.Button, onClick = onBack).semantics { contentDescription = backLabel },
+ contentAlignment = Alignment.Center,
+ ) { CoucouIcon(IconKind.BACK, tint = Color(IslandSurface.TEXT), size = 24.dp) }
+ Text(stringResource(R.string.scan_title), style = TypeScale.TITLE.style(Color(IslandSurface.TEXT)), maxLines = 1)
+ }
+ when {
+ state == ScanPermission.State.GRANTED && !cameraFailed -> {
+ Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) {
+ val current by rememberUpdatedState(onText)
+ CameraView(
+ onFound = { text ->
+ val accepted = current(text)
+ if (!accepted) wrong = true
+ accepted
+ },
+ onFailed = { cameraFailed = true },
+ )
+ Viewfinder()
+ }
+ Text(
+ stringResource(if (wrong) R.string.scan_not_pairing else R.string.scan_hint), Modifier.fillMaxWidth().padding(bottom = Gap),
+ style = TypeScale.BODY.style(if (wrong) Color(Tokens.DARK.danger) else Color(IslandSurface.TEXT_DIM)).copy(textAlign = TextAlign.Center),
+ )
+ }
+ state == ScanPermission.State.GRANTED -> Message(stringResource(R.string.scan_camera_error), onBack)
+ state == ScanPermission.State.ASK -> {
+ Text(stringResource(R.string.scan_why), Modifier.padding(top = Gap), style = TypeScale.BODY.style(Color(IslandSurface.TEXT)))
+ PillButton(stringResource(R.string.scan_allow), { launcher.launch(Manifest.permission.CAMERA) }, Modifier.fillMaxWidth(), PillKind.PRIMARY, onDark = true)
+ PillButton(stringResource(R.string.scan_paste_instead), onBack, Modifier.fillMaxWidth(), onDark = true)
+ }
+ else -> {
+ Text(stringResource(R.string.scan_blocked), Modifier.padding(top = Gap), style = TypeScale.BODY.style(Color(IslandSurface.TEXT)))
+ PillButton(
+ stringResource(R.string.scan_open_settings),
+ { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))) },
+ Modifier.fillMaxWidth(), PillKind.PRIMARY, onDark = true,
+ )
+ PillButton(stringResource(R.string.scan_paste_instead), onBack, Modifier.fillMaxWidth(), onDark = true)
+ }
+ }
+ }
+}
+
+@Composable
+private fun Message(text: String, onBack: () -> Unit) {
+ Text(text, Modifier.padding(top = Gap), style = TypeScale.BODY.style(Color(IslandSurface.TEXT)))
+ PillButton(stringResource(R.string.scan_paste_instead), onBack, Modifier.fillMaxWidth(), onDark = true)
+}
+
+/** A dimmed frame with a clear square in the middle, where the code should be. */
+@Composable
+private fun Viewfinder() {
+ val accent = Color.White
+ Canvas(Modifier.fillMaxSize()) {
+ val side = size.minDimension * 0.7f
+ val left = (size.width - side) / 2f
+ val top = (size.height - side) / 2f
+ val dim = Color(0x99000000)
+ drawRect(dim, Offset.Zero, Size(size.width, top))
+ drawRect(dim, Offset(0f, top + side), Size(size.width, size.height - top - side))
+ drawRect(dim, Offset(0f, top), Size(left, side))
+ drawRect(dim, Offset(left + side, top), Size(size.width - left - side, side))
+ drawRoundRect(accent, Offset(left, top), Size(side, side), CornerRadius(16.dp.toPx()), style = Stroke(3.dp.toPx()))
+ }
+}
+
+/**
+ * The camera preview and the code reader. Bound to this screen's lifecycle and unbound when it leaves the
+ * composition, so the camera is released on leaving, on pausing and once a code was accepted. [onFound]
+ * returns whether the code was accepted; after an accepted one no more frames are read.
+ */
+@Composable
+private fun CameraView(onFound: (String) -> Boolean, onFailed: () -> Unit) {
+ val context = LocalContext.current
+ val owner = LocalLifecycleOwner.current
+ // COMPATIBLE (a texture) so the rounded corners and the viewfinder above it draw properly.
+ val previewView = remember {
+ PreviewView(context).apply {
+ implementationMode = PreviewView.ImplementationMode.COMPATIBLE
+ scaleType = PreviewView.ScaleType.FILL_CENTER
+ }
+ }
+ val executor = remember { Executors.newSingleThreadExecutor() }
+ val done = remember { AtomicBoolean(false) }
+ val found by rememberUpdatedState(onFound)
+ val failed by rememberUpdatedState(onFailed)
+
+ DisposableEffect(owner) {
+ val decoder = QrDecoder()
+ var provider: ProcessCameraProvider? = null
+ var analysis: ImageAnalysis? = null
+ var lastWrong = ""
+ var lastWrongAt = 0L
+ val future = ProcessCameraProvider.getInstance(context)
+ future.addListener({
+ try {
+ val p = future.get()
+ provider = p
+ val preview = Preview.Builder().build().also { it.setSurfaceProvider(previewView.surfaceProvider) }
+ val a = ImageAnalysis.Builder()
+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
+ .setResolutionSelector(
+ ResolutionSelector.Builder()
+ .setResolutionStrategy(ResolutionStrategy(android.util.Size(1280, 720), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER))
+ .build(),
+ )
+ .build()
+ a.setAnalyzer(executor) { image: ImageProxy ->
+ try {
+ if (!done.get()) {
+ val plane = image.planes[0] // brightness only
+ val buf = plane.buffer
+ val bytes = ByteArray(buf.remaining()).also { buf.get(it) }
+ val text = decoder.decode(bytes, plane.rowStride, image.width, image.height)
+ val now = System.currentTimeMillis()
+ // The same wrong code in view is not reported again for a moment.
+ if (text != null && (text != lastWrong || now - lastWrongAt > 2_500)) {
+ var accepted = false
+ val latch = java.util.concurrent.CountDownLatch(1)
+ previewView.post { accepted = found(text); latch.countDown() }
+ latch.await(2, java.util.concurrent.TimeUnit.SECONDS)
+ if (accepted) {
+ done.set(true)
+ previewView.post { provider?.unbindAll() } // released at once, before the screen even changes
+ } else {
+ lastWrong = text; lastWrongAt = now
+ }
+ }
+ }
+ } finally {
+ image.close() // the frame is dropped; nothing is kept
+ }
+ }
+ analysis = a
+ p.unbindAll()
+ p.bindToLifecycle(owner, CameraSelector.DEFAULT_BACK_CAMERA, preview, a)
+ } catch (e: Exception) {
+ failed()
+ }
+ }, context.mainExecutor)
+ onDispose {
+ done.set(true)
+ analysis?.clearAnalyzer()
+ provider?.unbindAll()
+ executor.shutdown()
+ }
+ }
+ AndroidView({ previewView }, Modifier.fillMaxSize())
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/ServicesPanel.kt b/android/app/src/main/kotlin/com/coucou/android/ui/ServicesPanel.kt
new file mode 100644
index 00000000..e1b14012
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/ServicesPanel.kt
@@ -0,0 +1,51 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.ServiceCard
+
+/**
+ * The service cards the user allowed on the computer, read-only: the same headline and short lines as the pills
+ * there. Nothing here can be tapped to change anything, and no link or address is ever in a card.
+ */
+@Composable
+fun ServicesPanel(cards: List<ServiceCard>) {
+ if (cards.isEmpty()) return
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ SectionHeading(stringResource(R.string.services_title))
+ for (c in cards) ServiceCardView(c)
+ }
+}
+
+@Composable
+private fun ServiceCardView(c: ServiceCard) {
+ val t = tokens()
+ Panel {
+ Column(Modifier.fillMaxWidth().padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(c.title, Modifier.weight(1f), style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ c.reason?.let { Text(it, style = TypeScale.LABEL.style(t.textDim.c()), maxLines = 1, overflow = TextOverflow.Ellipsis) }
+ }
+ Text(c.headline, style = TypeScale.TITLE.style(t.text.c()), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ for (line in c.items) {
+ Row(horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(line.label, Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (line.detail.isNotEmpty()) Text(line.detail, style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1)
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/SessionScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/SessionScreen.kt
new file mode 100644
index 00000000..9b442915
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/SessionScreen.kt
@@ -0,0 +1,157 @@
+package com.coucou.android.ui
+
+import android.os.SystemClock
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.TypeScale
+import com.coucou.android.mochi.MochiConst
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.HomePanel
+import com.coucou.android.core.Pills
+import com.coucou.android.core.ToolLabels
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+
+/**
+ * One agent in detail, from what the computer sends with "Show session details on the phone": the project's
+ * folder name, how far it got, the last message and the steps it took (newest first, in plain words).
+ * Without that switch there is nothing to show but a hint on where to turn it on.
+ */
+@Composable
+fun SessionScreen(model: AppModel, pillId: String, onBack: () -> Unit) {
+ val s = model.sessions.firstOrNull { it.pillId == pillId }
+ val clock = remember { { SystemClock.elapsedRealtimeNanos() / 1e6 } }
+ val engine = remember(pillId) { MochiEngine(clock) }
+ if (s == null) {
+ Column(Modifier.fillMaxSize().padding(horizontal = Gutter)) {
+ ScreenTitle(stringResource(R.string.session_details), onBack)
+ Text(stringResource(R.string.session_ended), Modifier.padding(Gutter), style = TypeScale.BODY.style(tokens().textDim.c()))
+ }
+ return
+ }
+ if (engine.state != s.state) engine.setState(s.state)
+ // Its own colour, like on Home: the Mochi's body, the glow's state colour stays Louis's.
+ engine.bodyColor = HomePanel.colorHex(s)?.let { HomePanel.rgb(it) }
+ val name = s.agent.ifBlank { Pills.byId(s.pillId)?.name.orEmpty() }
+ val accent = HomePanel.colorHex(s)?.let { HomePanel.rgb(it) }?.let(::rgbColor) ?: tokens().text.c()
+ val t = tokens()
+ val busy = s.state == BotState.WORKING || s.state == BotState.THINKING || s.state == BotState.SEARCHING
+
+ LazyColumn(Modifier.fillMaxSize().padding(horizontal = Gutter), verticalArrangement = Arrangement.spacedBy(Gap)) {
+ item { ScreenTitle(name, onBack) }
+ item {
+ Panel(wash = MochiConst.STATES[s.state]?.color?.let(::rgbColor)) {
+ Row(Modifier.padding(Gutter), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Gutter)) {
+ MochiView(engine, Modifier.size(96.dp))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ HomeText.line(s) ?: stringResource(stateLabel(s.state)), style = TypeScale.HEADLINE.style(t.text.c()),
+ maxLines = 3, overflow = TextOverflow.Ellipsis,
+ )
+ s.project?.let { Chip(stringResource(R.string.session_project, it)) }
+ }
+ }
+ }
+ }
+ if (!s.finalLine.isNullOrBlank()) {
+ item { SectionHeading(stringResource(R.string.session_last)) }
+ item {
+ Panel(wash = MochiConst.STATES[BotState.FINISHED]?.color?.let(::rgbColor)) {
+ SelectionContainer { Text(s.finalLine, Modifier.padding(Gutter), style = TypeScale.BODY.style(t.text.c())) }
+ }
+ }
+ }
+ if (s.files.isNotEmpty()) {
+ item { SectionHeading(stringResource(R.string.files_heading)) }
+ item {
+ Panel {
+ // Newest change first, like the steps.
+ s.files.asReversed().forEachIndexed { i, f ->
+ if (i > 0) RowDivider()
+ ListRow(
+ f.name, hint = if (f.isNew) stringResource(R.string.files_new) else null,
+ onClick = { model.openDiff(s.pillId, f) },
+ trailing = {
+ Text(
+ stringResource(R.string.files_counts, f.added, f.removed), maxLines = 1,
+ style = TypeScale.SECONDARY.style(t.textDim.c()).copy(fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace),
+ )
+ },
+ )
+ }
+ }
+ }
+ }
+ item { SectionHeading(stringResource(R.string.session_steps)) }
+ val steps = HomePanel.stepsNewestFirst(s)
+ if (steps.isEmpty()) {
+ item {
+ Panel {
+ Text(
+ stringResource(if (model.detailsOffered) R.string.session_no_steps else R.string.session_hint),
+ Modifier.padding(Gutter), style = TypeScale.SECONDARY.style(t.textDim.c()),
+ )
+ }
+ }
+ } else {
+ item {
+ Panel {
+ SelectionContainer {
+ Column {
+ steps.forEachIndexed { i, step ->
+ if (i > 0) RowDivider()
+ val current = i == 0 && busy
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = Gutter, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ // Done steps carry a check; the one being worked on carries the agent's dot.
+ if (current) StateDot(accent, Modifier.padding(horizontal = 7.dp))
+ else CoucouIcon(IconKind.CHECK, tint = if (i == 0) StatusColors.online else t.textFaint.c(), size = 22.dp)
+ // Free text is never shown (it can hold a command or a path), so a step the label cannot name
+ // gets a neutral word instead of an empty row.
+ Text(
+ ToolLabels.label(step).ifEmpty {
+ stringResource(if (current) R.string.session_step_working else R.string.session_step_done)
+ },
+ Modifier.weight(1f),
+ style = TypeScale.BODY.style(if (i == 0) t.text.c() else t.textDim.c()).copy(fontWeight = if (current) FontWeight.SemiBold else FontWeight.Normal),
+ maxLines = 4, overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ item { Spacer(Modifier.height(Gutter)) }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/SettingsScreens.kt b/android/app/src/main/kotlin/com/coucou/android/ui/SettingsScreens.kt
new file mode 100644
index 00000000..33644ee3
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/SettingsScreens.kt
@@ -0,0 +1,334 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.draw.alpha
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.coucou.android.Attribution
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.app.Mode
+import com.coucou.android.core.HistoryDays
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.QuietHours
+import com.coucou.android.core.RelayLineKind
+import com.coucou.android.core.RelayStatus
+import com.coucou.android.link.LinkState
+import com.coucou.android.sound.SoundVolume
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
+
+/**
+ * The screen's title on one line; a long title is cut with "…". Sub-pages pass [onBack] and get a Back
+ * button; the three tab screens pass null (the bar is their navigation) and get the plain title.
+ */
+@Composable
+fun ScreenTitle(title: String, onBack: (() -> Unit)?, trailing: @Composable (() -> Unit)? = null) {
+ if (onBack == null) {
+ Row(Modifier.padding(top = Spacing.INSIDE.dp, bottom = 4.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(title, Modifier.weight(1f).padding(start = 4.dp), style = TypeScale.TITLE.style(tokens().text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ trailing?.invoke()
+ }
+ return
+ }
+ Row(Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ TextButton(onClick = onBack) { Text(stringResource(R.string.action_back), maxLines = 1) }
+ Text(title, Modifier.weight(1f), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ trailing?.invoke()
+ }
+}
+
+/** A small heading above a card, the same on every screen. */
+@Composable
+fun SectionTitle(text: String) {
+ Text(
+ text, Modifier.padding(start = 4.dp, top = 4.dp),
+ style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, fontWeight = FontWeight.SemiBold,
+ maxLines = 1,
+ )
+}
+
+/** A setting with a switch at its end. */
+@Composable
+fun SettingSwitch(title: String, hint: String?, checked: Boolean, onChange: (Boolean) -> Unit) {
+ ListRow(title, hint = hint, trailing = { CoucouSwitch(checked, onChange, label = title) })
+}
+
+/** A row that opens another page: its title and a chevron. */
+@Composable
+private fun LinkRow(title: String, onClick: () -> Unit) {
+ ListRow(title, onClick = onClick, trailing = { CoucouIcon(IconKind.CHEVRON, tint = tokens().textDim.c(), size = 20.dp) })
+}
+
+private fun clock(min: Int) = "%02d:%02d".format(QuietHours.wrap(min) / 60, QuietHours.wrap(min) % 60)
+
+/** A round 48 dp "−" or "+" button for stepping a time. */
+@Composable
+private fun StepButton(text: String, description: String, enabled: Boolean, onClick: () -> Unit) {
+ Box(
+ Modifier.alpha(if (enabled) 1f else 0.4f).size(Spacing.MIN_TOUCH.dp).clip(CircleShape).background(tokens().secondaryButton.c())
+ .clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = description },
+ contentAlignment = Alignment.Center,
+ ) { Text(text, style = TypeScale.HEADLINE.style(tokens().text.c())) }
+}
+
+@Composable
+private fun TimeRow(label: String, minutes: Int, enabled: Boolean, onChange: (Int) -> Unit) {
+ val t = tokens()
+ Row(
+ Modifier.fillMaxWidth().padding(horizontal = Spacing.INSIDE.dp, vertical = 4.dp).alpha(if (enabled) 1f else 0.5f),
+ horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(label, Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()))
+ StepButton("−", "$label, ${QuietHours.STEP} minutes earlier", enabled) { onChange(minutes - QuietHours.STEP) }
+ Text(clock(minutes), Modifier.width(56.dp), style = TypeScale.BODY.style(t.text.c()).copy(fontFamily = FontFamily.Monospace), maxLines = 1)
+ StepButton("+", "$label, ${QuietHours.STEP} minutes later", enabled) { onChange(minutes + QuietHours.STEP) }
+ }
+}
+
+/** Room under a list so its last row can scroll above the floating bar (64 + 16 gap + 16 margin). */
+val BarClearance = 96.dp
+
+/**
+ * Settings, a tab. Grouped, each group one panel: your computer (with Disconnect at the bottom, away
+ * from the everyday switches), the island, sound, notices, more, and About (Louis Raillé's required notice).
+ */
+@Composable
+fun SettingsScreen(model: AppModel, onHistory: () -> Unit, onGallery: () -> Unit, onWardrobe: () -> Unit, onOverlay: (Boolean) -> Unit, onDiagnostics: () -> Unit, onLicences: () -> Unit) {
+ val s = model.settings
+ val uri = LocalUriHandler.current
+ val t = tokens()
+ LazyColumn(
+ Modifier.padding(horizontal = Gutter), contentPadding = PaddingValues(bottom = BarClearance),
+ verticalArrangement = Arrangement.spacedBy(Gap),
+ ) {
+ item { ScreenTitle(stringResource(R.string.settings_title), null) }
+
+ item { SectionHeading(stringResource(R.string.settings_section_computer)) }
+ item {
+ Panel {
+ Row(Modifier.padding(Spacing.INSIDE.dp), horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.CenterVertically) {
+ StateDot(linkDotColor(model))
+ Text(linkStatusText(model), Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ when (model.mode) {
+ Mode.PAIRED -> {
+ RowDivider()
+ LinkRow(stringResource(R.string.diag_title), onDiagnostics)
+ RowDivider()
+ PillButton(stringResource(R.string.action_unpair), { model.unpair() }, Modifier.fillMaxWidth().padding(Spacing.INSIDE.dp), PillKind.DANGER)
+ }
+ Mode.DEMO -> {
+ RowDivider()
+ PillButton(stringResource(R.string.demo_leave), { model.stopDemo() }, Modifier.fillMaxWidth().padding(Spacing.INSIDE.dp))
+ }
+ Mode.NONE -> Text(
+ stringResource(R.string.settings_computer_none), Modifier.padding(start = Spacing.INSIDE.dp, end = Spacing.INSIDE.dp, bottom = Spacing.INSIDE.dp),
+ style = TypeScale.SECONDARY.style(t.textDim.c()),
+ )
+ }
+ }
+ }
+
+ if (model.mode == Mode.PAIRED) {
+ item { SectionHeading(stringResource(R.string.settings_section_away)) }
+ item { RelayCard(model) }
+ }
+
+ if (model.batteryHintVisible) item { BatteryCard(model) }
+
+ item { SectionHeading(stringResource(R.string.settings_section_display)) }
+ item { Panel { SettingSwitch(stringResource(R.string.overlay_title), stringResource(R.string.overlay_hint), model.overlayOn, onOverlay) } }
+
+ item { SectionHeading(stringResource(R.string.settings_section_sound)) }
+ item {
+ Panel {
+ SettingSwitch(stringResource(R.string.settings_sound), null, s.soundOn) { model.updateSettings(s.copy(soundOn = it)) }
+ RowDivider()
+ Column(Modifier.padding(horizontal = Spacing.INSIDE.dp, vertical = 8.dp)) {
+ Row {
+ Text(stringResource(R.string.settings_volume), Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()))
+ Text("${(s.volume / SoundVolume.MAX * 100).toInt().coerceIn(0, 100)}%", style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ CoucouSlider(
+ value = s.volume, onChange = { model.updateSettings(s.copy(volume = SoundVolume.clamp(it))) },
+ valueRange = 0f..SoundVolume.MAX, enabled = s.soundOn, label = stringResource(R.string.settings_volume),
+ )
+ }
+ }
+ }
+
+ item { SectionHeading(stringResource(R.string.settings_section_notices)) }
+ item {
+ Panel {
+ SettingSwitch(stringResource(R.string.notify_done), stringResource(R.string.notify_done_hint), s.notifyDone) {
+ model.updateSettings(s.copy(notifyDone = it))
+ }
+ RowDivider()
+ SettingSwitch(stringResource(R.string.quiet_hours), stringResource(R.string.quiet_hint), s.quiet.enabled) {
+ model.updateSettings(s.copy(quiet = s.quiet.copy(enabled = it)))
+ }
+ TimeRow(stringResource(R.string.quiet_from), s.quiet.fromMin, s.quiet.enabled) {
+ model.updateSettings(s.copy(quiet = s.quiet.copy(fromMin = QuietHours.wrap(it))))
+ }
+ TimeRow(stringResource(R.string.quiet_to), s.quiet.toMin, s.quiet.enabled) {
+ model.updateSettings(s.copy(quiet = s.quiet.copy(toMin = QuietHours.wrap(it))))
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+ }
+
+ item { SectionHeading(stringResource(R.string.settings_section_more)) }
+ item {
+ Panel {
+ LinkRow(stringResource(R.string.history_title), onHistory)
+ RowDivider()
+ LinkRow(stringResource(R.string.wardrobe_title), onWardrobe)
+ RowDivider()
+ LinkRow(stringResource(R.string.gallery), onGallery)
+ }
+ }
+
+ // Required by Louis Raillé's permission: visible, one tap from Home.
+ item { SectionHeading(stringResource(R.string.settings_section_about)) }
+ item {
+ Panel {
+ Column(Modifier.padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(stringResource(R.string.about_unofficial), style = TypeScale.BODY.style(t.text.c()))
+ Text(
+ stringResource(R.string.about_repo),
+ Modifier.clickable(role = Role.Button) { runCatching { uri.openUri(Attribution.REPO_URL) } },
+ style = TypeScale.BODY.style(t.text.c()).copy(textDecoration = TextDecoration.Underline),
+ )
+ Text(stringResource(R.string.about_assets), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+ RowDivider()
+ LinkRow(stringResource(R.string.licences_title), onLicences)
+ }
+ }
+ item { Spacer(Modifier.height(Gutter)) }
+ }
+}
+
+/**
+ * What you allowed or denied, in sentences (never the command or a path), grouped by day. Kept only on the
+ * phone. The same list as Home's "Recent", in full.
+ */
+@Composable
+fun HistoryScreen(model: AppModel, onBack: () -> Unit) {
+ val zone = remember { ZoneId.systemDefault() }
+ val now = System.currentTimeMillis()
+ val groups = HistoryDays.group(model.decisions, now, zone)
+ val dateFormat = remember { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) }
+ val timeFormat = remember { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) }
+ val t = tokens()
+ LazyColumn(Modifier.padding(horizontal = Gutter), verticalArrangement = Arrangement.spacedBy(Gap)) {
+ item { ScreenTitle(stringResource(R.string.history_title), onBack) }
+ item { Text(stringResource(R.string.history_note), Modifier.padding(horizontal = 4.dp), style = TypeScale.SECONDARY.style(t.textDim.c())) }
+ if (groups.isEmpty()) {
+ item { Panel { Text(stringResource(R.string.history_empty), Modifier.padding(Gutter), style = TypeScale.BODY.style(t.textDim.c())) } }
+ }
+ for ((key, list) in groups) {
+ val (day, date) = key
+ item {
+ SectionHeading(
+ when (day) {
+ HistoryDays.Day.TODAY -> stringResource(R.string.history_today)
+ HistoryDays.Day.YESTERDAY -> stringResource(R.string.history_yesterday)
+ HistoryDays.Day.OTHER -> dateFormat.format(date)
+ },
+ )
+ }
+ item {
+ Panel {
+ list.forEachIndexed { i, d ->
+ if (i > 0) RowDivider()
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = Spacing.INSIDE.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(Spacing.GAP.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ StateDot(if (d.allowed) StatusColors.online else t.danger.c())
+ Text(HomeText.decision(d.allowed, d.agent, d.tool), Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()), maxLines = 2, overflow = TextOverflow.Ellipsis)
+ Text(
+ timeFormat.format(java.time.Instant.ofEpochMilli(d.atMs).atZone(zone).toLocalTime()),
+ style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1,
+ )
+ }
+ }
+ }
+ }
+ }
+ if (groups.isNotEmpty()) {
+ item { PillButton(stringResource(R.string.history_clear), { model.clearDecisions() }, Modifier.fillMaxWidth(), PillKind.DANGER) }
+ }
+ item { Spacer(Modifier.height(Gutter)) }
+ }
+}
+
+/**
+ * "Away from home Wi-Fi": whether this phone also reaches the computer through the relay, and which way it is connected
+ * right now. The switch is shown only when the pairing includes a relay (the computer's switch was on when it was paired).
+ */
+@Composable
+private fun RelayCard(model: AppModel) {
+ val t = tokens()
+ val s = model.settings
+ val kind = RelayStatus.kind(model.hasRelay, s.useRelay, model.linkState == LinkState.CONNECTED, model.route, model.relayIssue)
+ val line = when (kind) {
+ RelayLineKind.NO_RELAY_IN_PAIRING -> stringResource(R.string.relay_line_none)
+ RelayLineKind.SWITCHED_OFF -> stringResource(R.string.relay_line_off)
+ RelayLineKind.DIRECT -> stringResource(R.string.relay_line_direct)
+ RelayLineKind.VIA_RELAY -> stringResource(R.string.relay_line_via, model.relayHost.orEmpty())
+ RelayLineKind.WAITING -> stringResource(R.string.relay_line_waiting)
+ RelayLineKind.ACCESS_REFUSED -> stringResource(R.string.relay_line_access)
+ RelayLineKind.ROOM_TAKEN -> stringResource(R.string.relay_line_taken)
+ RelayLineKind.RATE_LIMITED -> stringResource(R.string.relay_line_rate)
+ RelayLineKind.UNREACHABLE -> stringResource(R.string.relay_line_unreachable)
+ RelayLineKind.COMPUTER_AWAY -> stringResource(R.string.relay_line_away)
+ }
+ Panel {
+ if (model.hasRelay) {
+ SettingSwitch(stringResource(R.string.relay_use), stringResource(R.string.relay_use_hint), s.useRelay) {
+ model.updateSettings(s.copy(useRelay = it))
+ }
+ RowDivider()
+ }
+ Text(line, Modifier.padding(Spacing.INSIDE.dp), style = TypeScale.SECONDARY.style(t.textDim.c()))
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/Sheets.kt b/android/app/src/main/kotlin/com/coucou/android/ui/Sheets.kt
new file mode 100644
index 00000000..42fc2501
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/Sheets.kt
@@ -0,0 +1,273 @@
+package com.coucou.android.ui
+
+import android.os.SystemClock
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.slideInVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.ApprovalSheetPlan
+import com.coucou.android.core.HomePanel
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.MotionSpec
+import com.coucou.android.core.Pills
+import com.coucou.android.core.QuestionFlow
+import com.coucou.android.link.AskedOption
+import com.coucou.android.link.QuestionRequest
+import com.coucou.android.core.Radii
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.MochiConst
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+import kotlinx.coroutines.delay
+
+/**
+ * A panel that rises from the bottom over whatever is on screen, with a dim scrim behind it. It is black in
+ * both themes, like the island it comes from. Tapping the scrim or pressing Back closes it; taps on the
+ * panel itself never reach the scrim.
+ */
+@Composable
+fun BottomSheetHost(onDismiss: () -> Unit, wash: Color? = null, content: @Composable ColumnScope.() -> Unit) {
+ BackHandler(onBack = onDismiss)
+ var shown by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) { shown = true }
+ val shape = RoundedCornerShape(topStart = Radii.SHEET.dp, topEnd = Radii.SHEET.dp)
+ Box(Modifier.fillMaxSize()) {
+ Box(
+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss),
+ )
+ AnimatedVisibility(
+ visible = shown, modifier = Modifier.align(Alignment.BottomCenter),
+ enter = if (reducedMotion()) fadeIn(tween(MotionSpec.REDUCED_MS)) else slideInVertically(spring(dampingRatio = 0.72f, stiffness = 400f)) { it } + fadeIn(),
+ ) {
+ Column(
+ Modifier.fillMaxWidth().clip(shape).background(Color(IslandSurface.PANEL)).border(1.dp, Color.White.copy(alpha = 0.08f), shape)
+ .then(if (wash != null) Modifier.drawBehind { drawWash(wash, 0.45f) } else Modifier)
+ .pointerInput(Unit) { detectTapGestures { } }
+ .padding(start = 20.dp, end = 20.dp, top = 10.dp, bottom = 20.dp),
+ content = {
+ Box(Modifier.align(Alignment.CenterHorizontally).size(width = 36.dp, height = 4.dp).clip(RoundedCornerShape(2.dp)).background(Color.White.copy(alpha = 0.2f)))
+ Box(Modifier.size(14.dp))
+ content()
+ },
+ )
+ }
+ }
+}
+
+/** The colour of an agent for its Mochi: the user's choice on the computer, else the catalog's, else none. */
+private fun agentColour(model: AppModel, pillId: String) =
+ (model.sessions.firstOrNull { it.pillId == pillId }?.let { HomePanel.colorHex(it) } ?: Pills.byId(pillId)?.colorHex)?.let { HomePanel.rgb(it) }
+
+@Composable
+private fun SheetMochi(state: BotState, colour: com.coucou.android.mochi.Rgb?) {
+ val engine = remember { MochiEngine({ SystemClock.elapsedRealtimeNanos() / 1e6 }).apply { setState(state, force = true) } }
+ engine.bodyColor = colour
+ MochiView(engine, Modifier.size(84.dp))
+}
+
+/**
+ * A request for permission, in words: who, and what kind of action ("Wants to run a command"). The exact command is one tap
+ * away ("Show exact command") and is always repeated by the lock prompt, so Allow is never blind. Allow needs the lock;
+ * Deny does not. Taps in the first 600 ms are ignored.
+ */
+@Composable
+fun ApprovalSheet(model: AppModel, r: ApprovalRequest, onAllow: (ApprovalRequest) -> Unit, onDismiss: () -> Unit) {
+ var armed by remember(r.fingerprint) { mutableStateOf(false) }
+ LaunchedEffect(r.fingerprint) { delay(ApprovalSheetPlan.GUARD_MS); armed = true }
+ var showCommand by remember(r.fingerprint) { mutableStateOf(false) }
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ val wash = MochiConst.STATES[BotState.APPROVAL]?.color?.let(::rgbColor)
+ val name = model.agentName(r.pillId)
+ val kind = Pills.byId(r.pillId)?.name.orEmpty()
+ BottomSheetHost(onDismiss, wash) {
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically) {
+ SheetMochi(BotState.APPROVAL, agentColour(model, r.pillId))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(if (kind.isNotBlank() && kind != name) "$name · $kind" else name, style = TypeScale.SECONDARY.style(dim), maxLines = 1)
+ Text(stringResource(R.string.approval_wants, ApprovalSheetPlan.action(r.tool)), style = TypeScale.TITLE.style(white), maxLines = 3)
+ }
+ }
+ Text(stringResource(R.string.approval_caution), Modifier.padding(top = 12.dp), style = TypeScale.SECONDARY.style(dim))
+ Text(
+ stringResource(if (showCommand) R.string.approval_hide_cmd else R.string.approval_show_cmd),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button) { showCommand = !showCommand }.padding(vertical = 12.dp),
+ style = TypeScale.SECONDARY.style(dim).copy(textDecoration = TextDecoration.Underline),
+ )
+ if (showCommand) {
+ Column(
+ Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(Color.White.copy(alpha = 0.07f)).padding(12.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ Text(r.tool, style = TypeScale.LABEL.style(dim), maxLines = 1)
+ // The whole command that was sent, scrollable: never cut by a line limit.
+ Column(Modifier.heightIn(max = ApprovalSheetPlan.COMMAND_BOX_MAX_DP.dp).verticalScroll(rememberScrollState())) {
+ Text(r.command, style = TypeScale.MONO.style(white).copy(fontFamily = FontFamily.Monospace))
+ }
+ }
+ Box(Modifier.size(8.dp))
+ }
+ val canAllow = ApprovalSheetPlan.canAllowHere(r)
+ if (!canAllow) {
+ // Shown without a tap: the user must know the command is not all here before reading anything else.
+ Text(stringResource(R.string.approval_too_long), Modifier.padding(bottom = 4.dp), style = TypeScale.TITLE.style(white))
+ Text(stringResource(R.string.approval_on_computer), Modifier.padding(bottom = 10.dp), style = TypeScale.SECONDARY.style(dim))
+ }
+ Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ PillButton(stringResource(R.string.action_deny), { model.decide(r.fingerprint, allow = false) }, Modifier.weight(1f), onDark = true, enabled = armed)
+ if (canAllow) {
+ PillButton(
+ stringResource(R.string.action_allow), { onAllow(r) }, Modifier.weight(1f), PillKind.PRIMARY, enabled = armed, onDark = true,
+ icon = { CoucouIcon(IconKind.LOCK, tint = Color(IslandSurface.ON_PRIMARY), size = 18.dp) },
+ )
+ }
+ }
+ if (canAllow) Text(stringResource(R.string.approval_hint), Modifier.padding(top = 10.dp), style = TypeScale.LABEL.style(dim))
+ Text(
+ stringResource(R.string.approval_later),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button, onClick = onDismiss).padding(vertical = 14.dp),
+ style = TypeScale.SECONDARY.style(dim),
+ )
+ }
+}
+
+/**
+ * A question Claude Code asks. With the `answers` capability the options are here to tap, one question at a time, and the answer
+ * is sent only after the screen lock ([onSend]; the labels are the computer's exact ones, nothing typed ever goes in). Without it
+ * the sheet says whose question it is and where to answer.
+ */
+@Composable
+fun QuestionSheet(model: AppModel, pillId: String, onDismiss: () -> Unit, onSend: (QuestionRequest, List<List<String>>) -> Unit) {
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ val wash = MochiConst.STATES[BotState.QUESTION]?.color?.let(::rgbColor)
+ val request = model.questionFor(pillId)
+ BottomSheetHost(onDismiss, wash) {
+ if (request == null) {
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically) {
+ SheetMochi(BotState.QUESTION, agentColour(model, pillId))
+ Text(stringResource(R.string.question_title, model.agentName(pillId)), Modifier.weight(1f), style = TypeScale.TITLE.style(white), maxLines = 3)
+ }
+ Text(stringResource(R.string.question_body), Modifier.padding(top = 12.dp, bottom = 16.dp), style = TypeScale.BODY.style(dim))
+ PillButton(stringResource(R.string.question_ok), onDismiss, Modifier.fillMaxWidth(), PillKind.PRIMARY, onDark = true)
+ return@BottomSheetHost
+ }
+ var st by remember(request.fingerprint) { mutableStateOf(QuestionFlow.start(request.questions)) }
+ var armed by remember(request.fingerprint) { mutableStateOf(false) }
+ LaunchedEffect(request.fingerprint) { delay(ApprovalSheetPlan.GUARD_MS); armed = true }
+ val q = request.questions[st.index.coerceIn(0, request.questions.lastIndex)]
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically) {
+ SheetMochi(BotState.QUESTION, agentColour(model, pillId))
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(stringResource(R.string.question_title, model.agentName(pillId)), style = TypeScale.SECONDARY.style(dim), maxLines = 2)
+ QuestionFlow.position(request.questions, st)?.let { (n, total) ->
+ Text(stringResource(R.string.question_position, n, total), style = TypeScale.LABEL.style(dim))
+ }
+ }
+ }
+ Text(q.question, Modifier.padding(top = 12.dp), style = TypeScale.HEADLINE.style(white))
+ if (q.multiSelect) Text(stringResource(R.string.question_pick_many), Modifier.padding(top = 2.dp), style = TypeScale.SECONDARY.style(dim))
+ Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (o in q.options) {
+ OptionRow(o, selected = o.label in st.picks[st.index], multi = q.multiSelect) { st = QuestionFlow.toggle(request.questions, st, o.label) }
+ }
+ }
+ Row(Modifier.fillMaxWidth().padding(top = 16.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ if (st.index > 0) PillButton(stringResource(R.string.question_back), { st = QuestionFlow.back(st) }, Modifier.weight(1f), onDark = true)
+ if (QuestionFlow.isLast(request.questions, st)) {
+ PillButton(
+ stringResource(R.string.question_send),
+ { QuestionFlow.picks(request.questions, st)?.let { onSend(request, it) } }, Modifier.weight(1f), PillKind.PRIMARY,
+ enabled = armed && QuestionFlow.complete(request.questions, st), onDark = true,
+ icon = { CoucouIcon(IconKind.LOCK, tint = Color(IslandSurface.ON_PRIMARY), size = 18.dp) },
+ )
+ } else {
+ PillButton(
+ stringResource(R.string.question_next), { st = QuestionFlow.next(request.questions, st) }, Modifier.weight(1f), PillKind.PRIMARY,
+ enabled = QuestionFlow.canAdvance(request.questions, st), onDark = true,
+ )
+ }
+ }
+ Text(stringResource(R.string.approval_hint), Modifier.padding(top = 10.dp), style = TypeScale.LABEL.style(dim))
+ Text(
+ stringResource(R.string.approval_later),
+ Modifier.heightIn(min = Spacing.MIN_TOUCH.dp).clickable(role = Role.Button, onClick = onDismiss).padding(vertical = 14.dp),
+ style = TypeScale.SECONDARY.style(dim),
+ )
+ }
+}
+
+/** One option: a label, its description, and a mark that it is picked. Tapping it is the only way to answer. */
+@Composable
+private fun OptionRow(option: AskedOption, selected: Boolean, multi: Boolean, onClick: () -> Unit) {
+ val white = Color(IslandSurface.TEXT)
+ val dim = Color(IslandSurface.TEXT_DIM)
+ val shape = RoundedCornerShape(16.dp)
+ Row(
+ Modifier.fillMaxWidth().heightIn(min = Spacing.MIN_TOUCH.dp).clip(shape)
+ .background(Color.White.copy(alpha = if (selected) 0.16f else 0.07f))
+ .border(1.dp, if (selected) white.copy(alpha = 0.7f) else Color.Transparent, shape)
+ .selectable(selected = selected, role = if (multi) Role.Checkbox else Role.RadioButton, onClick = onClick)
+ .padding(horizontal = 14.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Box(
+ Modifier.size(22.dp).clip(if (multi) RoundedCornerShape(6.dp) else CircleShape)
+ .background(if (selected) white else Color.Transparent)
+ .border(1.5.dp, if (selected) white else dim, if (multi) RoundedCornerShape(6.dp) else CircleShape),
+ contentAlignment = Alignment.Center,
+ ) { if (selected) CoucouIcon(IconKind.CHECK, tint = Color(IslandSurface.ON_PRIMARY), size = 16.dp) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(option.label, style = TypeScale.BODY.style(white).copy(fontWeight = FontWeight.SemiBold))
+ if (option.description.isNotBlank()) Text(option.description, style = TypeScale.SECONDARY.style(dim))
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/Theme.kt b/android/app/src/main/kotlin/com/coucou/android/ui/Theme.kt
new file mode 100644
index 00000000..9cb71837
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/Theme.kt
@@ -0,0 +1,51 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.ColorScheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.unit.dp
+import com.coucou.android.core.Palette
+import com.coucou.android.core.StatusPalette
+import com.coucou.android.core.Tokens
+
+/**
+ * The look of the Coucou website (docs/site.css): near-black page, slightly lighter cards with a thin
+ * border, soft blue accent, rounded corners and pill-shaped buttons. Mochi itself is untouched.
+ */
+private fun scheme(p: Palette, t: Tokens): ColorScheme {
+ // Surfaces and text come from the tokens, the accent from Palette.
+ return darkColorScheme().copy(
+ background = Color(t.bg), surface = Color(t.bg),
+ surfaceVariant = Color(t.panel), surfaceContainer = Color(t.panel),
+ onBackground = Color(t.text), onSurface = Color(t.text), onSurfaceVariant = Color(t.textDim),
+ outline = Color(t.line), outlineVariant = Color(t.line),
+ primary = Color(p.accent), onPrimary = Color(p.onAccent), error = Color(p.error),
+ )
+}
+
+private val Dark = scheme(Palette.DARK, Tokens.DARK)
+
+/** Link status colours (the dot next to "Connected"). */
+object StatusColors {
+ val online = Color(StatusPalette.ONLINE)
+ val busy = Color(StatusPalette.BUSY)
+ val offline = Color(StatusPalette.OFFLINE)
+}
+
+@Composable
+fun CoucouTheme(content: @Composable () -> Unit) {
+ CompositionLocalProvider(LocalTokens provides Tokens.DARK) {
+ MaterialTheme(colorScheme = Dark, content = content)
+ }
+}
+
+/** The gutter at the side of every screen, and the gap between cards (one rhythm everywhere). */
+val Gutter = 16.dp
+val Gap = 12.dp
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/UsagePanel.kt b/android/app/src/main/kotlin/com/coucou/android/ui/UsagePanel.kt
new file mode 100644
index 00000000..5e5adb13
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/UsagePanel.kt
@@ -0,0 +1,90 @@
+package com.coucou.android.ui
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.core.PlanText
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.link.PlanUsage
+import com.coucou.android.link.PlanWindow
+import com.coucou.android.link.UsageSnapshot
+
+/**
+ * How much of the Claude and Codex plans is used and when they reset, as the PC's pills show it. Only what the
+ * computer sent (its switch is on); nothing here asks for more. Each bar also says its percentage in words.
+ */
+@Composable
+fun UsagePanel(usage: UsageSnapshot?, nowMs: Long = System.currentTimeMillis()) {
+ if (usage == null || (usage.claude == null && usage.codex == null)) return
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ SectionHeading(stringResource(R.string.usage_title))
+ Panel {
+ var first = true
+ usage.claude?.let { PlanBlock(stringResource(R.string.usage_claude), it, nowMs); first = false }
+ usage.codex?.let {
+ if (!first) RowDivider()
+ PlanBlock(stringResource(R.string.usage_codex), it, nowMs)
+ }
+ }
+ }
+}
+
+@Composable
+private fun PlanBlock(name: String, plan: PlanUsage, nowMs: Long) {
+ val t = tokens()
+ Column(Modifier.fillMaxWidth().padding(Spacing.INSIDE.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(name, Modifier.weight(1f), style = TypeScale.HEADLINE.style(t.text.c()))
+ plan.plan?.let { Text(it, style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1) }
+ }
+ plan.fiveHour?.let { WindowBar(name, stringResource(R.string.usage_five_hours), it, nowMs, weekly = false) }
+ plan.sevenDay?.let { WindowBar(name, stringResource(R.string.usage_week), it, nowMs, weekly = true) }
+ plan.resetCredits?.takeIf { it > 0 }?.let { Text(stringResource(R.string.usage_credits, it), style = TypeScale.SECONDARY.style(t.textDim.c())) }
+ }
+}
+
+@Composable
+private fun WindowBar(plan: String, label: String, w: PlanWindow, nowMs: Long, weekly: Boolean) {
+ val t = tokens()
+ val pct = PlanText.effectivePct(w, nowMs)
+ val color = when (PlanText.level(pct)) {
+ PlanText.Level.LOW -> StatusColors.online
+ PlanText.Level.MEDIUM -> StatusColors.busy
+ PlanText.Level.HIGH -> t.danger.c()
+ }
+ val reset = if (weekly && w.resetsAtMs > nowMs) stringResource(R.string.usage_resets_week, PlanText.weekday(w))
+ else when (val r = PlanText.resetsIn(w, nowMs)) {
+ PlanText.Reset.Now -> stringResource(R.string.usage_resets_now)
+ is PlanText.Reset.InHoursMinutes -> stringResource(R.string.usage_resets_hm, r.h, r.m)
+ is PlanText.Reset.InMinutes -> stringResource(R.string.usage_resets_m, r.m)
+ }
+ val spoken = stringResource(R.string.usage_desc, plan, label, pct)
+ Column(Modifier.semantics(mergeDescendants = true) { contentDescription = "$spoken. $reset" }, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(Modifier.clearAndSetSemantics { }, verticalAlignment = Alignment.CenterVertically) {
+ Text(label, Modifier.weight(1f), style = TypeScale.BODY.style(t.text.c()))
+ Text(stringResource(R.string.usage_pct, pct), style = TypeScale.BODY.style(t.text.c()), maxLines = 1)
+ }
+ Box(Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)).background(t.secondaryButton.c()).clearAndSetSemantics { }) {
+ Box(Modifier.fillMaxWidth(pct / 100f).height(8.dp).clip(RoundedCornerShape(4.dp)).background(color))
+ }
+ Text(reset, Modifier.clearAndSetSemantics { }, style = TypeScale.SECONDARY.style(t.textDim.c()), maxLines = 1)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/coucou/android/ui/WardrobeScreen.kt b/android/app/src/main/kotlin/com/coucou/android/ui/WardrobeScreen.kt
new file mode 100644
index 00000000..bde7db09
--- /dev/null
+++ b/android/app/src/main/kotlin/com/coucou/android/ui/WardrobeScreen.kt
@@ -0,0 +1,187 @@
+package com.coucou.android.ui
+
+import android.os.SystemClock
+import androidx.annotation.StringRes
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.ui.draw.clip
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.role
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.coucou.android.R
+import com.coucou.android.app.AppModel
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.Radii
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.TypeScale
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiView
+import com.coucou.android.mochi.outfit.ComposeGfx
+import com.coucou.android.mochi.outfit.Ctx2D
+import com.coucou.android.mochi.outfit.Outfit
+import com.coucou.android.mochi.outfit.Wardrobe
+import com.coucou.android.mochi.outfit.drawIconMochi
+import java.time.LocalDate
+
+/** The name of a wardrobe value, in the app's words. */
+@StringRes
+fun outfitLabelRes(id: String): Int = when (id) {
+ "auto" -> R.string.outfit_auto
+ "none" -> R.string.outfit_none
+ "partyHat" -> R.string.outfit_partyHat
+ "beanie" -> R.string.outfit_beanie
+ "crown" -> R.string.outfit_crown
+ "sunglasses" -> R.string.outfit_sunglasses
+ "roundGlasses" -> R.string.outfit_roundGlasses
+ "bow" -> R.string.outfit_bow
+ "scarf" -> R.string.outfit_scarf
+ "witchHat" -> R.string.outfit_witchHat
+ "pumpkin" -> R.string.outfit_pumpkin
+ "santaHat" -> R.string.outfit_santaHat
+ else -> R.string.outfit_bunnyEars
+}
+
+/** A little Mochi wearing [outfit], the PC's wardrobe icon (drawn by the same code as the big one). */
+@Composable
+fun OutfitIcon(outfit: Outfit, size: Dp, modifier: Modifier = Modifier) {
+ Canvas(modifier.size(size)) {
+ drawIntoCanvas { c ->
+ c.save()
+ val k = this.size.width / 40f
+ c.scale(k, k)
+ drawIconMochi(Ctx2D(ComposeGfx(c, Rect(0f, 0f, 40f, 40f))), 40.0, outfit)
+ c.restore()
+ }
+ }
+}
+
+/** "None": a crossed-out circle, like the PC's. */
+@Composable
+private fun NoOutfitIcon(size: Dp) {
+ val color = tokens().textDim.c()
+ Canvas(Modifier.size(size)) {
+ val r = this.size.width * 0.26f
+ val c = Offset(this.size.width / 2, this.size.height / 2)
+ val stroke = Stroke(width = this.size.width * 0.035f, cap = StrokeCap.Round)
+ drawCircle(color, r, c, style = stroke)
+ drawLine(color, Offset(c.x - r * 0.68f, c.y + r * 0.68f), Offset(c.x + r * 0.68f, c.y - r * 0.68f), strokeWidth = stroke.width, cap = StrokeCap.Round)
+ }
+}
+
+/**
+ * Settings > Mochi's wardrobe: what Mochi wears on this phone. Either the same as on the computer (the default),
+ * or one of the PC's thirteen choices ("Auto" follows the seasons on this phone's calendar). A preview on top.
+ */
+@Composable
+fun WardrobeScreen(model: AppModel, onBack: () -> Unit) {
+ val t = tokens()
+ val s = model.settings
+ val clock = remember { { SystemClock.elapsedRealtimeNanos() / 1e6 } }
+ val preview = remember { MochiEngine(clock) }
+ val worn = model.dress()
+ val first = remember { androidx.compose.runtime.mutableStateOf(true) }
+ LaunchedEffect(worn) {
+ preview.setOutfit(worn, animated = !first.value)
+ first.value = false
+ }
+ val following = s.outfit == Wardrobe.FOLLOW
+ val today = LocalDate.now()
+ val seasonal = Wardrobe.seasonal(today)
+ LazyColumn(Modifier.padding(horizontal = Gutter), contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = BarClearance), verticalArrangement = Arrangement.spacedBy(Gap)) {
+ item { ScreenTitle(stringResource(R.string.wardrobe_title), onBack) }
+ item {
+ Panel {
+ Column(Modifier.fillMaxWidth().padding(Spacing.INSIDE.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ MochiView(preview, Modifier.size(120.dp))
+ Text(stringResource(outfitLabelRes(model.outfitSelection)), style = TypeScale.TITLE.style(t.text.c()), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(stringResource(R.string.wardrobe_note), style = TypeScale.SECONDARY.style(t.textDim.c()), textAlign = TextAlign.Center)
+ }
+ }
+ }
+ item {
+ Panel {
+ ListRow(
+ stringResource(R.string.wardrobe_follow), hint = stringResource(R.string.wardrobe_follow_hint),
+ modifier = Modifier.clickable(role = Role.RadioButton) { model.updateSettings(s.copy(outfit = Wardrobe.FOLLOW)) }
+ .semantics { selected = following },
+ trailing = { if (following) CoucouIcon(IconKind.CHECK, tint = t.online.c(), size = 22.dp) },
+ )
+ }
+ }
+ items(Wardrobe.SELECTIONS.chunked(3)) { row ->
+ Row(horizontalArrangement = Arrangement.spacedBy(Gap), modifier = Modifier.fillMaxWidth()) {
+ for (id in row) {
+ val chosen = !following && s.outfit == id
+ val label = stringResource(outfitLabelRes(id))
+ Box(Modifier.weight(1f)) {
+ OutfitCell(label, chosen, onClick = { model.updateSettings(s.copy(outfit = id)) }) {
+ when (id) {
+ "none" -> NoOutfitIcon(56.dp)
+ "auto" -> Box(contentAlignment = Alignment.BottomCenter) {
+ OutfitIcon(seasonal, 56.dp)
+ Text(
+ stringResource(R.string.wardrobe_auto_tag), Modifier.background(androidx.compose.ui.graphics.Color(0x99000000), RoundedCornerShape(50)).padding(horizontal = 6.dp, vertical = 1.dp),
+ style = TypeScale.LABEL.style(androidx.compose.ui.graphics.Color.White), maxLines = 1,
+ )
+ }
+ else -> OutfitIcon(Wardrobe.outfitOf(id), 56.dp)
+ }
+ }
+ }
+ }
+ // A short last row keeps its cells the same width as the others.
+ repeat(3 - row.size) { Spacer(Modifier.weight(1f)) }
+ }
+ }
+ item { Spacer(Modifier.height(Gutter)) }
+ }
+}
+
+@Composable
+private fun OutfitCell(label: String, chosen: Boolean, onClick: () -> Unit, icon: @Composable () -> Unit) {
+ val t = tokens()
+ val shape = RoundedCornerShape(Radii.PANEL.dp)
+ val selectedText = stringResource(R.string.wardrobe_selected)
+ Column(
+ Modifier.fillMaxWidth().clip(shape).background(t.panel.c()).border(if (chosen) 2.dp else 1.dp, if (chosen) t.text.c() else t.line.c(), shape)
+ .clickable(role = Role.RadioButton, onClick = onClick)
+ .semantics { selected = chosen; contentDescription = if (chosen) "$label, $selectedText" else label }
+ .padding(vertical = 12.dp, horizontal = 4.dp),
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ icon()
+ Text(label, style = TypeScale.LABEL.style(t.text.c()), maxLines = 2, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis)
+ }
+}
diff --git a/android/app/src/main/res/drawable/ic_stat_mochi.xml b/android/app/src/main/res/drawable/ic_stat_mochi.xml
new file mode 100644
index 00000000..6bb59d3c
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_stat_mochi.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- One-colour Mochi for the status bar: a rounded blob with two eyes cut out. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FFFFFFFF" android:fillType="evenOdd"
+ android:pathData="M12,4.5C6.2,4.5 2.5,7.4 2.5,12.2C2.5,17 6.2,19.5 12,19.5C17.8,19.5 21.5,17 21.5,12.2C21.5,7.4 17.8,4.5 12,4.5ZM8.2,10.2C7.6,10.2 7.2,10.7 7.2,11.3L7.2,12.7C7.2,13.3 7.6,13.8 8.2,13.8C8.8,13.8 9.2,13.3 9.2,12.7L9.2,11.3C9.2,10.7 8.8,10.2 8.2,10.2ZM15.8,10.2C15.2,10.2 14.8,10.7 14.8,11.3L14.8,12.7C14.8,13.3 15.2,13.8 15.8,13.8C16.4,13.8 16.8,13.3 16.8,12.7L16.8,11.3C16.8,10.7 16.4,10.2 15.8,10.2Z" />
+</vector>
diff --git a/android/app/src/main/res/drawable/widget_bg.xml b/android/app/src/main/res/drawable/widget_bg.xml
new file mode 100644
index 00000000..8e68d251
--- /dev/null
+++ b/android/app/src/main/res/drawable/widget_bg.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#F21C1C1E" />
+ <corners android:radius="22dp" />
+</shape>
diff --git a/android/app/src/main/res/layout/widget_glance.xml b/android/app/src/main/res/layout/widget_glance.xml
new file mode 100644
index 00000000..10504118
--- /dev/null
+++ b/android/app/src/main/res/layout/widget_glance.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The home-screen widget: a dot for the tone, the headline, one detail line and up to four agents. Plain RemoteViews, no library. -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/widget_root"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@drawable/widget_bg"
+ android:orientation="vertical"
+ android:padding="14dp">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/widget_dot"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="●"
+ android:textSize="14sp" />
+
+ <TextView
+ android:id="@+id/widget_headline"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:layout_weight="1"
+ android:maxLines="1"
+ android:ellipsize="end"
+ android:textColor="#FFFFFFFF"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/widget_detail"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="2dp"
+ android:maxLines="1"
+ android:ellipsize="end"
+ android:textColor="#FFAEAEB2"
+ android:textSize="12sp" />
+
+ <TextView
+ android:id="@+id/widget_lines"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:maxLines="4"
+ android:ellipsize="end"
+ android:lineSpacingExtra="2dp"
+ android:textColor="#FFE5E5EA"
+ android:textSize="12sp" />
+</LinearLayout>
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 00000000..96b35fb8
Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/android/app/src/main/res/raw/annoyed.wav b/android/app/src/main/res/raw/annoyed.wav
new file mode 100644
index 00000000..04e7653f
Binary files /dev/null and b/android/app/src/main/res/raw/annoyed.wav differ
diff --git a/android/app/src/main/res/raw/approval.wav b/android/app/src/main/res/raw/approval.wav
new file mode 100644
index 00000000..df865d38
Binary files /dev/null and b/android/app/src/main/res/raw/approval.wav differ
diff --git a/android/app/src/main/res/raw/dizzy.wav b/android/app/src/main/res/raw/dizzy.wav
new file mode 100644
index 00000000..598b5d9b
Binary files /dev/null and b/android/app/src/main/res/raw/dizzy.wav differ
diff --git a/android/app/src/main/res/raw/error.wav b/android/app/src/main/res/raw/error.wav
new file mode 100644
index 00000000..89738c96
Binary files /dev/null and b/android/app/src/main/res/raw/error.wav differ
diff --git a/android/app/src/main/res/raw/finish.wav b/android/app/src/main/res/raw/finish.wav
new file mode 100644
index 00000000..c430e46c
Binary files /dev/null and b/android/app/src/main/res/raw/finish.wav differ
diff --git a/android/app/src/main/res/raw/greet.wav b/android/app/src/main/res/raw/greet.wav
new file mode 100644
index 00000000..7fa6d0c1
Binary files /dev/null and b/android/app/src/main/res/raw/greet.wav differ
diff --git a/android/app/src/main/res/raw/love.wav b/android/app/src/main/res/raw/love.wav
new file mode 100644
index 00000000..8c5b4740
Binary files /dev/null and b/android/app/src/main/res/raw/love.wav differ
diff --git a/android/app/src/main/res/raw/question.wav b/android/app/src/main/res/raw/question.wav
new file mode 100644
index 00000000..9b6e0251
Binary files /dev/null and b/android/app/src/main/res/raw/question.wav differ
diff --git a/android/app/src/main/res/raw/rate.wav b/android/app/src/main/res/raw/rate.wav
new file mode 100644
index 00000000..2a0cc03f
Binary files /dev/null and b/android/app/src/main/res/raw/rate.wav differ
diff --git a/android/app/src/main/res/raw/search.wav b/android/app/src/main/res/raw/search.wav
new file mode 100644
index 00000000..eac10791
Binary files /dev/null and b/android/app/src/main/res/raw/search.wav differ
diff --git a/android/app/src/main/res/raw/slap.wav b/android/app/src/main/res/raw/slap.wav
new file mode 100644
index 00000000..d82a676c
Binary files /dev/null and b/android/app/src/main/res/raw/slap.wav differ
diff --git a/android/app/src/main/res/raw/sleep.wav b/android/app/src/main/res/raw/sleep.wav
new file mode 100644
index 00000000..41453cca
Binary files /dev/null and b/android/app/src/main/res/raw/sleep.wav differ
diff --git a/android/app/src/main/res/raw/think.wav b/android/app/src/main/res/raw/think.wav
new file mode 100644
index 00000000..49c1dde9
Binary files /dev/null and b/android/app/src/main/res/raw/think.wav differ
diff --git a/android/app/src/main/res/raw/work.wav b/android/app/src/main/res/raw/work.wav
new file mode 100644
index 00000000..523ffc69
Binary files /dev/null and b/android/app/src/main/res/raw/work.wav differ
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
new file mode 100644
index 00000000..5a87c237
--- /dev/null
+++ b/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,256 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated by android/scripts/gen-strings.mjs. Do not edit. -->
+<resources>
+ <string name="app_name">Coucou for Android</string>
+ <string name="about_unofficial">Coucou for Android, by Rhytam Biswas. Part of Coucou by Louis Raillé.</string>
+ <string name="about_repo">github.com/Louis-CFM/coucou</string>
+ <string name="licences_title">Licences</string>
+ <string name="licences_intro">The code of Coucou is MIT-licensed. The name, the character, the icon and the sounds are Louis Raillé\'s and are not. The libraries are listed with their licence.</string>
+ <string name="about_assets">The name Coucou, the Mochi character, the icon and the sounds are © Louis Raillé and used with permission. The Android code is © Rhytam Biswas, released under the MIT License.</string>
+ <string name="action_allow">Allow</string>
+ <string name="action_deny">Deny</string>
+ <string name="action_close">Close</string>
+ <string name="widget_description">Shows whether your agents are working, without opening Coucou.</string>
+ <string name="status_connected">Connected</string>
+ <string name="status_connecting">Connecting…</string>
+ <string name="status_not_connected">Not connected</string>
+ <string name="demo_mode">Demo mode</string>
+ <string name="demo_try">Try demo mode</string>
+ <string name="pair_button">Pair</string>
+ <string name="approval_title">Approval needed</string>
+ <string name="action_unpair">Disconnect this computer</string>
+ <string name="demo_leave">Leave demo mode</string>
+ <string name="gallery">Mochi gallery</string>
+ <string name="pair_paste_short">Paste the link</string>
+ <string name="pairing_headline">Connect to your computer</string>
+ <string name="pairing_help">On your computer open Coucou, then Settings, Android phone, and scan the code it shows.</string>
+ <string name="pairing_footer">Coucou for Android, by Rhytam Biswas.</string>
+ <string name="pairing_about">About</string>
+ <string name="paste_title">Paste the pairing link</string>
+ <string name="paste_hint">Copy it from Coucou on your computer (Settings, Android phone).</string>
+ <string name="approval_later">Not now</string>
+ <string name="approval_wants">Wants to %1$s</string>
+ <string name="approval_too_long">Command is longer than shown</string>
+ <string name="approval_on_computer">Answer this request on your computer. Allow is not offered here, because the whole command cannot be shown on the phone.</string>
+ <string name="approval_caution">Allow only if you asked for this.</string>
+ <string name="approval_show_cmd">Show exact command</string>
+ <string name="approval_hide_cmd">Hide exact command</string>
+ <string name="question_title">%1$s has a question</string>
+ <string name="question_body">Answer it on your computer. To answer here, turn on \"Let the phone answer Claude Code\'s questions\" in Coucou on your computer (Settings &gt; Android phone).</string>
+ <string name="question_see_answer">Answer the question</string>
+ <string name="question_position">Question %1$d of %2$d</string>
+ <string name="question_pick_many">Pick one or more</string>
+ <string name="question_next">Next</string>
+ <string name="question_back">Back</string>
+ <string name="question_send">Send answer</string>
+ <string name="question_confirm_title">Send your answer</string>
+ <string name="question_sent">Answer sent</string>
+ <string name="question_not_sent">The answer could not be sent. Your computer may have answered already.</string>
+ <string name="question_see">See the question</string>
+ <string name="question_ok">OK</string>
+ <string name="home_running">%1$d running</string>
+ <string name="home_empty_title">Nothing is running</string>
+ <string name="home_empty_hint">Start an agent on your computer and it shows up here.</string>
+ <string name="recent_title">Recent</string>
+ <string name="recent_all">See all</string>
+ <string name="status_looking">Looking for your computer…</string>
+ <string name="discovery_title">Can\'t find your computer</string>
+ <string name="discovery_body">Is the phone on the same Wi-Fi as the computer? Is the computer awake, with Coucou running and the phone link on, and does Windows allow Coucou on private networks? Some hotspots and guest networks block devices from finding each other (client isolation).</string>
+ <string name="discovery_pair_again">Pair again</string>
+ <string name="discovery_enter_address">Enter address manually</string>
+ <string name="address_title">Computer address</string>
+ <string name="address_hint">For example 192.168.1.20 or 192.168.1.20:47821. Your pairing stays as it is: only the address changes.</string>
+ <string name="address_save">Use this address</string>
+ <string name="address_bad">That is not a valid address.</string>
+ <string name="chat_off_not_paired_title">Not connected</string>
+ <string name="chat_off_not_paired_body">Pair your computer first, then you can chat through it.</string>
+ <string name="chat_off_offline_title">Not connected</string>
+ <string name="chat_off_offline_body">Your computer cannot be reached right now. Check that it is on, with Coucou running, on the same Wi-Fi.</string>
+ <string name="chat_off_title">Chat is off on your computer</string>
+ <string name="chat_nomodel_title">Your computer has no model allowed for the phone yet</string>
+ <string name="chat_off_hint">On your computer open Coucou &gt; Settings &gt; Android phone, turn on \"Let the phone chat with my AI providers\" and tick a model.</string>
+ <string name="chat_go_pair">Connect to your computer</string>
+ <string name="chat_go_settings">Open Settings</string>
+ <string name="tab_home">Home</string>
+ <string name="tab_chat">Chat</string>
+ <string name="tab_settings">Settings</string>
+ <string name="design_note">The building blocks of the new look. No other screen uses them yet.</string>
+ <string name="pair_clipboard">Paste from clipboard</string>
+ <string name="notif_unlock">Unlock to see the request</string>
+ <string name="msg_not_pending">That request is no longer pending.</string>
+ <string name="msg_bad_link">That is not a Coucou pairing link.</string>
+ <string name="msg_rejected">The desktop rejected this phone. Pair again.</string>
+ <string name="msg_link_error">Link error</string>
+ <string name="msg_need_lock">Set a screen lock to approve from your phone.</string>
+ <string name="approval_hint">Allow on the phone asks for the fingerprint or the screen lock. Deny does not.</string>
+ <string name="overlay_title">Show Mochi over other apps</string>
+ <string name="overlay_hint">An island drops from the top of the screen while an agent works, then goes back up.</string>
+ <string name="msg_overlay_permission">Allow “display over other apps” for Coucou, then come back.</string>
+ <string name="settings_title">Settings</string>
+ <string name="settings_sound">Mochi\'s sounds</string>
+ <string name="settings_volume">Volume</string>
+ <string name="notify_done">When an agent finishes or fails</string>
+ <string name="notify_done_hint">A quiet notice in the notification shade, and the pill if it is on. Permission requests and questions always notify you.</string>
+ <string name="quiet_hours">Quiet hours</string>
+ <string name="quiet_hint">No sound and no pill for finished or failed agents. Requests and questions still come through.</string>
+ <string name="quiet_from">From</string>
+ <string name="quiet_to">To</string>
+ <string name="history_title">Activity</string>
+ <string name="history_empty">Your decisions will appear here. They stay on this phone.</string>
+ <string name="history_today">Today</string>
+ <string name="history_yesterday">Yesterday</string>
+ <string name="history_clear">Clear history</string>
+ <string name="history_note">Kept only on this phone, never sent anywhere.</string>
+ <string name="action_back">Back</string>
+ <string name="notif_finished">Finished</string>
+ <string name="notif_error">Stopped on an error</string>
+ <string name="notif_question">Has a question</string>
+ <string name="notif_ratelimit">Hit a usage limit</string>
+ <string name="island_answer_on_pc">Tap to open Coucou, or answer on your computer</string>
+ <string name="state_ready">Ready</string>
+ <string name="state_working">Working</string>
+ <string name="state_thinking">Thinking</string>
+ <string name="state_searching">Searching</string>
+ <string name="state_approval">Waiting for your OK</string>
+ <string name="state_question">Has a question</string>
+ <string name="state_error">Error</string>
+ <string name="state_finished">Finished</string>
+ <string name="state_ratelimit">Limit reached</string>
+ <string name="state_sleeping">Sleeping</string>
+ <string name="state_dizzy">Dizzy</string>
+ <string name="agent_kind">Agent</string>
+ <string name="link_pair">Pair with your computer</string>
+ <string name="link_approval">Review request</string>
+ <string name="overlay_missing">Allow “display over other apps” so the island can show.</string>
+ <string name="overlay_allow">Allow</string>
+ <string name="settings_section_computer">Computer</string>
+ <string name="settings_section_away">Away from home Wi-Fi</string>
+ <string name="relay_use">Use the relay when I\'m away</string>
+ <string name="relay_use_hint">Reaches your computer from mobile data or another network, through the relay you set up. Everything stays end-to-end encrypted. The direct link is always tried first.</string>
+ <string name="relay_line_none">This pairing has no relay. On your computer, turn on Away from home Wi-Fi in Settings, then scan the new code.</string>
+ <string name="relay_line_off">The relay is off. Coucou only connects when your computer is on this network.</string>
+ <string name="relay_line_direct">Connected directly on this network.</string>
+ <string name="relay_line_via">Connected through your relay (%1$s).</string>
+ <string name="relay_line_waiting">Looking for your computer. It will use the relay if it is not on this network.</string>
+ <string name="relay_line_access">The relay refused the access key. Check it in Settings on your computer.</string>
+ <string name="relay_line_taken">This pairing is in use somewhere else. Pair again from your computer.</string>
+ <string name="relay_line_rate">The relay is limiting connections for now. Trying again soon.</string>
+ <string name="relay_line_unreachable">Cannot reach the relay. Check your internet connection.</string>
+ <string name="relay_line_away">Your computer is not answering through the relay. It may be asleep or have the relay off.</string>
+ <string name="settings_section_sound">Sound</string>
+ <string name="settings_section_notices">Notices</string>
+ <string name="settings_section_display">Display</string>
+ <string name="settings_section_more">More</string>
+ <string name="settings_section_about">About</string>
+ <string name="settings_computer_none">No computer connected yet. You can pair one from the Home screen.</string>
+ <string name="action_cancel">Cancel</string>
+ <string name="chat_title">Chat</string>
+ <string name="chat_note">Uses your computer\'s API key. Your computer sends your messages to the provider you pick; the key never reaches this phone.</string>
+ <string name="chat_empty">Ask anything. Your message goes to the model you pick above the box.</string>
+ <string name="chat_placeholder">Ask me anything…</string>
+ <string name="chat_send">Send</string>
+ <string name="chat_stop">Stop</string>
+ <string name="chat_clear">Clear</string>
+ <string name="chat_clear_title">Clear this chat?</string>
+ <string name="chat_clear_body">This removes the conversation from this phone and tells your computer to forget it.</string>
+ <string name="chat_model">Model: %1$s</string>
+ <string name="chat_count">%1$d / %2$d</string>
+ <string name="chat_ref_too_long">That message is too long.</string>
+ <string name="chat_ref_no_model">Pick a model first.</string>
+ <string name="chat_ref_busy">Wait for the answer to finish, or stop it.</string>
+ <string name="chat_ref_offline">Not connected to your computer.</string>
+ <string name="chat_err_off">Chat is turned off on your computer.</string>
+ <string name="chat_err_not_allowed">That model is not allowed for the phone.</string>
+ <string name="chat_err_busy">Another answer is still being written.</string>
+ <string name="chat_err_rate">Too many messages. Try again in a few minutes.</string>
+ <string name="chat_err_too_long">The message is too long.</string>
+ <string name="chat_err_empty">Nothing to send.</string>
+ <string name="chat_err_no_key">Your computer has no key for that provider.</string>
+ <string name="chat_err_unreachable">Your computer could not reach the provider.</string>
+ <string name="chat_err_auth">The provider refused your computer\'s key.</string>
+ <string name="chat_err_provider">The provider returned an error.</string>
+ <string name="chat_err_canceled">Stopped.</string>
+ <string name="chat_err_internal">Something went wrong.</string>
+ <string name="chat_err_connection">The connection to your computer was lost.</string>
+ <string name="chat_err_interrupted">Stopped when the app closed.</string>
+ <string name="session_details">Details</string>
+ <string name="session_last">Last message</string>
+ <string name="session_steps">Steps</string>
+ <string name="session_step_working">Working</string>
+ <string name="session_step_done">Step done</string>
+ <string name="session_no_steps">No steps yet.</string>
+ <string name="session_hint">Turn on “Show session details on the phone” in your computer\'s Settings to see the steps and the last message here.</string>
+ <string name="session_ended">This session is no longer running.</string>
+ <string name="session_project">Project: %1$s</string>
+ <string name="scan_button">Scan QR code</string>
+ <string name="scan_title">Scan QR code</string>
+ <string name="scan_hint">Point the camera at the code in your computer\'s Settings → Android phone.</string>
+ <string name="scan_not_pairing">That is not a Coucou pairing code</string>
+ <string name="scan_why">Coucou uses the camera only on this screen, to read the pairing code. Nothing is saved or sent.</string>
+ <string name="scan_allow">Allow camera</string>
+ <string name="scan_blocked">The camera is off for Coucou. Turn it on in Android\'s settings, or paste the link instead.</string>
+ <string name="scan_open_settings">Open settings</string>
+ <string name="scan_paste_instead">Paste the link instead</string>
+ <string name="scan_camera_error">The camera could not start. Paste the link instead.</string>
+ <string name="pair_confirm_title">Pair with %1$s?</string>
+ <string name="pair_confirm_body">%1$s:%2$d on your network. Only pair with a computer you own.</string>
+ <string name="pair_confirm_relay">It can also reach your computer from other networks through the relay at %1$s. Only pair if you set up that relay yourself.</string>
+ <string name="pair_confirm_replace">This replaces the computer you are connected to now.</string>
+ <string name="pair_confirm_ok">Pair</string>
+ <string name="wardrobe_title">Mochi\'s wardrobe</string>
+ <string name="wardrobe_note">Choose what Mochi wears on this phone.</string>
+ <string name="wardrobe_follow">Same as my computer</string>
+ <string name="wardrobe_follow_hint">Mochi wears what you chose in Coucou on your computer.</string>
+ <string name="wardrobe_auto_tag">AUTO</string>
+ <string name="wardrobe_selected">Selected</string>
+ <string name="outfit_auto">Auto (seasons)</string>
+ <string name="outfit_none">None</string>
+ <string name="outfit_partyHat">Party hat</string>
+ <string name="outfit_beanie">Beanie</string>
+ <string name="outfit_crown">Crown</string>
+ <string name="outfit_sunglasses">Sunglasses</string>
+ <string name="outfit_roundGlasses">Round glasses</string>
+ <string name="outfit_bow">Bow</string>
+ <string name="outfit_scarf">Scarf</string>
+ <string name="outfit_witchHat">Witch hat</string>
+ <string name="outfit_pumpkin">Pumpkin</string>
+ <string name="outfit_santaHat">Santa hat</string>
+ <string name="outfit_bunnyEars">Bunny ears</string>
+ <string name="files_heading">Files changed</string>
+ <string name="files_counts">+%1$d −%2$d</string>
+ <string name="files_new">New file</string>
+ <string name="file_loading">Loading the changes…</string>
+ <string name="file_failed">Could not load this change. Check the connection and try again.</string>
+ <string name="file_gone">This change is no longer available on your computer.</string>
+ <string name="file_too_large">This change is too large to show line by line.</string>
+ <string name="file_truncated">Only the first 200 lines are shown.</string>
+ <string name="file_empty">Nothing to show.</string>
+ <string name="file_close">Close</string>
+ <string name="file_summary">+%1$d added, −%2$d removed</string>
+ <string name="usage_title">Plan usage</string>
+ <string name="usage_claude">Claude</string>
+ <string name="usage_codex">Codex</string>
+ <string name="usage_five_hours">5 hours</string>
+ <string name="usage_week">Week</string>
+ <string name="usage_pct">%1$d%%</string>
+ <string name="usage_resets_now">Resetting…</string>
+ <string name="usage_resets_hm">Resets in %1$d h %2$d</string>
+ <string name="usage_resets_m">Resets in %1$d min</string>
+ <string name="usage_resets_week">Resets %1$s</string>
+ <string name="usage_credits">%1$d free resets available</string>
+ <string name="usage_desc">%1$s, %2$s: %3$d percent used</string>
+ <string name="services_title">Services</string>
+ <string name="diag_title">Can\'t connect?</string>
+ <string name="diag_intro">These checks find where the connection breaks. Nothing secret is shown or copied: the report hides the pairing code, the fingerprint, the computer\'s name and its full address.</string>
+ <string name="diag_run">Check again</string>
+ <string name="diag_running">Checking…</string>
+ <string name="diag_copy">Copy report</string>
+ <string name="diag_copied">Report copied</string>
+ <string name="diag_ok">OK</string>
+ <string name="diag_problem">Problem</string>
+ <string name="diag_skipped">Not checked</string>
+ <string name="battery_title">Keep the connection while the screen is off</string>
+ <string name="battery_body">Android pauses background apps to save battery. If requests stop reaching you when the phone is locked, let Coucou run without restrictions. This is only a suggestion.</string>
+ <string name="battery_open">Open settings</string>
+ <string name="battery_not_now">Not now</string>
+</resources>
diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml
new file mode 100644
index 00000000..262aec0a
--- /dev/null
+++ b/android/app/src/main/res/values/themes.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Dark only (the UI itself is Compose). -->
+ <style name="Theme.Coucou" parent="android:Theme.DeviceDefault">
+ <item name="android:windowActionBar">false</item>
+ <item name="android:windowNoTitle">true</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/xml/backup_rules.xml b/android/app/src/main/res/xml/backup_rules.xml
new file mode 100644
index 00000000..a785c54e
--- /dev/null
+++ b/android/app/src/main/res/xml/backup_rules.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Android 11 and older: nothing is backed up (the pairing secret stays on this phone). -->
+<full-backup-content>
+ <exclude domain="root" /><exclude domain="sharedpref" /><exclude domain="database" /><exclude domain="file" />
+</full-backup-content>
diff --git a/android/app/src/main/res/xml/coucou_widget_info.xml b/android/app/src/main/res/xml/coucou_widget_info.xml
new file mode 100644
index 00000000..c0e73f58
--- /dev/null
+++ b/android/app/src/main/res/xml/coucou_widget_info.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="180dp"
+ android:minHeight="110dp"
+ android:targetCellWidth="3"
+ android:targetCellHeight="2"
+ android:minResizeWidth="110dp"
+ android:minResizeHeight="70dp"
+ android:resizeMode="horizontal|vertical"
+ android:updatePeriodMillis="0"
+ android:widgetCategory="home_screen"
+ android:initialLayout="@layout/widget_glance"
+ android:description="@string/widget_description" />
diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 00000000..facca1fb
--- /dev/null
+++ b/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The pairing secret must never leave this phone: no cloud backup, no device-to-device transfer. -->
+<data-extraction-rules>
+ <cloud-backup><exclude domain="root" /><exclude domain="sharedpref" /><exclude domain="database" /><exclude domain="file" /></cloud-backup>
+ <device-transfer><exclude domain="root" /><exclude domain="sharedpref" /><exclude domain="database" /><exclude domain="file" /></device-transfer>
+</data-extraction-rules>
diff --git a/android/app/src/test/kotlin/com/coucou/android/ApprovalSheetPlanTest.kt b/android/app/src/test/kotlin/com/coucou/android/ApprovalSheetPlanTest.kt
new file mode 100644
index 00000000..e50d65f8
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ApprovalSheetPlanTest.kt
@@ -0,0 +1,43 @@
+package com.coucou.android
+
+import com.coucou.android.core.ApprovalSheetPlan
+import com.coucou.android.core.OverlayPolicy
+import com.coucou.android.link.ApprovalRequest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ApprovalSheetPlanTest {
+ private fun r(fp: String, tool: String = "Bash") = ApprovalRequest("p", fp, tool, "rm -rf /tmp/x", 0L)
+
+ @Test fun theFirstRequestShowsUntilTheUserClosesIt() {
+ val list = listOf(r("a"), r("b"))
+ assertEquals("a", ApprovalSheetPlan.next(list, null)!!.fingerprint)
+ assertEquals("b", ApprovalSheetPlan.next(list, "a")!!.fingerprint)
+ assertNull(ApprovalSheetPlan.next(listOf(r("a")), "a"))
+ assertNull(ApprovalSheetPlan.next(emptyList(), null))
+ }
+
+ @Test fun aClosedRequestComesBackWhenHomeAsksForIt() {
+ assertEquals("a", ApprovalSheetPlan.next(listOf(r("a")), null)!!.fingerprint)
+ }
+
+ @Test fun theSheetNamesTheKindOfActionNotTheCommand() {
+ assertEquals("run a command", ApprovalSheetPlan.action("Bash"))
+ assertEquals("edit files", ApprovalSheetPlan.action("Write"))
+ assertFalse(ApprovalSheetPlan.action("Bash").contains("rm"))
+ }
+
+ @Test fun aCommandThatWasCutIsNeverAllowedFromThePhone() {
+ assertTrue(ApprovalSheetPlan.canAllowHere(r("a")))
+ assertFalse(ApprovalSheetPlan.canAllowHere(r("a").copy(truncated = true)))
+ // 10,000 characters, as the computer would send them: the first 500 and the flag.
+ assertFalse(ApprovalSheetPlan.canAllowHere(ApprovalRequest("p", "a", "Bash", "x".repeat(500), 0L, truncated = true)))
+ }
+
+ @Test fun earlyTapsAreIgnoredLikeOnTheIsland() {
+ assertEquals(OverlayPolicy.TAP_GUARD_MS.toLong(), ApprovalSheetPlan.GUARD_MS)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/AssetsTest.kt b/android/app/src/test/kotlin/com/coucou/android/AssetsTest.kt
new file mode 100644
index 00000000..782b29fe
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/AssetsTest.kt
@@ -0,0 +1,52 @@
+package com.coucou.android
+
+import com.coucou.android.mochi.MochiConst
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class AssetsTest {
+ private val raw = File("src/main/res/raw")
+ private val res = File("src/main/res")
+
+ @Test fun everyBundledSoundIsTheDesktopsOwnFileByteForByte() {
+ val desktop = ReferenceFiles.file("NotchBuddy/Resources/sounds").listFiles { f -> f.extension == "wav" }!!.associateBy { it.name }
+ for (f in raw.listFiles()!!) {
+ val original = desktop[f.name] ?: error("${f.name} is not one of the desktop's sounds")
+ assertTrue(f.name, original.readBytes().contentEquals(f.readBytes()))
+ }
+ }
+
+ @Test fun everySoundTheAppPlaysIsBundled() {
+ val code = File("src/main/kotlin").walkTopDown().filter { it.extension == "kt" }.joinToString("\n") { it.readText() }
+ val played = Regex("""\.play\("(\w+)"\)""").findAll(code).map { it.groupValues[1] }.toSet() + MochiConst.STATE_SOUND.values
+ assertTrue(played.isNotEmpty())
+ played.forEach { assertTrue("$it.wav", File(raw, "$it.wav").exists()) }
+ }
+
+ @Test fun noBundledSoundIsLeftUnused() {
+ val code = File("src/main/kotlin").walkTopDown().filter { it.extension == "kt" && it.name != "SoundPlayer.kt" }.joinToString("\n") { it.readText() }
+ val played = Regex("""\.play\("(\w+)"\)""").findAll(code).map { it.groupValues[1] }.toSet() + MochiConst.STATE_SOUND.values
+ assertEquals(raw.listFiles()!!.map { it.nameWithoutExtension }.toSet(), played)
+ }
+
+
+ @Test fun rawNamesAreValidAndroidResourceNames() {
+ raw.listFiles()!!.forEach { assertTrue(it.name, Regex("""[a-z][a-z0-9_]*\.wav""").matches(it.name)) }
+ }
+
+ @Test fun soundTableCoversEveryBundledSound() {
+ val src = File("src/main/kotlin/com/coucou/android/sound/SoundPlayer.kt").readText()
+ val mapped = Regex("\"(\\w+)\" to R\\.raw\\.(\\w+)").findAll(src).map { assertEquals(it.groupValues[1], it.groupValues[2]); it.groupValues[1] }.toSet()
+ assertEquals(raw.listFiles()!!.map { it.nameWithoutExtension }.toSet(), mapped)
+ }
+
+ @Test fun notificationIconIsMonochromeVector() {
+ assertTrue(File(res, "drawable/ic_stat_mochi.xml").readText().contains("#FFFFFFFF"))
+ }
+
+ @Test fun launcherIconIsPresent() {
+ assertTrue(File(res, "mipmap-xxxhdpi/ic_launcher.png").length() > 1000)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/AttributionTest.kt b/android/app/src/test/kotlin/com/coucou/android/AttributionTest.kt
new file mode 100644
index 00000000..018ac42f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/AttributionTest.kt
@@ -0,0 +1,11 @@
+package com.coucou.android
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class AttributionTest {
+ @Test fun nameAndRepoMatchPermission() {
+ assertEquals("Coucou for Android", Attribution.APP_NAME)
+ assertEquals("https://github.com/Louis-CFM/coucou", Attribution.REPO_URL)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ChatHistoryTest.kt b/android/app/src/test/kotlin/com/coucou/android/ChatHistoryTest.kt
new file mode 100644
index 00000000..10d82649
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ChatHistoryTest.kt
@@ -0,0 +1,89 @@
+package com.coucou.android
+
+import com.coucou.android.core.ChatHistory
+import com.coucou.android.core.ChatMessage
+import com.coucou.android.core.ChatRole
+import com.coucou.android.core.ChatSession
+import com.coucou.android.core.ChatStatus
+import com.coucou.android.core.TextFile
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ChatHistoryTest {
+ private class Mem(var text: String? = null) : TextFile {
+ override fun read() = text
+ override fun write(text: String) { this.text = text }
+ override fun delete() { text = null }
+ }
+
+ private val sample = listOf(
+ ChatMessage("u-c1", ChatRole.USER, "Hello \"there\"\nsecond line é"),
+ ChatMessage("c1", ChatRole.ASSISTANT, "Hi!", ChatStatus.DONE),
+ ChatMessage("u-c2", ChatRole.USER, "again"),
+ ChatMessage("c2", ChatRole.ASSISTANT, "part", ChatStatus.FAILED, "rate"),
+ )
+
+ @Test fun whatIsSavedComesBack() {
+ val h = ChatHistory(Mem())
+ h.save(sample)
+ assertEquals(sample, h.load())
+ }
+
+ @Test fun savingNothingRemovesTheFile() {
+ val m = Mem()
+ val h = ChatHistory(m)
+ h.save(sample)
+ assertTrue(m.text != null)
+ h.save(emptyList())
+ assertNull(m.text)
+ assertEquals(emptyList<ChatMessage>(), h.load())
+ }
+
+ @Test fun clearDeletesTheFile() {
+ val m = Mem()
+ val h = ChatHistory(m)
+ h.save(sample)
+ h.clear()
+ assertNull(m.text)
+ }
+
+ @Test fun aDamagedOrUnknownFileIsAnEmptyHistory() {
+ for (bad in listOf("", " ", "not json", "{}", """{"v":2,"messages":[]}""", """{"v":1}""", """{"v":1,"messages":5}""", "[]")) {
+ assertEquals(bad, emptyList<ChatMessage>(), ChatHistory(Mem(bad)).load())
+ }
+ }
+
+ @Test fun badEntriesAreSkippedAndTheRestKept() {
+ val text = """{"v":1,"messages":[5,{"id":"","role":"user","text":"x"},{"id":"a","role":"alien","text":"x"},{"id":"ok","role":"user","text":"kept"}]}"""
+ assertEquals(listOf(ChatMessage("ok", ChatRole.USER, "kept")), ChatHistory(Mem(text)).load())
+ }
+
+ @Test fun anAnswerThatWasStillArrivingIsShownAsInterrupted() {
+ val h = ChatHistory(Mem())
+ h.save(listOf(ChatMessage("c1", ChatRole.ASSISTANT, "half", ChatStatus.STREAMING)))
+ val m = h.load().single()
+ assertEquals(ChatStatus.FAILED, m.status)
+ assertEquals("interrupted", m.reason)
+ assertEquals("half", m.text)
+ }
+
+ @Test fun onlyTheLastTwoHundredAreKept() {
+ val many = (1..300).map { ChatMessage("m$it", ChatRole.USER, "t$it") }
+ val h = ChatHistory(Mem())
+ h.save(many)
+ val back = h.load()
+ assertEquals(ChatSession.MAX_MESSAGES, back.size)
+ assertEquals("m300", back.last().id)
+ }
+
+ @Test fun theFileHoldsTheChatAndNothingElse() {
+ // No key, address or model list is ever in a ChatMessage, so none can be in the file.
+ val m = Mem()
+ ChatHistory(m).save(sample)
+ assertFalse(m.text!!.contains("token", ignoreCase = true))
+ assertTrue(m.text!!.length < 2000)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ChatScreenTest.kt b/android/app/src/test/kotlin/com/coucou/android/ChatScreenTest.kt
new file mode 100644
index 00000000..507b3f47
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ChatScreenTest.kt
@@ -0,0 +1,48 @@
+package com.coucou.android
+
+import com.coucou.android.core.ChatReasons
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Source-level guards for the Chat screen (Compose cannot be rendered in a JVM test). */
+class ChatScreenTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val strings get() = File("src/main/res/values/strings.xml").readText()
+
+ @Test fun everyReasonCodeHasAnEnglishSentence() {
+ for (code in ChatReasons.KNOWN) assertTrue("chat_err_$code", strings.contains("name=\"chat_err_$code\""))
+ assertEquals("internal", ChatReasons.key("something-new"))
+ assertEquals("internal", ChatReasons.key(null))
+ assertEquals("rate", ChatReasons.key("rate"))
+ }
+
+ @Test fun theScreenMapsEveryKnownReasonToItsSentence() {
+ val ui = src("ui/ChatScreen.kt")
+ for (code in ChatReasons.KNOWN.filter { it != "internal" }) assertTrue("reason $code", ui.contains("\"$code\" -> R.string.chat_err_$code"))
+ }
+
+ @Test fun theKeyNoteIsOnTheScreenAndNoKeyIsEverHandledHere() {
+ val ui = src("ui/ChatScreen.kt")
+ assertTrue(ui.contains("R.string.chat_note"))
+ assertTrue(strings.contains("Uses your computer's API key") || strings.contains("Uses your computer\\'s API key"))
+ // the phone has no key, address or provider call of its own
+ for (word in listOf("api-key", "apiKey", "Authorization", "https://")) assertFalse(word, ui.contains(word))
+ }
+
+ @Test fun clearAsksFirstAndTellsTheComputerToForget() {
+ val ui = src("ui/ChatScreen.kt")
+ assertTrue(ui.contains("AlertDialog"))
+ assertTrue(ui.contains("model.chatClear()"))
+ assertTrue(src("app/AppModel.kt").contains("link?.chatReset()"))
+ }
+
+ @Test fun theBoxCannotSendWhenUnavailableEmptyOrTooLong() {
+ val ui = src("ui/ChatScreen.kt")
+ assertTrue(ui.contains("enabled = model.chatAvailable && length in 1..limit"))
+ assertTrue(ui.contains("enabled = model.chatAvailable"))
+ }
+
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ChatSessionTest.kt b/android/app/src/test/kotlin/com/coucou/android/ChatSessionTest.kt
new file mode 100644
index 00000000..daf81a9f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ChatSessionTest.kt
@@ -0,0 +1,155 @@
+package com.coucou.android
+
+import com.coucou.android.core.ChatIds
+import com.coucou.android.core.ChatModels
+import com.coucou.android.core.ChatRole
+import com.coucou.android.core.ChatSession
+import com.coucou.android.core.ChatSession.Refusal
+import com.coucou.android.core.ChatSession.Sent
+import com.coucou.android.core.ChatStatus
+import com.coucou.android.link.ChatModel
+import com.coucou.android.link.Protocol
+import com.coucou.android.link.Wire
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ChatSessionTest {
+ private var n = 0
+ private fun session() = ChatSession(newId = { "c${++n}" })
+
+ private fun ChatSession.ask(text: String = "hi", model: String? = "openai/gpt", connected: Boolean = true) = send(text, model, connected)
+
+ @Test fun aQuestionIsSentOnceAndShowsUpTwiceOnScreen() {
+ val s = session()
+ val sent = s.ask(" Why is the sky blue? ") as Sent.Ok
+ assertEquals("c1", sent.msg.id)
+ assertEquals("openai/gpt", sent.msg.model)
+ assertEquals("Why is the sky blue?", sent.msg.text)
+ assertEquals("c1", s.running)
+ assertEquals(listOf(ChatRole.USER, ChatRole.ASSISTANT), s.messages.map { it.role })
+ assertEquals(ChatStatus.STREAMING, s.messages[1].status)
+ assertEquals("", s.messages[1].text)
+ }
+
+ @Test fun refusalsChangeNothing() {
+ val s = session()
+ assertEquals(Refusal.EMPTY, (s.ask(" ") as Sent.No).why)
+ assertEquals(Refusal.TOO_LONG, (s.ask("x".repeat(Protocol.CHAT_MAX_TEXT + 1)) as Sent.No).why)
+ assertEquals(Refusal.NO_MODEL, (s.ask(model = null) as Sent.No).why)
+ assertEquals(Refusal.NO_MODEL, (s.ask(model = " ") as Sent.No).why)
+ assertEquals(Refusal.OFFLINE, (s.ask(connected = false) as Sent.No).why)
+ assertTrue(s.messages.isEmpty())
+ assertNull(s.running)
+ assertTrue(s.ask("x".repeat(Protocol.CHAT_MAX_TEXT)) is Sent.Ok)
+ }
+
+ @Test fun onlyOneAnswerAtATime() {
+ val s = session()
+ s.ask("one")
+ assertEquals(Refusal.BUSY, (s.ask("two") as Sent.No).why)
+ assertEquals(2, s.messages.size)
+ }
+
+ @Test fun deltasBuildTheAnswerAndDoneEndsIt() {
+ val s = session()
+ s.ask()
+ s.onDelta("c1", "Hel"); s.onDelta("c1", "lo")
+ assertEquals("Hello", s.messages[1].text)
+ assertEquals(ChatStatus.STREAMING, s.messages[1].status)
+ s.onDone("c1", null)
+ assertEquals("Hello", s.messages[1].text)
+ assertEquals(ChatStatus.DONE, s.messages[1].status)
+ assertNull(s.running)
+ assertTrue(s.ask("next") is Sent.Ok)
+ }
+
+ @Test fun aCorrectedAnswerReplacesTheStreamedOne() {
+ val s = session()
+ s.ask()
+ s.onDelta("c1", "<think>hmm")
+ s.onDone("c1", "Answer")
+ assertEquals("Answer", s.messages[1].text)
+ }
+
+ @Test fun anErrorKeepsWhatArrivedAndSaysWhy() {
+ val s = session()
+ s.ask()
+ s.onDelta("c1", "partial")
+ s.onError("c1", "provider")
+ with(s.messages[1]) {
+ assertEquals("partial", text); assertEquals(ChatStatus.FAILED, status); assertEquals("provider", reason)
+ }
+ assertNull(s.running)
+ }
+
+ @Test fun cancelStopsWaitingAtOnceAndLateWordsAreIgnored() {
+ val s = session()
+ s.ask()
+ s.onDelta("c1", "a")
+ assertEquals("c1", s.cancel())
+ assertEquals("canceled", s.messages[1].reason)
+ s.onDelta("c1", "late"); s.onDone("c1", "late"); s.onError("c1", "rate")
+ assertEquals("a", s.messages[1].text)
+ assertEquals("canceled", s.messages[1].reason)
+ assertNull(s.cancel())
+ }
+
+ @Test fun wordsForAnotherRequestChangeNothing() {
+ val s = session()
+ s.ask()
+ s.onDelta("other", "x"); s.onDone("other", "y"); s.onError("other", "auth")
+ assertEquals("", s.messages[1].text)
+ assertEquals("c1", s.running)
+ }
+
+ @Test fun aDroppedLinkEndsTheWaitWithoutLosingTheText() {
+ val s = session()
+ s.ask(); s.onDelta("c1", "half")
+ s.onDisconnected()
+ assertEquals("half", s.messages[1].text)
+ assertEquals("connection", s.messages[1].reason)
+ assertNull(s.running)
+ s.onDisconnected() // nothing running: nothing happens
+ }
+
+ @Test fun clearForgetsEverythingAndStopsWaiting() {
+ val s = session()
+ s.ask(); s.onDone("c1", null); s.ask("again")
+ s.clear()
+ assertTrue(s.messages.isEmpty())
+ assertNull(s.running)
+ s.onDelta("c2", "late")
+ assertTrue(s.messages.isEmpty())
+ }
+
+ @Test fun onlyTheLastTwoHundredMessagesAreKept() {
+ val s = session()
+ repeat(150) { s.ask("q$it"); s.onDone("c${it + 1}", null) }
+ assertEquals(ChatSession.MAX_MESSAGES, s.messages.size)
+ assertEquals("q149", s.messages[s.messages.size - 2].text)
+ }
+
+ @Test fun anAnswerCannotGrowWithoutLimit() {
+ val s = session()
+ s.ask()
+ repeat(10) { s.onDelta("c1", "x".repeat(10_000)) }
+ assertEquals(ChatSession.MAX_TEXT, s.messages[1].text.length)
+ }
+
+ @Test fun generatedIdsAreValidAndDifferent() {
+ val ids = (1..200).map { ChatIds.random() }
+ assertTrue(ids.all { Wire.isChatId(it) })
+ assertEquals(200, ids.toSet().size)
+ }
+
+ @Test fun theModelStaysIfStillAllowedElseTheFirst() {
+ val a = ChatModel("openai/a", "openai", "A")
+ val b = ChatModel("google/b", "google", "B")
+ assertEquals("google/b", ChatModels.pick(listOf(a, b), "google/b"))
+ assertEquals("openai/a", ChatModels.pick(listOf(a, b), "gone/x"))
+ assertEquals("openai/a", ChatModels.pick(listOf(a, b), null))
+ assertNull(ChatModels.pick(emptyList(), "openai/a"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ChatTabTest.kt b/android/app/src/test/kotlin/com/coucou/android/ChatTabTest.kt
new file mode 100644
index 00000000..77a746d7
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ChatTabTest.kt
@@ -0,0 +1,127 @@
+package com.coucou.android
+
+import com.coucou.android.core.BarFit
+import com.coucou.android.core.ChatTab
+import com.coucou.android.core.ChatTabState
+import com.coucou.android.core.Screen
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ChatTabTest {
+ private fun s(paired: Boolean = true, connected: Boolean = true, offered: Boolean = true, models: Int = 2) =
+ ChatTab.state(paired, connected, offered, models)
+
+ @Test fun nothingPairedComesFirst() {
+ assertEquals(ChatTabState.NOT_PAIRED, s(paired = false, connected = false, offered = false, models = 0))
+ assertEquals(ChatTabState.NOT_PAIRED, s(paired = false, connected = true, offered = true, models = 3))
+ }
+
+ @Test fun pairedButNotConnectedIsNotConnectedWhateverWasOfferedBefore() {
+ assertEquals(ChatTabState.NOT_CONNECTED, s(connected = false))
+ assertEquals(ChatTabState.NOT_CONNECTED, s(connected = false, offered = false, models = 0))
+ }
+
+ @Test fun connectedWithoutTheChatCapabilityIsChatOff() {
+ assertEquals(ChatTabState.CHAT_OFF, s(offered = false, models = 0))
+ assertEquals("models without the capability still mean chat is off", ChatTabState.CHAT_OFF, s(offered = false, models = 2))
+ }
+
+ @Test fun offeredWithNoModelAllowedIsNoModels() {
+ assertEquals(ChatTabState.NO_MODELS, s(models = 0))
+ assertEquals(ChatTabState.NO_MODELS, s(models = -1))
+ }
+
+ @Test fun connectedOfferedWithAModelIsReady() {
+ assertEquals(ChatTabState.READY, s())
+ assertEquals(ChatTabState.READY, s(models = 1))
+ }
+
+ @Test fun everyStateButReadyHasAWayOutOrAHint() {
+ assertEquals(Screen.HOME, ChatTab.action(ChatTabState.NOT_PAIRED))
+ assertEquals(Screen.SETTINGS, ChatTab.action(ChatTabState.NOT_CONNECTED))
+ assertNull(ChatTab.action(ChatTabState.CHAT_OFF))
+ assertNull(ChatTab.action(ChatTabState.NO_MODELS))
+ assertNull(ChatTab.action(ChatTabState.READY))
+ }
+
+ @Test fun allFiveStatesAreReachable() {
+ val seen = setOf(s(paired = false), s(connected = false), s(offered = false), s(models = 0), s())
+ assertEquals(ChatTabState.entries.toSet(), seen)
+ }
+}
+
+class BarFitTest {
+ private val labels = listOf("Home", "Chat", "Settings")
+
+ @Test fun threeLabelsFitOnTheAverageAndOnTheNarrowestPhoneAtLargeFonts() {
+ for (width in listOf(360, 392, 411, 432)) for (scale in listOf(1.0, 1.15, 1.3)) {
+ assertTrue("width $width dp, font scale $scale", BarFit.fits(width, labels, scale))
+ }
+ }
+
+ @Test fun theLongestLabelIsTheOneThatDecidesAndStillFitsAt360DpAtOnePointThree() {
+ val w = BarFit.itemWidthDp(360, 3)
+ assertTrue(BarFit.labelWidthDp("Settings", 1.3) <= w)
+ assertTrue("room to spare at 1.3x", w - BarFit.labelWidthDp("Settings", 1.3) > 10)
+ }
+
+ @Test fun theCheckCanFailSoItMeansSomething() {
+ assertFalse(BarFit.fits(360, labels, 3.0))
+ assertFalse(BarFit.fits(200, labels, 1.0))
+ }
+
+ @Test fun moreTabsWouldNotFitAtLargeFonts() {
+ assertFalse(BarFit.fits(360, labels + listOf("History", "Gallery"), 1.3))
+ }
+}
+
+/** Guards for the Chat tab's screens and the bar (Compose cannot be rendered in a JVM test, so these read the sources). */
+class ChatTabSourceTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val chat get() = src("ui/ChatScreen.kt")
+ private val bar get() = src("ui/BottomBar.kt")
+ private val strings get() = File("src/main/res/values/strings.xml").readText()
+
+ @Test fun theBarKeepsEveryLabelOnOneLineAndGrowsWithTheFont() {
+ assertTrue(bar.contains("maxLines = 1, softWrap = false"))
+ assertTrue(bar.contains("height(IntrinsicSize.Min).heightIn(min = 64.dp)"))
+ assertTrue(bar.contains("BarFit.ITEM_SIDE_PADDING_DP"))
+ assertTrue(Regex("""BAR_SIDE_MARGIN_DP\s*=\s*24""").containsMatchIn(src("core/ChatTab.kt")) && bar.contains("padding(horizontal = 24.dp)"))
+ }
+
+ @Test fun theChatScreenShowsAnEmptyStateWhenThereIsNothingToChatWithOrRead() {
+ assertTrue(chat.contains("if (tabState != ChatTabState.READY && messages.isEmpty())"))
+ assertTrue(chat.contains("ChatEmpty(tabState, onHome, onSettings)"))
+ assertTrue("a sleeping Mochi", chat.contains("BotState.SLEEPING"))
+ }
+
+ @Test fun anExistingConversationStaysReadableWithTheReasonAboveIt() {
+ assertTrue(chat.contains("chatStateTitle(tabState)") && chat.contains("chatStateBody(tabState)"))
+ assertTrue("it cannot be sent to while unavailable", chat.contains("enabled = model.chatAvailable"))
+ }
+
+ @Test fun theWordsAreTheRequestedOnesAndNoRawErrorOrSecretIsInThem() {
+ assertTrue(strings.contains("Not connected"))
+ assertTrue(strings.contains("Chat is off on your computer"))
+ assertTrue(strings.contains("Your computer has no model allowed for the phone yet"))
+ assertTrue(strings.contains("On your computer open Coucou &gt; Settings &gt; Android phone, turn on"))
+ assertTrue(strings.contains("Let the phone chat with my AI providers"))
+ assertTrue(strings.contains("tick a model"))
+ val body = Regex("""<string name="chat_(off|nomodel)[a-z_]*">([^<]*)</string>""").findAll(strings).map { it.groupValues[2].lowercase() }.toList()
+ for (b in body) for (bad in listOf("token", "key=", "exception", "error:", "http", "sha")) assertFalse("'$b' mentions $bad", b.contains(bad))
+ }
+
+ @Test fun theModelStatePicksTheScreen() {
+ assertTrue(src("app/AppModel.kt").contains("val chatTabState: ChatTabState get() = ChatTab.state("))
+ }
+
+ @Test fun homeNoLongerHasAChatEntryAndThereIsNoUnreadDotToKeep() {
+ val main = src("MainActivity.kt")
+ assertFalse(main.contains("AskBar") || main.contains("ChatEntry"))
+ assertFalse(File("src/main").walkTopDown().filter { it.isFile && it.extension == "kt" }.any { Regex("""\bunread\b""", RegexOption.IGNORE_CASE).containsMatchIn(it.readText()) })
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/DesignSystemTest.kt b/android/app/src/test/kotlin/com/coucou/android/DesignSystemTest.kt
new file mode 100644
index 00000000..acb20ac1
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/DesignSystemTest.kt
@@ -0,0 +1,63 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Guards for the redesign's building blocks (the Compose code cannot be rendered in a JVM test, so
+ * these read the sources): accessible controls, colours only from the tokens, no icon library.
+ */
+class DesignSystemTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val system get() = src("ui/DesignSystem.kt")
+ private val controls get() = src("ui/DesignControls.kt")
+ private val icons get() = src("ui/DesignIcons.kt")
+
+ @Test fun theSwitchIsARealToggleForTalkBack() {
+ assertTrue(controls.contains("role = Role.Switch"))
+ assertTrue(controls.contains("toggleable("))
+ }
+
+ @Test fun theSliderCanBeSteppedByTalkBack() {
+ assertTrue(controls.contains("progressBarRangeInfo"))
+ assertTrue(controls.contains("setProgress"))
+ assertTrue(controls.contains("detectTapGestures") && controls.contains("detectHorizontalDragGestures"))
+ }
+
+ @Test fun everyControlIsAtLeast48DpToHit() {
+ assertTrue(controls.contains("Spacing.MIN_TOUCH.dp"))
+ assertTrue(system.contains("heightIn(min = Spacing.MIN_TOUCH.dp)"))
+ }
+
+ @Test fun buttonsAndRowsAnnounceThemselvesAsButtons() {
+ assertTrue(system.contains("role = Role.Button"))
+ }
+
+ @Test fun iconsAreDrawnInCodeWithNoIconLibrary() {
+ assertTrue(icons.contains("IconSpec.shapes("))
+ val gradle = File("build.gradle.kts").readText()
+ assertFalse(gradle.contains("material-icons"))
+ assertFalse(gradle.contains("androidx.navigation"))
+ for (text in listOf(system, controls, icons)) assertFalse(text.contains("androidx.compose.material.icons"))
+ }
+
+ @Test fun withAnimationsOffNothingSpringsOrSlides() {
+ assertTrue(system.contains("fun reducedMotion()") && system.contains("ANIMATOR_DURATION_SCALE"))
+ assertTrue("the switch snaps", controls.contains("if (reduced) snap()"))
+ assertTrue("the sheet only fades", src("ui/Sheets.kt").contains("if (reducedMotion()) fadeIn(tween(MotionSpec.REDUCED_MS))"))
+ assertTrue("the island jumps to its size", src("ui/IslandOverlay.kt").contains("if (reduced) { width.jump(w.toDouble())"))
+ }
+
+ @Test fun theBarGrowsWithTheFontInsteadOfCuttingItsLabels() {
+ val bar = src("ui/BottomBar.kt")
+ assertTrue(bar.contains("height(IntrinsicSize.Min).heightIn(min = 64.dp)"))
+ assertTrue(bar.contains("maxLines = 1"))
+ }
+
+ @Test fun statusDotsUseTheThemeSafeColours() {
+ val theme = src("ui/Theme.kt")
+ for (c in listOf("ONLINE", "BUSY", "OFFLINE")) assertTrue(c, theme.contains("StatusPalette.$c"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/DiffAssemblerTest.kt b/android/app/src/test/kotlin/com/coucou/android/DiffAssemblerTest.kt
new file mode 100644
index 00000000..5602eb2a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/DiffAssemblerTest.kt
@@ -0,0 +1,74 @@
+package com.coucou.android
+
+import com.coucou.android.core.DiffAssembler
+import com.coucou.android.link.DiffRow
+import com.coucou.android.link.ServerMsg
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class DiffAssemblerTest {
+ private fun part(i: Int, of: Int, n: Int, pill: String = "p", file: Long = 7, truncated: Boolean = false) = ServerMsg.Diff(
+ pill, file, "app.ts", 5, 4, tooLarge = false, gone = false, truncated = truncated, part = i, parts = of,
+ lines = (0 until n).map { DiffRow('+', "l$i-$it") },
+ )
+
+ @Test fun oneWholePartIsDone() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ val v = a.accept(part(0, 1, 3))
+ assertNotNull(v)
+ assertEquals(3, v!!.rows.size)
+ assertEquals("app.ts", v.name)
+ assertEquals(5, v.added)
+ }
+
+ @Test fun partsAreJoinedInOrder() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ assertNull(a.accept(part(0, 2, 100)))
+ val v = a.accept(part(1, 2, 100))!!
+ assertEquals(200, v.rows.size)
+ assertEquals("l0-0", v.rows.first().text)
+ assertEquals("l1-99", v.rows.last().text)
+ assertFalse(v.truncated)
+ }
+
+ @Test fun nothingIsKeptAfterItIsDone() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ a.accept(part(0, 1, 2))
+ assertNull("an unasked answer is dropped", a.accept(part(0, 1, 2)))
+ }
+
+ @Test fun whatWasNotAskedForIsDropped() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ assertNull(a.accept(part(0, 1, 2, pill = "other")))
+ assertNull(a.accept(part(0, 1, 2, file = 8)))
+ assertNotNull(a.accept(part(0, 1, 2)))
+ assertNull(DiffAssembler().accept(part(0, 1, 2)))
+ }
+
+ @Test fun aPartOutOfOrderWaitsForAFreshStart() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ assertNull(a.accept(part(1, 2, 10)))
+ assertNull(a.accept(part(0, 2, 10)))
+ assertNotNull(a.accept(part(1, 2, 10)))
+ }
+
+ @Test fun cancelForgetsEverything() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ a.accept(part(0, 2, 100))
+ a.cancel()
+ assertNull(a.accept(part(1, 2, 100)))
+ }
+
+ @Test fun neverMoreThanTwoHundredRowsAndTheNoteSaysSo() {
+ val a = DiffAssembler().apply { expect("p", 7) }
+ a.accept(part(0, 3, 100))
+ a.accept(part(1, 3, 100))
+ val v = a.accept(part(2, 3, 100))!!
+ assertEquals(200, v.rows.size)
+ assertTrue(v.truncated)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/DiscoverySourceTest.kt b/android/app/src/test/kotlin/com/coucou/android/DiscoverySourceTest.kt
new file mode 100644
index 00000000..e4eb4383
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/DiscoverySourceTest.kt
@@ -0,0 +1,75 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Guards for the Android side of "finding the computer again" (system pieces cannot run in a JVM test, so these read the sources). */
+class DiscoverySourceTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val nsd get() = src("app/NsdDiscovery.kt")
+ private val model get() = src("app/AppModel.kt")
+ private val discovery get() = src("link/Discovery.kt")
+
+ @Test fun itUsesTheFrameworkAndNoNewLibrary() {
+ assertTrue(nsd.contains("NsdManager") && nsd.contains("Discovery.SERVICE_TYPE"))
+ val gradle = File("build.gradle.kts").readText().lowercase()
+ for (bad in listOf("jmdns", "zeroconf", "play-services", "mlkit", "androidx.nsd")) assertFalse("build.gradle.kts mentions $bad", gradle.contains(bad))
+ assertEquals("_coucou._tcp", Regex("""SERVICE_TYPE\s*=\s*"([^"]+)"""").find(discovery)!!.groupValues[1])
+ }
+
+ @Test fun theMulticastLockIsHeldOnlyWhileBrowsing() {
+ val start = nsd.substringAfter("override fun start").substringBefore("override fun stop")
+ val stop = nsd.substringAfter("override fun stop").substringBefore("private fun enqueue")
+ assertTrue(start.contains("acquire()"))
+ assertTrue(stop.contains("release()"))
+ assertTrue(File("src/main/AndroidManifest.xml").readText().contains("CHANGE_WIFI_MULTICAST_STATE"))
+ }
+
+ @Test fun theMatchingChecksAndTheSecretNeverMeet() {
+ // the probe has no token parameter, and neither the browsing code nor the finder ever mentions one
+ assertTrue(Regex("""fun interface Probe\s*\{\s*fun check\(host: String, port: Int, certSha256: String\): ProbeResult\s*\}""").containsMatchIn(discovery))
+ assertFalse(nsd.contains("token", ignoreCase = true))
+ assertFalse(discovery.substringBefore("object PinnedProbe").contains(".token") && discovery.contains("Log."))
+ assertFalse("the token is never logged", Regex("""Log\.[a-z]\([^)]*token""", RegexOption.IGNORE_CASE).containsMatchIn(model + nsd + discovery))
+ }
+
+ @Test fun theSavedAddressIsTriedFirstAndTheNetworkIsOnlySearchedAfterAFailure() {
+ assertTrue(model.contains("override fun onConnectFailed(consecutive: Int)"))
+ assertTrue(model.contains("DiscoveryPolicy.FAILURES_BEFORE_DISCOVERY"))
+ assertTrue(src("link/LinkClient.kt").contains("DiscoveryPolicy.SAVED_CONNECT_TIMEOUT_MS"))
+ }
+
+ @Test fun nothingScansWithoutAPairingOrWithoutWifiAndTheSearchEndsWithTheLink() {
+ val stopLink = model.substringAfter("private fun stopLink()").substringBefore("}\n")
+ assertTrue(stopLink.contains("finder.stop()") && stopLink.contains("netWatch.stop()"))
+ assertTrue(model.contains("if (!wifiUp) { finder.stop(); return }"))
+ assertTrue(model.contains("if (state == LinkState.CONNECTED) finder.connected()"))
+ assertTrue(model.contains("DiscoveryPolicy.mayDiscover("))
+ }
+
+ @Test fun aFoundAddressChangesOnlyTheAddressInTheStoredPairing() {
+ val use = model.substringAfter("private fun useAddress").substringBefore("/** A computer matching")
+ assertTrue(use.contains("Discovery.withAddress(p, host, port)") && use.contains("store.savePairing(q)"))
+ assertTrue("a manual address goes through the same function", model.substringAfter("fun setAddress").substringBefore("/**").contains("useAddress(host, port)"))
+ }
+
+ @Test fun theNetworkCallbackIsRegisteredOnlyWhilePairedAndNeverPolls() {
+ val watch = src("app/NetworkWatch.kt")
+ assertTrue(watch.contains("registerDefaultNetworkCallback") && watch.contains("unregisterNetworkCallback"))
+ assertFalse(watch.contains("Thread.sleep") || watch.contains("postDelayed"))
+ assertTrue(model.substringAfter("private fun connect(").substringBefore("/** The saved address").contains("netWatch.start()"))
+ }
+
+ @Test fun theStatusLineAndTheHintSayWhatIsHappening() {
+ assertTrue(src("ui/LinkStatus.kt").contains("R.string.status_looking"))
+ val hint = src("ui/DiscoveryHint.kt")
+ for (s in listOf("discovery_title", "discovery_body", "discovery_pair_again", "discovery_enter_address", "address_save")) assertTrue(s, hint.contains("R.string.$s"))
+ assertTrue(src("MainActivity.kt").contains("model.discovery == DiscoveryState.NOT_FOUND"))
+ val strings = File("src/main/res/values/strings.xml").readText()
+ assertTrue(strings.contains("same Wi-Fi") && strings.contains("client isolation") && strings.contains("private networks"))
+ }
+
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/EnglishOnlyTest.kt b/android/app/src/test/kotlin/com/coucou/android/EnglishOnlyTest.kt
new file mode 100644
index 00000000..636536d2
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/EnglishOnlyTest.kt
@@ -0,0 +1,39 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The app is English only, whatever the phone's language is. */
+class EnglishOnlyTest {
+ private fun read(path: String) = File(path).readText()
+
+ @Test fun theBuildKeepsOnlyEnglishResources() {
+ val gradle = read("build.gradle.kts")
+ assertTrue(Regex("""resourceConfigurations\s*\+=\s*listOf\("en"\)""").containsMatchIn(gradle))
+ }
+
+ @Test fun thereIsNoLanguageChoiceAnywhere() {
+ assertFalse(read("src/main/AndroidManifest.xml").contains("localeConfig"))
+ assertFalse(File("src/main/res/xml/locales_config.xml").exists())
+ assertFalse(File("src/main/kotlin/com/coucou/android/core/Languages.kt").exists())
+ val settings = read("src/main/kotlin/com/coucou/android/ui/SettingsScreens.kt")
+ assertFalse(settings.contains("LocaleManager"))
+ assertFalse(settings.contains("applicationLocales"))
+ }
+
+ @Test fun englishStringsAreTheSingleSourceOfTruth() {
+ val source = read("../i18n/app-strings.json")
+ val english = Regex("""name="([a-z_0-9]+)"""").findAll(read("src/main/res/values/strings.xml")).map { it.groupValues[1] }.toSet()
+ val declared = Regex("""^\s{4}"([a-z_0-9]+)":""", RegexOption.MULTILINE).findAll(source.substringAfter(""""strings"""")).map { it.groupValues[1] }.toSet()
+ assertEquals(declared, english)
+ }
+
+ @Test fun thereAreNoOtherLanguagesInTheRepo() {
+ val folders = File("src/main/res").listFiles().orEmpty().map { it.name }.filter { it.startsWith("values") }
+ assertEquals(listOf("values"), folders.sorted())
+ assertFalse(File("../i18n/extra.json").exists())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/GlanceSurfacesTest.kt b/android/app/src/test/kotlin/com/coucou/android/GlanceSurfacesTest.kt
new file mode 100644
index 00000000..d16b4d43
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/GlanceSurfacesTest.kt
@@ -0,0 +1,56 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Source guards for the widget, the tile and the ongoing notification (Compose and Android classes only compile in CI). */
+class GlanceSurfacesTest {
+ private fun read(path: String) = File(path).readText()
+ private val manifest get() = read("src/main/AndroidManifest.xml")
+ private val widget get() = read("src/main/kotlin/com/coucou/android/app/GlanceWidget.kt")
+ private val tile get() = read("src/main/kotlin/com/coucou/android/app/GlanceTile.kt")
+ private val notifications get() = read("src/main/kotlin/com/coucou/android/app/Notifications.kt")
+ private val model get() = read("src/main/kotlin/com/coucou/android/app/AppModel.kt")
+
+ @Test fun theWidgetAndTheTileAreRegistered() {
+ assertTrue(manifest.contains("""android:name=".app.GlanceWidget""""))
+ assertTrue(manifest.contains("android.appwidget.action.APPWIDGET_UPDATE"))
+ assertTrue(manifest.contains("@xml/coucou_widget_info"))
+ assertTrue(manifest.contains("""android:name=".app.GlanceTile""""))
+ assertTrue(manifest.contains("""android:permission="android.permission.BIND_QUICK_SETTINGS_TILE""""))
+ assertTrue(manifest.contains("android.service.quicksettings.action.QS_TILE"))
+ }
+
+ @Test fun theWidgetNeverWakesOnATimer() {
+ val info = read("src/main/res/xml/coucou_widget_info.xml")
+ assertTrue(info.contains("""android:updatePeriodMillis="0""""))
+ assertTrue(info.contains("""android:widgetCategory="home_screen""""))
+ }
+
+ @Test fun noSurfaceAddsAnythingBeyondTheGlance() {
+ // They draw the Glance and nothing else: no step text, no command, no final answer.
+ for ((name, src) in listOf("widget" to widget, "tile" to tile)) {
+ for (word in listOf("statusText", "finalLine", "steps", ".command", "files")) assertFalse("$name uses $word", src.contains(word))
+ }
+ assertFalse(notifications.substringAfter("private fun ongoing(g: Glance?)").substringBefore("fun updateOngoing").contains("statusText"))
+ }
+
+ @Test fun theOngoingNotificationIsPrivateOnTheLockScreen() {
+ val body = notifications.substringAfter("private fun ongoing(g: Glance?)").substringBefore("fun updateOngoing")
+ assertTrue(body.contains("VISIBILITY_PRIVATE"))
+ assertTrue(body.contains("setPublicVersion"))
+ }
+
+ @Test fun theTileOnlyOpensTheApp() {
+ assertTrue(tile.contains("startActivityAndCollapse"))
+ for (word in listOf("decide", "allow", "answer", "unpair")) assertFalse("tile uses $word", tile.contains(word, ignoreCase = true))
+ }
+
+ @Test fun everyChangeOfThePictureReachesTheSurfaces() {
+ assertTrue(model.substringAfter("private fun refreshIsland()").take(200).contains("pushGlance()"))
+ val push = model.substringAfter("private fun pushGlance()").substringBefore("private fun refreshIsland()")
+ for (call in listOf("notifier.updateOngoing", "GlanceWidget.update", "GlanceTile.requestUpdate")) assertTrue(call, push.contains(call))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/GlanceTest.kt b/android/app/src/test/kotlin/com/coucou/android/GlanceTest.kt
new file mode 100644
index 00000000..38f6ad6b
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/GlanceTest.kt
@@ -0,0 +1,104 @@
+package com.coucou.android
+
+import com.coucou.android.core.Glance
+import com.coucou.android.core.GlanceBuilder
+import com.coucou.android.core.GlanceTone
+import com.coucou.android.link.LinkState
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class GlanceTest {
+ private fun s(id: String, state: BotState, status: String = "") = SessionInfo(id, "", state, status, 0, 0, 0L)
+ private val names = mapOf("a" to "Claude Code", "b" to "Codex", "c" to "Gemini")
+ private fun build(
+ sessions: List<SessionInfo> = emptyList(), approvals: Int = 0, link: LinkState = LinkState.CONNECTED,
+ paired: Boolean = true, desktop: String? = "Léa's PC",
+ ): Glance = GlanceBuilder.build(paired, link, desktop, sessions, approvals) { names[it] ?: "An agent" }
+
+ @Test fun notPairedInvitesToConnect() {
+ val g = build(paired = false)
+ assertEquals("Not paired", g.headline)
+ assertFalse(g.connected)
+ assertEquals(GlanceTone.CALM, g.tone)
+ }
+
+ @Test fun aLostLinkSaysSoAndShowsNoAgents() {
+ val g = build(listOf(s("a", BotState.WORKING)), link = LinkState.DISCONNECTED)
+ assertEquals("Not connected", g.headline)
+ assertTrue(g.lines.isEmpty())
+ assertEquals("Connecting…", build(link = LinkState.CONNECTING).headline)
+ }
+
+ @Test fun idleAndConnected() {
+ val g = build()
+ assertEquals("Connected", g.headline)
+ assertEquals("To Léa's PC", g.detail)
+ assertEquals(GlanceTone.OK, g.tone)
+ }
+
+ @Test fun oneAgentWorking() {
+ val g = build(listOf(s("a", BotState.WORKING)))
+ assertEquals("Claude Code is working", g.headline)
+ assertEquals(GlanceTone.BUSY, g.tone)
+ }
+
+ @Test fun severalAgentsWorkingAreCounted() {
+ val g = build(listOf(s("a", BotState.WORKING), s("b", BotState.THINKING), s("c", BotState.SEARCHING)))
+ assertEquals("3 agents are working", g.headline)
+ }
+
+ @Test fun anApprovalBeatsEverything() {
+ val g = build(listOf(s("a", BotState.ERROR), s("b", BotState.WORKING)), approvals = 2)
+ assertEquals("Waiting for you", g.headline)
+ assertEquals("2 requests to approve", g.detail)
+ assertEquals(2, g.waiting)
+ assertEquals(GlanceTone.ATTENTION, g.tone)
+ }
+
+ @Test fun aQuestionCountsAsWaiting() {
+ val g = build(listOf(s("a", BotState.QUESTION), s("b", BotState.WORKING)))
+ assertEquals("Waiting for your answer", g.headline)
+ assertEquals(1, g.waiting)
+ }
+
+ @Test fun troubleBeatsWork() {
+ val g = build(listOf(s("a", BotState.WORKING), s("b", BotState.ERROR)))
+ assertEquals("An agent needs a look", g.headline)
+ assertEquals("1 agent stopped", g.detail)
+ assertEquals(GlanceTone.TROUBLE, g.tone)
+ }
+
+ @Test fun finishedWhenNothingElseIsGoingOn() {
+ assertEquals("All done", build(listOf(s("a", BotState.FINISHED))).headline)
+ }
+
+ @Test fun linesAreUrgentFirstAndLimited() {
+ val many = listOf(
+ s("a", BotState.IDLE), s("b", BotState.WORKING), s("c", BotState.ERROR),
+ s("a", BotState.FINISHED), s("b", BotState.QUESTION), s("c", BotState.SLEEPING),
+ )
+ val g = build(many)
+ assertEquals(GlanceBuilder.MAX_LINES, g.lines.size)
+ assertEquals(listOf(BotState.QUESTION, BotState.ERROR, BotState.WORKING, BotState.FINISHED), g.lines.map { it.state })
+ }
+
+ @Test fun neitherAStepNorACommandNorAFileNameIsEverShown() {
+ val secret = listOf(
+ s("a", BotState.WORKING, "Edit · /home/me/secret/plan.md"),
+ s("b", BotState.SEARCHING, "Running rm -rf build"),
+ s("c", BotState.THINKING, "token sk-12345"),
+ )
+ val g = build(secret, desktop = null)
+ val everything = (listOf(g.headline, g.detail) + g.lines.flatMap { listOf(it.agent, it.text) }).joinToString("|")
+ for (leak in listOf("secret", "plan.md", "rm -rf", "sk-12345", "/home")) assertFalse(leak, everything.contains(leak))
+ }
+
+ @Test fun workingLinesUseOnlyTheStateWord() {
+ val g = build(listOf(s("a", BotState.WORKING, "Bash"), s("b", BotState.SEARCHING, "Grep"), s("c", BotState.THINKING, "x")))
+ assertEquals(setOf("Working", "Searching", "Thinking"), g.lines.map { it.text }.toSet())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/HomePanelTest.kt b/android/app/src/test/kotlin/com/coucou/android/HomePanelTest.kt
new file mode 100644
index 00000000..f5f8435c
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/HomePanelTest.kt
@@ -0,0 +1,79 @@
+package com.coucou.android
+
+import com.coucou.android.core.HomePanel
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class HomePanelTest {
+ private fun s(id: String, st: BotState) = SessionInfo(id, id, st, "", 0, 0, 0L)
+
+ @Test fun theAgentThatNeedsYouMostIsInTheBigCard() {
+ val list = listOf(s("a", BotState.WORKING), s("b", BotState.APPROVAL), s("c", BotState.ERROR), s("d", BotState.IDLE))
+ assertEquals("b", HomePanel.focus(list, null)!!.pillId)
+ assertEquals("c", HomePanel.focus(list.filter { it.pillId != "b" }, null)!!.pillId)
+ assertEquals("a", HomePanel.focus(listOf(s("d", BotState.IDLE), s("a", BotState.WORKING)), null)!!.pillId)
+ }
+
+ @Test fun onATieTheFirstOneWins() {
+ assertEquals("a", HomePanel.focus(listOf(s("a", BotState.WORKING), s("b", BotState.WORKING)), null)!!.pillId)
+ }
+
+ @Test fun aTappedAgentStaysInTheCardWhileItExists() {
+ val list = listOf(s("a", BotState.APPROVAL), s("b", BotState.IDLE))
+ assertEquals("b", HomePanel.focus(list, "b")!!.pillId)
+ assertEquals("a", HomePanel.focus(list, "gone")!!.pillId)
+ }
+
+ @Test fun noAgentMeansNoFocus() {
+ assertNull(HomePanel.focus(emptyList(), null))
+ assertNull(HomePanel.focus(emptyList(), "a"))
+ }
+
+ @Test fun theOthersExcludeTheFocusAndKeepTheirOrder() {
+ val list = listOf(s("a", BotState.IDLE), s("b", BotState.IDLE), s("c", BotState.IDLE), s("d", BotState.IDLE), s("e", BotState.IDLE))
+ val others = HomePanel.others(list, list[0])
+ assertEquals(listOf("b", "c", "d", "e"), others.map { it.pillId })
+ assertEquals(5, HomePanel.others(list, null).size)
+ }
+
+ @Test fun theLinkAnswersARequestFirstThenPairsThenIsGone() {
+ assertEquals(HomePanel.Link.APPROVAL, HomePanel.link(paired = true, demo = false, hasApproval = true))
+ assertEquals(HomePanel.Link.APPROVAL, HomePanel.link(paired = false, demo = true, hasApproval = true))
+ assertEquals(HomePanel.Link.PAIR, HomePanel.link(paired = false, demo = false, hasApproval = false))
+ // Settings is no longer a link on the card (it has its own button): nothing to show.
+ assertEquals(HomePanel.Link.NONE, HomePanel.link(paired = true, demo = false, hasApproval = false))
+ assertEquals(HomePanel.Link.NONE, HomePanel.link(paired = false, demo = true, hasApproval = false))
+ }
+
+ @Test fun pillColoursBecomeMochiBodies() {
+ val c = HomePanel.rgb("#8AB4F8")!!
+ assertEquals(0x8A / 255.0, c.r, 1e-9)
+ assertEquals(0xB4 / 255.0, c.g, 1e-9)
+ assertEquals(0xF8 / 255.0, c.b, 1e-9)
+ assertNull(HomePanel.rgb("blue"))
+ assertNull(HomePanel.rgb("#12"))
+ assertNull(HomePanel.rgb("#GGGGGG"))
+ }
+
+ @Test fun theCardOpensOnlyWhenThereIsSomethingToShow() {
+ assertTrue(!HomePanel.hasDetails(s("a", BotState.IDLE)))
+ assertTrue(HomePanel.hasDetails(s("a", BotState.IDLE).copy(steps = listOf("x"))))
+ assertTrue(HomePanel.hasDetails(s("a", BotState.IDLE).copy(finalLine = "done")))
+ assertTrue(HomePanel.hasDetails(s("a", BotState.IDLE).copy(project = "app")))
+ assertTrue(!HomePanel.hasDetails(s("a", BotState.IDLE).copy(finalLine = " ", color = "#112233")))
+ }
+
+ @Test fun theUsersColourBeatsTheCatalogsAndTheCatalogIsTheFallback() {
+ assertEquals("#2DD4BF", HomePanel.colorHex(s("agent_gemini", BotState.IDLE).copy(color = "#2DD4BF")))
+ assertEquals("#8AB4F8", HomePanel.colorHex(s("agent_gemini", BotState.IDLE)))
+ assertNull(HomePanel.colorHex(s("not_a_pill", BotState.IDLE)))
+ }
+
+ @Test fun stepsAreListedNewestFirst() {
+ assertEquals(listOf("c", "b", "a"), HomePanel.stepsNewestFirst(s("a", BotState.IDLE).copy(steps = listOf("a", "b", "c"))))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/HomeTextTest.kt b/android/app/src/test/kotlin/com/coucou/android/HomeTextTest.kt
new file mode 100644
index 00000000..c4a05e0b
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/HomeTextTest.kt
@@ -0,0 +1,57 @@
+package com.coucou.android
+
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.ToolLabels
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class HomeTextTest {
+ private fun s(state: BotState, status: String = "", final: String? = null) =
+ SessionInfo("p", "A", state, status, 0, 0, 0L, finalLine = final)
+
+ @Test fun aRawToolNameBecomesASentence() {
+ assertEquals("Running a command", HomeText.line(s(BotState.WORKING, "Bash")))
+ assertEquals("Editing files", HomeText.line(s(BotState.WORKING, "Edit · a.txt")))
+ }
+
+ @Test fun aFinishedAgentShowsItsLastMessage() {
+ assertEquals("Migration applied.", HomeText.line(s(BotState.FINISHED, "Bash", "Migration applied.")))
+ assertEquals("Running a command", HomeText.line(s(BotState.FINISHED, "Bash", " ")))
+ }
+
+ @Test fun onlyAFinishedAgentShowsALastMessage() {
+ assertEquals("Reading files", HomeText.line(s(BotState.WORKING, "Read", "old message")))
+ }
+
+ @Test fun nothingToSayIsNull() {
+ assertNull(HomeText.line(s(BotState.IDLE)))
+ }
+
+ @Test fun requestsReadAsActions() {
+ assertEquals("run a command", ToolLabels.action("Bash"))
+ assertEquals("edit files", ToolLabels.action("multi_edit"))
+ assertEquals("search the web", ToolLabels.action("WebSearch"))
+ assertEquals("list issues", ToolLabels.action("list_issues"))
+ assertEquals("do something", ToolLabels.action(" "))
+ }
+
+ @Test fun theRecentListSaysWhatYouDecided() {
+ assertEquals("Allowed: edit files", HomeText.recent(true, "Edit"))
+ assertEquals("Denied: run a command", HomeText.recent(false, "Bash"))
+ }
+
+ @Test fun runningCountsBusyAgentsOnly() {
+ val all = listOf(s(BotState.WORKING), s(BotState.THINKING), s(BotState.SEARCHING), s(BotState.IDLE), s(BotState.APPROVAL), s(BotState.FINISHED))
+ assertEquals(3, HomeText.running(all))
+ assertEquals(0, HomeText.running(emptyList()))
+ }
+
+ @Test fun aDecisionIsASentenceWithNoCommand() {
+ assertEquals("You allowed Claude Code to run a command", HomeText.decision(true, "Claude Code", "Bash"))
+ assertEquals("You denied Codex to edit files", HomeText.decision(false, "Codex", "Edit"))
+ assertEquals("You allowed an agent to read files", HomeText.decision(true, " ", "Read"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IconSpecTest.kt b/android/app/src/test/kotlin/com/coucou/android/IconSpecTest.kt
new file mode 100644
index 00000000..8a673164
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IconSpecTest.kt
@@ -0,0 +1,44 @@
+package com.coucou.android
+
+import com.coucou.android.core.IconKind
+import com.coucou.android.core.IconShape
+import com.coucou.android.core.IconSpec
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class IconSpecTest {
+ @Test fun everyIconHasADrawing() {
+ for (k in IconKind.entries) assertTrue("$k", IconSpec.shapes(k).isNotEmpty())
+ }
+
+ @Test fun everythingStaysOnTheGridWithRoomForTheStroke() {
+ val margin = IconSpec.STROKE / 2
+ for (k in IconKind.entries) for (v in IconSpec.extent(k)) {
+ assertTrue("$k point $v", v >= margin && v <= IconSpec.GRID - margin)
+ }
+ }
+
+ @Test fun polylinesHavePairsAndAtLeastTwoPoints() {
+ for (k in IconKind.entries) for (s in IconSpec.shapes(k)) if (s is IconShape.Poly) {
+ assertEquals("$k", 0, s.points.size % 2)
+ assertTrue("$k", s.points.size >= 4)
+ }
+ }
+
+ @Test fun noTwoIconsAreTheSameDrawing() {
+ assertEquals(IconKind.entries.size, IconKind.entries.map { IconSpec.shapes(it) }.toSet().size)
+ }
+
+ @Test fun theSettingsIconIsNotASunOrAGear() {
+ // The old gear was a ring with eight spokes. Settings is two rails with two knobs.
+ val s = IconSpec.shapes(IconKind.SLIDERS)
+ assertEquals(2, s.count { it is IconShape.Circle })
+ assertTrue(s.none { it is IconShape.Arc })
+ assertTrue(s.filterIsInstance<IconShape.Poly>().all { p -> p.points[1] == p.points[3] }) // every rail is horizontal
+ }
+
+ @Test fun strokeIsTheSameAsThePc() {
+ assertEquals(1.9, IconSpec.STROKE, 0.0)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IslandLookTest.kt b/android/app/src/test/kotlin/com/coucou/android/IslandLookTest.kt
new file mode 100644
index 00000000..c2d24cc5
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IslandLookTest.kt
@@ -0,0 +1,60 @@
+package com.coucou.android
+
+import com.coucou.android.core.IslandGeometry
+import com.coucou.android.core.PxRect
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * The island on a 720x1600 phone with a small centred camera hole (the Galaxy A12s class). The
+ * hole's rectangle is an assumption (about 56x66 px at the top centre), not a measurement: the real
+ * inset is read from the display at run time.
+ */
+class IslandLookTest {
+ private val density = 1.75f // 720 px wide = about 411 dp
+ private val hole = PxRect(332, 0, 388, 66)
+ private val box = IslandGeometry.place(720, density, hole, statusBarH = 70)
+
+ private fun dp(px: Int) = px / density
+
+ @Test fun theIslandIsCentredOnTheCameraHole() {
+ assertEquals(0, box.centerOffsetX)
+ assertEquals("content starts under the hole", 66, box.topInset)
+ }
+
+ @Test fun theWorkingStripIsNarrow() {
+ assertTrue("working strip ${dp(box.workingW)} dp", dp(box.workingW) in 220f..260f)
+ }
+
+ @Test fun theResultAndRequestCardsAreWiderThanTheStrip() {
+ assertTrue(box.cardW > box.workingW)
+ assertTrue(box.approvalW >= box.cardW)
+ assertTrue("fits the screen with a margin", box.cardW <= 720 - 2 * (12 * density).toInt())
+ }
+
+ @Test fun hiddenItIsJustAboveTheHoleSoItGrowsOutOfIt() {
+ assertTrue("notch ${dp(box.notchWidth)} dp", dp(box.notchWidth) in 40f..70f)
+ assertTrue(box.notchWidth > hole.width)
+ assertTrue(box.notchWidth < box.workingW / 2)
+ }
+
+ @Test fun cornersAreThePCsFourteenAndTwentyTwo() {
+ assertEquals(14, Math.round(dp(box.cornerSmall)))
+ assertEquals(22, Math.round(dp(box.cornerLarge)))
+ }
+
+ @Test fun anOffCentreHoleStillKeepsTheWholeIslandOnScreen() {
+ val right = IslandGeometry.place(720, density, PxRect(600, 0, 656, 66), statusBarH = 70)
+ assertTrue(right.centerOffsetX > 0)
+ assertTrue(right.centerOffsetX + right.approvalW / 2 <= 360)
+ }
+
+ @Test fun theFlaresFitBesideTheIslandOnANarrowPhone() {
+ // 360 dp wide (1080 px at 3.0): island plus a flare on each side stays inside the screen with its margin.
+ val narrow = IslandGeometry.place(1080, 3.0f, PxRect(504, 0, 576, 90), statusBarH = 90)
+ val ear = (IslandGeometry.EAR_DP * 3.0f).toInt()
+ assertTrue(narrow.approvalW + 2 * ear <= 1080 - 2 * (IslandGeometry.MARGIN_DP * 3.0f).toInt())
+ assertEquals(14, IslandGeometry.EAR_DP) // the PC's flare
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IslandMotionTest.kt b/android/app/src/test/kotlin/com/coucou/android/IslandMotionTest.kt
new file mode 100644
index 00000000..c3e71f8f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IslandMotionTest.kt
@@ -0,0 +1,97 @@
+package com.coucou.android
+
+import com.coucou.android.core.Spring
+import com.coucou.android.core.Tracked
+import com.coucou.android.core.closeCurve
+import com.coucou.android.core.cubicBezier
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The island moves like the PC's: windows/src/core/anim.ts. */
+class IslandMotionTest {
+ @Test fun theCloseCurveStartsAtZeroEndsAtOneAndNeverGoesBack() {
+ assertEquals(0.0, closeCurve(0.0), 1e-9)
+ assertEquals(1.0, closeCurve(1.0), 1e-4)
+ var last = -1.0
+ for (i in 0..100) {
+ val v = closeCurve(i / 100.0)
+ assertTrue("monotonic at $i", v >= last - 1e-12)
+ last = v
+ }
+ }
+
+ @Test fun theCloseCurveIsCubicBezierPoint45_0_2_1() {
+ // Reference values of CSS cubic-bezier(.45, 0, .2, 1), computed independently.
+ assertEquals(0.0, closeCurve(0.0), 1e-4)
+ assertEquals(0.5, cubicBezier(0.0, 0.0, 1.0, 1.0)(0.5), 1e-3) // a straight line stays straight
+ assertTrue("slow start", closeCurve(0.1) < 0.1)
+ assertTrue("fast middle then settles", closeCurve(0.5) > 0.5)
+ assertTrue(closeCurve(0.9) > 0.97)
+ }
+
+ @Test fun aSpringGrowsPastItsTargetOnceThenSettles() {
+ val s = Spring(0.0)
+ s.target = 100.0
+ var peak = 0.0
+ repeat(240 * 4) { s.step(1.0 / 60.0 / 4) ; peak = maxOf(peak, s.value) }
+ assertTrue("damping 0.72 overshoots a little: $peak", peak > 100.0 && peak < 125.0)
+ s.step(2.0)
+ assertTrue(s.settled)
+ assertEquals(100.0, s.value, 0.5)
+ }
+
+ @Test fun aSpringIsStableWhenAFrameIsDropped() {
+ val s = Spring(0.0)
+ s.target = 100.0
+ s.step(0.5) // a half second hiccup in one go
+ assertTrue(s.value.isFinite() && s.value in 0.0..200.0)
+ }
+
+ @Test fun growingUsesTheSpringAndShrinkingUsesTheTimedCurve() {
+ val grow = Tracked(10.0)
+ grow.goTo(100.0, 0.0)
+ var now = 0.0
+ var peak = 0.0
+ repeat(120) { now += 16.0; grow.step(0.016, now); peak = maxOf(peak, grow.value) }
+ assertTrue("the spring overshoots", peak > 100.0)
+
+ val shrink = Tracked(100.0)
+ shrink.goTo(0.0, 1000.0)
+ var low = 100.0
+ now = 1000.0
+ repeat(40) { now += 10.0; shrink.step(0.010, now); low = minOf(low, shrink.value) }
+ assertEquals("the curve never overshoots", 0.0, shrink.value, 1e-9)
+ assertTrue(low >= 0.0)
+ }
+
+ @Test fun theCloseCurveTakes340Milliseconds() {
+ val t = Tracked(100.0)
+ t.curveTowards(0.0, 0.0)
+ t.step(0.0, 339.0)
+ assertTrue(t.animating)
+ assertTrue(t.value > 0.0)
+ t.step(0.0, 340.0)
+ assertFalse(t.animating)
+ assertEquals(0.0, t.value, 1e-9)
+ }
+
+ @Test fun aValueThatIsNotMovingCostsNothing() {
+ val t = Tracked(5.0)
+ assertFalse(t.animating)
+ t.step(0.016, 1.0)
+ assertEquals(5.0, t.value, 0.0)
+ }
+
+ @Test fun reopeningWhileItRetractsContinuesFromTheCurrentSize() {
+ val t = Tracked(100.0)
+ t.curveTowards(0.0, 0.0)
+ t.step(0.0, 170.0)
+ val mid = t.value
+ assertTrue(mid in 1.0..99.0)
+ t.goTo(100.0, 170.0) // something new started: grow again from where it is
+ assertEquals(mid, t.value, 1e-9)
+ assertTrue(t.animating)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IslandOverlayTest.kt b/android/app/src/test/kotlin/com/coucou/android/IslandOverlayTest.kt
new file mode 100644
index 00000000..dcbfd0ad
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IslandOverlayTest.kt
@@ -0,0 +1,25 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Guards for how the island over other apps is drawn (the window cannot be rendered in a JVM test, so these read the source). */
+class IslandOverlayTest {
+ private val src = File("src/main/kotlin/com/coucou/android/ui/IslandOverlay.kt").readText()
+
+ @Test fun theRequestCardNamesTheActionAndNeverShowsTheCommand() {
+ val card = src.substringAfter("private fun RequestCard").substringBefore("A window outside any activity")
+ assertTrue(card.contains("R.string.approval_wants"))
+ assertFalse(card.contains("Monospace") || card.contains(".command") || card.contains("s.text,"))
+ assertTrue("Allow keeps its lock note", card.contains("R.string.approval_hint"))
+ }
+
+ @Test fun everyTapStillGoesThroughTheEarlyTapGuard() {
+ for (what in listOf("tap(\"Deny\")", "tap(\"Allow\")", "tap(\"the request header\")", "tap(\"the result card\")", "tap(\"the working strip\")")) {
+ assertTrue(what, src.contains(what))
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IslandPlanTest.kt b/android/app/src/test/kotlin/com/coucou/android/IslandPlanTest.kt
new file mode 100644
index 00000000..2564455c
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IslandPlanTest.kt
@@ -0,0 +1,139 @@
+package com.coucou.android
+
+import com.coucou.android.core.IslandGeometry
+import com.coucou.android.core.IslandPlan
+import com.coucou.android.core.IslandSpec
+import com.coucou.android.core.PxRect
+import com.coucou.android.core.QuietHours
+import com.coucou.android.core.UserSettings
+import com.coucou.android.link.ApprovalRequest
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class IslandPlanTest {
+ private val name = { id: String -> if (id == "a") "Alpha" else "Beta" }
+ private fun s(id: String, st: BotState, text: String = "") = SessionInfo(id, "", st, text, 0, 0, 0L)
+ private val request = ApprovalRequest("a", "f".repeat(64), "Bash", "ls", 0L)
+ private val noon = 12 * 60
+ private val settings = UserSettings()
+
+ @Test fun theIslandOffersAllowOnlyForACommandThatIsShownWhole() {
+ assertTrue(IslandPlan.active(emptyList(), listOf(request), true, name)!!.canAllow)
+ assertFalse(IslandPlan.active(emptyList(), listOf(request.copy(truncated = true)), true, name)!!.canAllow)
+ }
+
+ @Test fun workingShowsWhenAllowedAndNeverWhenNot() {
+ val list = listOf(s("a", BotState.WORKING, "Runs tests"))
+ assertEquals(IslandSpec.Kind.WORKING, IslandPlan.active(list, emptyList(), allowed = true, name)!!.kind)
+ assertNull(IslandPlan.active(list, emptyList(), allowed = false, name))
+ }
+
+ @Test fun thinkingAndSearchingCountAsWorking() {
+ for (st in listOf(BotState.THINKING, BotState.SEARCHING)) {
+ assertEquals(IslandSpec.Kind.WORKING, IslandPlan.active(listOf(s("a", st)), emptyList(), true, name)!!.kind)
+ }
+ }
+
+ @Test fun aRequestComesBeforeAQuestionBeforeWork() {
+ val all = listOf(s("a", BotState.WORKING), s("b", BotState.QUESTION))
+ assertEquals(IslandSpec.Kind.QUESTION, IslandPlan.active(all, emptyList(), true, name)!!.kind)
+ val withRequest = IslandPlan.active(all, listOf(request), true, name)!!
+ assertEquals(IslandSpec.Kind.APPROVAL, withRequest.kind)
+ assertEquals("the island says what kind of action, never the command", "run a command", withRequest.text)
+ assertEquals("Alpha", withRequest.agent)
+ }
+
+ @Test fun idleSleepingFinishedAreNotAnActiveState() {
+ for (st in listOf(BotState.IDLE, BotState.SLEEPING, BotState.FINISHED, BotState.ERROR, BotState.DIZZY)) {
+ assertNull("$st", IslandPlan.active(listOf(s("a", st)), emptyList(), true, name))
+ }
+ }
+
+ @Test fun finishingFlashesOnAChangeOnly() {
+ val done = s("a", BotState.FINISHED, "All done")
+ val spec = IslandPlan.flash(BotState.WORKING, done, settings, noon, true, name)
+ assertEquals(IslandSpec.Kind.FINISHED, spec!!.kind)
+ assertEquals("free text from the computer is not shown", "", spec.text)
+ assertNull("the first picture after connecting", IslandPlan.flash(null, done, settings, noon, true, name))
+ assertNull("the same state again", IslandPlan.flash(BotState.FINISHED, done, settings, noon, true, name))
+ }
+
+ @Test fun errorsAndLimitsFlashToo() {
+ assertEquals(IslandSpec.Kind.ERROR, IslandPlan.flash(BotState.WORKING, s("a", BotState.ERROR), settings, noon, true, name)!!.kind)
+ assertEquals(IslandSpec.Kind.RATELIMIT, IslandPlan.flash(BotState.WORKING, s("a", BotState.RATELIMIT), settings, noon, true, name)!!.kind)
+ }
+
+ @Test fun theUsersSwitchesAreRespected() {
+ val done = s("a", BotState.FINISHED)
+ assertNull("not allowed (switch off, no permission or app on screen)", IslandPlan.flash(BotState.WORKING, done, settings, noon, false, name))
+ assertNull("notice switch off", IslandPlan.flash(BotState.WORKING, done, settings.copy(notifyDone = false), noon, true, name))
+ val quiet = settings.copy(quiet = QuietHours(true, 22 * 60, 8 * 60))
+ assertNull("quiet hours", IslandPlan.flash(BotState.WORKING, done, quiet, 23 * 60, true, name))
+ assertNotNull("outside quiet hours", IslandPlan.flash(BotState.WORKING, done, quiet, noon, true, name))
+ }
+
+ @Test fun workingIsNotGatedByTheFinishedSwitchOrQuietHours() {
+ val list = listOf(s("a", BotState.WORKING))
+ // The user asked: working shows with the overlay; the notice switch and quiet hours govern finished/failed.
+ assertNotNull(IslandPlan.active(list, emptyList(), true, name))
+ }
+
+ @Test fun theIslandNeverShowsWhileCoucouIsOpen() {
+ assertTrue(IslandPlan.allowed(overlayOn = true, permitted = true, appInForeground = false))
+ assertTrue(!IslandPlan.allowed(overlayOn = true, permitted = true, appInForeground = true))
+ assertTrue(!IslandPlan.allowed(overlayOn = false, permitted = true, appInForeground = false))
+ assertTrue(!IslandPlan.allowed(overlayOn = true, permitted = false, appInForeground = false))
+ }
+
+ // ── geometry ────────────────────────────────────────────────────────────
+
+ @Test fun theIslandIsCentredOnTheCameraCutoutAndHangsBelowIt() {
+ // Galaxy A12s: 720 px wide, a centred waterdrop about 70 px wide and 66 px tall.
+ val box = IslandGeometry.place(720, 2f, PxRect(325, 0, 395, 66), statusBarH = 70)
+ assertEquals(0, box.centerOffsetX)
+ assertEquals("content starts under the cut-out", 66, box.topInset)
+ assertTrue(box.workingH > box.topInset)
+ assertTrue(box.cardH > box.workingH && box.approvalH > box.cardH)
+ assertTrue(box.workingW <= 720 && box.approvalW <= 720)
+ }
+
+ @Test fun anOffCentreCutoutMovesTheIslandButItStaysOnScreen() {
+ val left = IslandGeometry.place(720, 2f, PxRect(80, 0, 150, 60), statusBarH = 60)
+ assertTrue(left.centerOffsetX < 0)
+ val maxOffset = (720 - left.approvalW) / 2
+ assertTrue(left.centerOffsetX >= -maxOffset)
+ }
+
+ @Test fun withoutACutoutItHangsFromTheStatusBarAtTheCentre() {
+ val box = IslandGeometry.place(1080, 3f, null, statusBarH = 72)
+ assertEquals(0, box.centerOffsetX)
+ assertEquals(72, box.topInset)
+ }
+
+ @Test fun anEmptyOrBrokenCutoutIsIgnored() {
+ val box = IslandGeometry.place(720, 2f, PxRect(0, 0, 0, 0), statusBarH = 50)
+ assertEquals(50, box.topInset)
+ assertEquals(0, box.centerOffsetX)
+ }
+
+ @Test fun sizesFollowTheKindOfContent() {
+ val box = IslandGeometry.place(720, 2f, null, 48)
+ assertEquals(box.workingW to box.workingH, IslandGeometry.sizeFor(box, IslandSpec.Kind.WORKING))
+ assertEquals(box.approvalW to box.approvalH, IslandGeometry.sizeFor(box, IslandSpec.Kind.APPROVAL))
+ assertEquals(box.cardW to box.cardH, IslandGeometry.sizeFor(box, IslandSpec.Kind.FINISHED))
+ assertEquals(box.cardW to box.cardH, IslandGeometry.sizeFor(box, IslandSpec.Kind.QUESTION))
+ }
+
+ @Test fun theIslandSaysWhatTheAgentDoesNotTheRawToolName() {
+ val w = IslandPlan.active(listOf(s("a", BotState.WORKING, "ask_question")), emptyList(), true, name)!!
+ assertEquals("Asking a question", w.text)
+ val f = IslandPlan.flash(BotState.WORKING, s("a", BotState.FINISHED, "Bash"), settings, noon, true, name)!!
+ assertEquals("Running a command", f.text)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/IslandTimelineTest.kt b/android/app/src/test/kotlin/com/coucou/android/IslandTimelineTest.kt
new file mode 100644
index 00000000..0f3f9a61
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/IslandTimelineTest.kt
@@ -0,0 +1,150 @@
+package com.coucou.android
+
+import com.coucou.android.core.IslandSpec
+import com.coucou.android.core.IslandTimeline
+import com.coucou.android.core.IslandTimeline.Phase
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class IslandTimelineTest {
+ private var now = 1_000.0
+ private val t = IslandTimeline { now }
+
+ private fun spec(kind: IslandSpec.Kind, state: BotState, text: String = "") = IslandSpec(kind, "agent_gemini", "Gemini CLI", state, text)
+ private val working = spec(IslandSpec.Kind.WORKING, BotState.WORKING, "Runs npm test")
+ private val finished = spec(IslandSpec.Kind.FINISHED, BotState.FINISHED, "All done")
+ private val error = spec(IslandSpec.Kind.ERROR, BotState.ERROR, "Build failed")
+ private val limit = spec(IslandSpec.Kind.RATELIMIT, BotState.RATELIMIT)
+ private val approval = spec(IslandSpec.Kind.APPROVAL, BotState.APPROVAL, "Bash: rm -rf x")
+ private val question = spec(IslandSpec.Kind.QUESTION, BotState.QUESTION)
+
+ private fun advance(ms: Double) { now += ms; t.tick() }
+
+ @Test fun nothingIsScheduledWhileHidden() {
+ assertEquals(Phase.HIDDEN, t.phase)
+ assertNull(t.nextDeadline())
+ assertNull(t.current)
+ }
+
+ @Test fun workingOpensTheIslandAndKeepsItOpenWithoutAnyTimer() {
+ t.setActive(working)
+ assertEquals(Phase.OPEN, t.phase)
+ assertEquals(working, t.current)
+ assertNull("no deadline while it works", t.nextDeadline())
+ advance(3_600_000.0)
+ assertEquals(Phase.OPEN, t.phase)
+ }
+
+ @Test fun finishingHoldsTenSecondsThenRetracts() {
+ t.setActive(working)
+ t.setActive(null) // the agent stopped working...
+ t.flash(finished) // ...and finished
+ assertEquals("the island does not retract in between", Phase.OPEN, t.phase)
+ assertEquals(finished, t.current)
+ assertEquals(now + 10_000.0, t.nextDeadline()!!, 0.0)
+
+ advance(9_999.0)
+ assertEquals(Phase.OPEN, t.phase)
+ advance(1.0)
+ assertEquals(Phase.RETRACTING, t.phase)
+ assertEquals("it shrinks around what it showed", finished, t.current)
+ assertEquals(now + 340.0, t.nextDeadline()!!, 0.0)
+
+ advance(340.0)
+ assertEquals(Phase.HIDDEN, t.phase)
+ assertNull(t.current)
+ assertNull(t.nextDeadline())
+ }
+
+ @Test fun errorsAndRateLimitsAlsoWaitTenSeconds() {
+ for (s in listOf(error, limit)) {
+ t.dismiss()
+ t.flash(s)
+ advance(9_000.0)
+ assertEquals(Phase.OPEN, t.phase)
+ advance(1_000.0)
+ assertEquals(Phase.RETRACTING, t.phase)
+ }
+ }
+
+ @Test fun aNewerEventRestartsTheHold() {
+ t.flash(finished)
+ advance(8_000.0)
+ t.flash(error)
+ assertEquals(error, t.current)
+ advance(8_000.0)
+ assertEquals("16 s after the first event but only 8 after the second", Phase.OPEN, t.phase)
+ advance(2_000.0)
+ assertEquals(Phase.RETRACTING, t.phase)
+ }
+
+ @Test fun aRequestOrAQuestionStaysUntilAnsweredOrExpired() {
+ t.setActive(approval)
+ advance(125_000.0)
+ assertEquals("a request has no 10 s limit", Phase.OPEN, t.phase)
+ assertNull(t.nextDeadline())
+ t.setActive(null) // answered, or expired
+ assertEquals(Phase.RETRACTING, t.phase)
+
+ t.dismiss()
+ t.setActive(question)
+ advance(60_000.0)
+ assertEquals(Phase.OPEN, t.phase)
+ }
+
+ @Test fun aRequestOutranksAFinishedNoticeAndTheNoticeStillHoldsAfterwards() {
+ t.flash(finished)
+ advance(2_000.0)
+ t.setActive(approval)
+ assertEquals(approval, t.current)
+ assertNull("a request pins the island", t.nextDeadline())
+ advance(4_000.0)
+ t.setActive(null) // answered after 4 s
+ assertEquals("the finished notice is still inside its 10 s", finished, t.current)
+ assertEquals(Phase.OPEN, t.phase)
+ advance(4_000.0)
+ assertEquals(Phase.RETRACTING, t.phase)
+ }
+
+ @Test fun aNewSessionStartingWhileItRetractsReopensIt() {
+ t.flash(finished)
+ advance(10_000.0)
+ assertEquals(Phase.RETRACTING, t.phase)
+ advance(100.0)
+ t.setActive(working)
+ assertEquals(Phase.OPEN, t.phase)
+ assertEquals(working, t.current)
+ assertNull(t.nextDeadline())
+ advance(1_000.0)
+ assertEquals(Phase.OPEN, t.phase)
+ }
+
+ @Test fun theWindowCanGoOnceTheRetractIsFinished() {
+ t.flash(finished)
+ advance(10_000.0)
+ t.retractFinished()
+ assertEquals(Phase.HIDDEN, t.phase)
+ assertNull(t.nextDeadline())
+ }
+
+ @Test fun dismissClosesAtOnceAndForgetsEverything() {
+ t.setActive(working)
+ t.flash(finished)
+ t.dismiss()
+ assertEquals(Phase.HIDDEN, t.phase)
+ assertNull(t.current)
+ assertNull(t.nextDeadline())
+ advance(60_000.0)
+ assertEquals("a forgotten notice must not come back", Phase.HIDDEN, t.phase)
+ }
+
+ @Test fun workingWinsOverAFinishedNoticeFromAnotherSession() {
+ t.flash(finished)
+ t.setActive(working)
+ assertEquals(working, t.current)
+ assertTrue(t.nextDeadline() == null)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/JvmNameClashTest.kt b/android/app/src/test/kotlin/com/coucou/android/JvmNameClashTest.kt
new file mode 100644
index 00000000..07830bd8
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/JvmNameClashTest.kt
@@ -0,0 +1,31 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Kotlin turns `var x` into `setX`, so a function with that name in the same class is a compile error ("platform
+ * declaration clash") that only Gradle shows. Twice it cost a red CI run; this finds it on the JVM.
+ */
+class JvmNameClashTest {
+ @Test fun noFunctionSharesTheNameOfAPropertySetter() {
+ val dir = File("src/main/kotlin/com/coucou/android")
+ val bad = ArrayList<String>()
+ for (f in dir.walkTopDown().filter { it.extension == "kt" }) {
+ val text = f.readText()
+ // A `private var` or one with `private set` has no setter method, so it cannot clash.
+ val lines = text.lines()
+ val vars = lines.indices.mapNotNull { i ->
+ val m = Regex("""^\s*((?:internal|public|override|lateinit|@\w+)\s+)*var\s+([a-z][A-Za-z0-9]*)\b""").find(lines[i]) ?: return@mapNotNull null
+ val privateSet = lines[i].contains("private set") || lines.getOrNull(i + 1)?.trim() == "private set"
+ if (privateSet) null else m.groupValues[2]
+ }.toSet()
+ for (name in vars) {
+ val setter = "set" + name.replaceFirstChar { it.uppercase() }
+ if (Regex("""\bfun\s+$setter\s*\(""").containsMatchIn(text)) bad.add("${f.name}: var $name and fun $setter")
+ }
+ }
+ assertTrue(bad.toString(), bad.isEmpty())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/KeepAliveSourceTest.kt b/android/app/src/test/kotlin/com/coucou/android/KeepAliveSourceTest.kt
new file mode 100644
index 00000000..3b95c52a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/KeepAliveSourceTest.kt
@@ -0,0 +1,73 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** How the link is kept alive while the phone sleeps, checked where a unit test can see it: the wiring and the permissions. */
+class KeepAliveSourceTest {
+ private fun src(path: String) = File("src/main/kotlin/com/coucou/android/$path").readText()
+ private val manifest get() = File("src/main/AndroidManifest.xml").readText()
+
+ @Test fun theAlarmUsesAllowWhileIdleAndNoExactAlarmPermission() {
+ val alarm = src("app/KeepAlive.kt")
+ assertTrue(alarm.contains("setAndAllowWhileIdle"))
+ assertFalse("no exact alarms: they need a permission Google restricts", alarm.contains("setExact") || manifest.contains("SCHEDULE_EXACT_ALARM") || manifest.contains("USE_EXACT_ALARM"))
+ assertTrue(alarm.contains("AlarmManager.ELAPSED_REALTIME_WAKEUP"))
+ }
+
+ @Test fun theWakeLockHasATimeoutAndIsTakenInOnePlaceOnly() {
+ val all = File("src/main/kotlin").walkTopDown().filter { it.extension == "kt" }.joinToString("\n") { it.readText() }
+ assertEquals("one wake lock in the whole app", 1, Regex("""newWakeLock\(""").findAll(all).count())
+ assertTrue(src("app/KeepAlive.kt").contains("acquire(KeepAlivePolicy.WAKE_LOCK_MS)"))
+ assertFalse("never held without a timeout", Regex("""wakeLock\w*\.acquire\(\)""", RegexOption.IGNORE_CASE).containsMatchIn(all))
+ assertTrue(manifest.contains("android.permission.WAKE_LOCK"))
+ }
+
+ @Test fun theReceiverIsNotExportedSoOnlyOurAlarmCanStartIt() {
+ assertTrue(Regex("""<receiver\s+android:name="\.app\.KeepAliveReceiver"\s+android:exported="false"\s*/>""").containsMatchIn(manifest))
+ }
+
+ @Test fun theAlarmAndTheWatchersLiveExactlyAsLongAsThePairing() {
+ val model = src("app/AppModel.kt")
+ val connect = model.substringAfter("private fun connect(p: PairingPayload)").substringBefore("/** The saved address")
+ assertTrue(connect.contains("screenWatch.start()") && connect.contains("KeepAliveAlarm.arm(context)"))
+ val stop = model.substringAfter("private fun stopLink()").substringBefore("notifier.cancelAllStatus()")
+ assertTrue(stop.contains("screenWatch.stop()") && stop.contains("KeepAliveAlarm.cancel(context)"))
+ // The alarm chain ends by itself when there is no pairing any more.
+ assertTrue(model.substringAfter("fun keepAliveTick()").substringBefore("}").contains("if (mode != Mode.PAIRED) return"))
+ }
+
+ @Test fun everyWakeUpGoesThroughThePolicy() {
+ val model = src("app/AppModel.kt")
+ assertTrue(model.contains("ReconnectPolicy.decide("))
+ assertTrue(model.contains("onWake(Wake.NEW_NETWORK)") && model.contains("onWake(Wake.SCREEN_ON)") && model.contains("onWake(Wake.ALARM)"))
+ assertTrue("a network that appears is looked at, not only Wi-Fi", src("app/NetworkWatch.kt").contains("onAvailable(network: Network) { changed(); onNewNetwork() }"))
+ }
+
+ @Test fun theLinkAsksForAPongAtEveryCheckAndKeepsTheSystemsOwnProbeToo() {
+ val client = src("link/LinkClient.kt")
+ assertTrue(client.contains("override fun checkNow()"))
+ assertTrue(client.contains("s.keepAlive = true"))
+ }
+
+ @Test fun theBatterySettingIsOnlyEverOpenedNeverChangedByTheApp() {
+ val ui = src("ui/ConnectionHelp.kt")
+ assertTrue(ui.contains("ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS") && ui.contains("ACTION_APPLICATION_DETAILS_SETTINGS"))
+ assertFalse("the direct request needs a permission Google restricts", manifest.contains("REQUEST_IGNORE_BATTERY_OPTIMIZATIONS") || ui.contains("ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"))
+ }
+
+ @Test fun cantConnectIsInTheComputerPanelOnlyWhenPaired() {
+ val settings = src("ui/SettingsScreens.kt")
+ val paired = settings.substringAfter("Mode.PAIRED -> {").substringBefore("Mode.DEMO ->")
+ assertTrue(paired.contains("LinkRow(stringResource(R.string.diag_title), onDiagnostics)"))
+ assertFalse(settings.substringAfter("Mode.DEMO ->").substringBefore("Mode.NONE").contains("diag_title"))
+ }
+
+ @Test fun theDiagnosticsScreenIsNotSecretButTheReportMasksTheAddress() {
+ assertTrue(src("app/AppModel.kt").contains("Diagnostics.maskHost(it.host)"))
+ assertFalse(src("ui/DiagnosticsScreen.kt").contains("p.token") || src("ui/DiagnosticsScreen.kt").contains("certSha256"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/LicencesTest.kt b/android/app/src/test/kotlin/com/coucou/android/LicencesTest.kt
new file mode 100644
index 00000000..0e776b0b
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/LicencesTest.kt
@@ -0,0 +1,78 @@
+package com.coucou.android
+
+import com.coucou.android.core.Licences
+import com.coucou.android.core.Nav
+import com.coucou.android.core.Screen
+import com.coucou.android.core.Tab
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Settings > About > Licences: the texts that ship are the real ones, every library in the build is covered, and the screen is reachable. */
+class LicencesTest {
+ private fun asset(name: String) = File("src/main/assets/licenses/$name").readText()
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+
+ @Test fun theMitTextIsTheRepositorysLicenceFileWord_for_word() {
+ assertEquals(ReferenceFiles.file("LICENSE").readText(), asset("MIT.txt"))
+ assertTrue(asset("MIT.txt").contains("Copyright (c) 2026 Louis Raillé"))
+ assertTrue(asset("MIT.txt").contains("Permission is hereby granted, free of charge"))
+ assertTrue(asset("MIT.txt").contains("THE SOFTWARE IS PROVIDED \"AS IS\""))
+ }
+
+ @Test fun theApacheTextIsTheWholeLicence() {
+ val a = asset("Apache-2.0.txt")
+ for (part in listOf(
+ "Apache License", "Version 2.0, January 2004", "TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION", "1. Definitions.",
+ "Grant of Copyright License", "Grant of Patent License", "Redistribution.", "Disclaimer of Warranty", "Limitation of Liability",
+ "END OF TERMS AND CONDITIONS", "APPENDIX: How to apply the Apache License to your work.",
+ )) assertTrue("missing: $part", a.contains(part))
+ }
+
+ @Test fun theNoticesNameWhoOwnsWhatAndTheArtworkIsNotMit() {
+ val n = asset("NOTICES.txt")
+ assertTrue(n.contains("part of Coucou by Louis Raillé"))
+ assertTrue(n.contains("https://github.com/Louis-CFM/coucou"))
+ assertTrue(n.contains("released under the MIT License"))
+ assertTrue(n.contains("NOT covered by the MIT License"))
+ assertTrue(n.contains("LICENSE-ASSETS.md"))
+ assertTrue(n.contains("written permission"))
+ assertTrue(n.contains("ZXing Core 3.5.3") && n.contains("Apache License, Version 2.0"))
+ assertTrue(n.contains("Android Open Source Project") && n.contains("JetBrains"))
+ }
+
+ @Test fun theZxingVersionInTheNoticeIsTheOneInTheBuild() {
+ val v = Regex("""com\.google\.zxing:core:([0-9.]+)""").find(File("build.gradle.kts").readText())!!.groupValues[1]
+ assertTrue("NOTICES.txt names ZXing Core $v", asset("NOTICES.txt").contains("ZXing Core $v"))
+ }
+
+ @Test fun everyLibraryInTheBuildIsCoveredByANotice() {
+ val groups = Regex("""implementation\("([^":]+):""").findAll(File("build.gradle.kts").readText()).map { it.groupValues[1] }.toSet()
+ val covered = setOf("androidx.activity", "androidx.lifecycle", "androidx.compose.material3", "androidx.compose.ui", "androidx.camera", "com.google.zxing")
+ assertEquals("a new dependency needs a line in NOTICES.txt and in this list", covered, groups)
+ }
+
+ @Test fun theScreenShowsTheThreeFilesInOrder() {
+ assertEquals(listOf("NOTICES.txt", "MIT.txt", "Apache-2.0.txt"), Licences.FILES)
+ for (f in Licences.FILES) assertTrue("$f is bundled", File("src/main/assets/licenses/$f").length() > 500)
+ val text = Licences.FILES.joinToString("\n\n") { asset(it) }
+ val p = Licences.paragraphs(text)
+ assertTrue(p.size > 50)
+ assertTrue(p.none { it.isBlank() })
+ // nothing is lost by cutting it into blocks
+ assertEquals(text.filterNot { it.isWhitespace() }, p.joinToString("").filterNot { it.isWhitespace() })
+ }
+
+ @Test fun licencesIsOneTapFromAboutAndBackGoesToSettings() {
+ assertEquals(Screen.SETTINGS, Nav.back(Screen.LICENCES))
+ assertEquals(Tab.SETTINGS, Nav.tabOf(Screen.LICENCES))
+ assertFalse(Nav.barVisible(Screen.LICENCES, false))
+ val settings = src("ui/SettingsScreens.kt")
+ assertTrue(settings.substringAfter("settings_section_about").contains("LinkRow(stringResource(R.string.licences_title), onLicences)"))
+ assertTrue(src("MainActivity.kt").contains("Screen.LICENCES -> LicencesScreen("))
+ // it reads the bundled files and says nothing of its own
+ assertTrue(src("ui/LicencesScreen.kt").contains("licenses/\$name"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/MarkdownLiteTest.kt b/android/app/src/test/kotlin/com/coucou/android/MarkdownLiteTest.kt
new file mode 100644
index 00000000..8da9dc6d
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/MarkdownLiteTest.kt
@@ -0,0 +1,74 @@
+package com.coucou.android
+
+import com.coucou.android.core.MarkdownLite
+import com.coucou.android.core.MdBlock
+import com.coucou.android.core.MdSpan
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class MarkdownLiteTest {
+ private fun plain(vararg t: String) = t.map { MdSpan(it) }
+
+ @Test fun paragraphsAreSeparatedByBlankLines() {
+ val b = MarkdownLite.parse("First line\nstill first\n\nSecond")
+ assertEquals(listOf(MdBlock.Para(plain("First line\nstill first")), MdBlock.Para(plain("Second"))), b)
+ }
+
+ @Test fun boldAndInlineCode() {
+ assertEquals(
+ listOf(MdSpan("Use "), MdSpan("soft reset", bold = true), MdSpan(" with "), MdSpan("git reset", code = true), MdSpan(".")),
+ MarkdownLite.inline("Use **soft reset** with `git reset`."),
+ )
+ }
+
+ @Test fun anUnfinishedMarkerStaysAsTheCharactersItIs() {
+ // Half an answer: "**bol" has no partner yet.
+ assertEquals(plain("a **bol"), MarkdownLite.inline("a **bol"))
+ assertEquals(plain("a `co"), MarkdownLite.inline("a `co"))
+ assertEquals(plain("****"), MarkdownLite.inline("****"))
+ assertEquals(plain("``"), MarkdownLite.inline("``"))
+ }
+
+ @Test fun bulletsWithDashStarOrDot() {
+ val b = MarkdownLite.parse("- one\n* two **b**\n• three\n-not a bullet")
+ assertEquals(MdBlock.Bullet(plain("one")), b[0])
+ assertEquals(MdBlock.Bullet(listOf(MdSpan("two "), MdSpan("b", bold = true))), b[1])
+ assertEquals(MdBlock.Bullet(plain("three")), b[2])
+ assertEquals(MdBlock.Para(plain("-not a bullet")), b[3])
+ }
+
+ @Test fun fencedCodeIsKeptAsItIsAndNothingInsideIsStyled() {
+ val b = MarkdownLite.parse("Before\n```kotlin\nval a = **x**\n indented\n```\nAfter")
+ assertEquals(
+ listOf(MdBlock.Para(plain("Before")), MdBlock.Code("val a = **x**\n indented"), MdBlock.Para(plain("After"))),
+ b,
+ )
+ }
+
+ @Test fun anUnfinishedFenceRunsToTheEndWhileTheAnswerIsStillArriving() {
+ assertEquals(listOf(MdBlock.Code("line1\nline2")), MarkdownLite.parse("```\nline1\nline2"))
+ }
+
+ @Test fun headingsBecomeBoldLines() {
+ assertEquals(listOf(MdBlock.Para(listOf(MdSpan("Title", bold = true)))), MarkdownLite.parse("## Title"))
+ assertEquals(listOf(MdBlock.Para(plain("#hashtag"))), MarkdownLite.parse("#hashtag"))
+ }
+
+ @Test fun linksImagesAndHtmlStayPlainText() {
+ val text = "[x](https://evil.example) ![i](http://a/b.png) <script>alert(1)</script>"
+ assertEquals(listOf(MdBlock.Para(plain(text))), MarkdownLite.parse(text))
+ }
+
+ @Test fun windowsLineEndingsAndEmptyInput() {
+ assertEquals(listOf(MdBlock.Para(plain("a\nb"))), MarkdownLite.parse("a\r\nb"))
+ assertEquals(emptyList<MdBlock>(), MarkdownLite.parse(""))
+ assertEquals(emptyList<MdBlock>(), MarkdownLite.parse("\n\n \n"))
+ }
+
+ @Test fun neverThrowsOnOddInput() {
+ for (s in listOf("```", "``` ```", "**", "`", "- ", "-", "#", "# ", "\u0000", "a".repeat(100_000))) MarkdownLite.parse(s)
+ assertTrue(true)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/MochiConstTest.kt b/android/app/src/test/kotlin/com/coucou/android/MochiConstTest.kt
new file mode 100644
index 00000000..8154460e
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/MochiConstTest.kt
@@ -0,0 +1,48 @@
+package com.coucou.android
+
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.EyeShape
+import com.coucou.android.mochi.MochiConst
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Test
+
+/** Checks the state table against windows/src/mochi/engine.ts, the reference implementation. */
+class MochiConstTest {
+ private val src = ReferenceFiles.read("windows/src/mochi/engine.ts")
+
+ @Test fun stateColoursMatchReference() {
+ val block = src.substringAfter("const C = {").substringBefore("};")
+ val re = Regex("""(\w+):\s*\[([\d.]+),\s*([\d.]+),\s*([\d.]+)]""")
+ val ref = re.findAll(block).associate { it.groupValues[1] to Triple(it.groupValues[2], it.groupValues[3], it.groupValues[4]) }
+ assertEquals(11, ref.size)
+ for (s in BotState.entries) {
+ val (r, g, b) = ref.getValue(s.key)
+ val c = MochiConst.STATES.getValue(s).color
+ assertEquals("${s.key}.r", r.toDouble(), c.r, 1e-9)
+ assertEquals("${s.key}.g", g.toDouble(), c.g, 1e-9)
+ assertEquals("${s.key}.b", b.toDouble(), c.b, 1e-9)
+ }
+ }
+
+ @Test fun stateTintsAndEyesMatchReference() {
+ val block = src.substringAfter("export const BOT_STATES").substringBefore("/** State")
+ val re = Regex("""(\w+): \{ \.\.\.base, color: C\.\w+, tint: ([\d.]+), eye: "(\w+)"""")
+ val rows = re.findAll(block).toList()
+ assertEquals(11, rows.size)
+ for (m in rows) {
+ val state = BotState.entries.first { it.key == m.groupValues[1] }
+ val cfg = MochiConst.STATES.getValue(state)
+ assertEquals(state.key, m.groupValues[2].toDouble(), cfg.tint, 1e-9)
+ assertEquals(state.key, EyeShape.valueOf(m.groupValues[3].uppercase()), cfg.eye)
+ }
+ }
+
+ @Test fun stateSoundsMatchReferenceAndFilesExist() {
+ val block = src.substringAfter("export const STATE_SOUND").substringBefore("};")
+ val ref = Regex("""(\w+): "(\w+)"""").findAll(block).associate { it.groupValues[1] to it.groupValues[2] }
+ for ((state, sound) in MochiConst.STATE_SOUND) assertEquals(ref[state.key], sound)
+ assertEquals(ref.size, MochiConst.STATE_SOUND.size)
+ for (sound in ref.values) assertNotNull(ReferenceFiles.file("NotchBuddy/Resources/sounds/$sound.wav").takeIf { it.exists() })
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/MochiEngineTest.kt b/android/app/src/test/kotlin/com/coucou/android/MochiEngineTest.kt
new file mode 100644
index 00000000..ad22039d
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/MochiEngineTest.kt
@@ -0,0 +1,188 @@
+package com.coucou.android
+
+import com.coucou.android.core.Ease
+import com.coucou.android.mochi.BotEmote
+import com.coucou.android.mochi.BotState
+import com.coucou.android.mochi.EyeShape
+import com.coucou.android.mochi.MochiEngine
+import com.coucou.android.mochi.MochiGeometry
+import com.coucou.android.mochi.ParticleType
+import com.coucou.android.mochi.Prop
+import com.coucou.android.mochi.SoundSink
+import com.coucou.android.mochi.TweenKey
+import kotlin.math.abs
+import kotlin.math.pow
+import kotlin.random.Random
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class MochiEngineTest {
+ private class Clock { var ms = 10_000.0 }
+
+ private fun engine(clock: Clock, sounds: MutableList<String> = mutableListOf()) =
+ MochiEngine({ clock.ms }, Random(1), SoundSink { sounds.add(it) })
+
+ /** Advances the clock in 16 ms frames, as a 60 fps host would. */
+ private fun MochiEngine.run(clock: Clock, ms: Int) {
+ repeat(ms / 16) { clock.ms += 16; update(0.016) }
+ }
+
+ @Test fun easingsHitEndpoints() {
+ for (f in listOf(Ease.out, Ease.inOut, Ease.back, Ease.lin, Ease.easeIn)) {
+ assertEquals(0.0, f(0.0), 1e-9)
+ assertEquals(1.0, f(1.0), 1e-9)
+ }
+ assertEquals(0.5, Ease.inOut(0.5), 1e-9)
+ assertTrue("back overshoots", Ease.back(0.8) > 1.0)
+ }
+
+ @Test fun bodyIsASuperellipseOfExponent2_7() {
+ val rx = 1.14
+ val ry = 0.88
+ for (p in MochiGeometry.bodyPoints(rx, ry, 1.0, 0.0)) {
+ val v = abs(p.x / rx).pow(2.7) + abs(p.y / ry).pow(2.7)
+ assertEquals(1.0, v, 1e-6)
+ }
+ val first = MochiGeometry.bodyPoints(rx, ry, 1.0, 0.0).first()
+ assertEquals(rx, first.x, 1e-9)
+ assertEquals(0.0, first.y, 1e-9)
+ }
+
+ @Test fun fullMorphGivesTheMailboxOutline() {
+ val pts = MochiGeometry.bodyPoints(1.14, 0.88, 1.0, 1.0)
+ assertEquals(MochiGeometry.BODY_SEGMENTS + 1, pts.size)
+ // The box is 1.0 wide and 0.94 tall (tw, th in engine.ts).
+ assertTrue(pts.all { abs(it.x) <= 1.0 + 1e-6 && abs(it.y) <= 0.94 + 1e-6 })
+ assertEquals(1.0, pts.first().x, 1e-9)
+ }
+
+ @Test fun tweenRunsKeysInOrderAndLocksTheProperty() {
+ val clock = Clock()
+ val e = engine(clock)
+ var done = false
+ e.anim(Prop.OX, listOf(TweenKey(1.0, 100.0, Ease.lin), TweenKey(0.0, 100.0, Ease.lin))) { done = true }
+ clock.ms += 50; e.update(0.05)
+ assertEquals(0.5, e.ox, 1e-9)
+ clock.ms += 50; e.update(0.05)
+ assertEquals(1.0, e.ox, 1e-9)
+ clock.ms += 100; e.update(0.1)
+ assertEquals(0.0, e.ox, 1e-9)
+ assertTrue(done)
+ }
+
+ @Test fun settingAStateCopiesItsConfig() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setState(BotState.APPROVAL)
+ assertEquals(EyeShape.WIDE, e.cfg.eye)
+ assertEquals(0.78, e.tint, 1e-9)
+ e.run(clock, 600)
+ assertEquals(1.0, e.badgeS, 0.01)
+ assertEquals(com.coucou.android.mochi.BadgeKind.BANG, e.badge?.kind)
+ }
+
+ @Test fun colourEasesTowardsTheStateColour() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setState(BotState.ERROR)
+ e.run(clock, 3000)
+ assertEquals(e.colT.r, e.col.r, 0.01)
+ assertEquals(e.colT.g, e.col.g, 0.01)
+ }
+
+ @Test fun loveEmotePutsHeartsInTheEyesAndEmitsHearts() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.triggerEmote(BotEmote.LOVE, 1.8)
+ assertEquals(EyeShape.HEART, e.eyeOverride)
+ assertEquals(4, e.particles.count { it.type == ParticleType.HEART })
+ e.run(clock, 2000)
+ assertNull("override expires", e.eyeOverride)
+ }
+
+ @Test fun permanentEmoteSticksUntilCleared() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setPermanentEmote(BotEmote.HAPPY)
+ e.run(clock, 5000)
+ assertEquals(EyeShape.HAPPY, e.eyeOverride)
+ e.setPermanentEmote(null)
+ e.run(clock, 100)
+ assertNull(e.eyeOverride)
+ }
+
+ @Test fun threeSlapsWithin1_7sMakeMochiDizzy() {
+ val clock = Clock()
+ val sounds = mutableListOf<String>()
+ val e = engine(clock, sounds)
+ var dizzy = false
+ e.onDizzy = { dizzy = true }
+ e.slap(); clock.ms += 300; e.update(0.3)
+ e.slap(); clock.ms += 300; e.update(0.3)
+ assertFalse(dizzy)
+ e.slap()
+ assertTrue(dizzy)
+ assertTrue(sounds.contains("slap"))
+ }
+
+ @Test fun slapsSpacedOutDoNotAccumulate() {
+ val clock = Clock()
+ val e = engine(clock)
+ var dizzy = false
+ e.onDizzy = { dizzy = true }
+ repeat(3) { e.slap(); clock.ms += 2000; e.update(2.0) }
+ assertFalse(dizzy)
+ }
+
+ @Test fun greetWavesThenLowersItsHands() {
+ val clock = Clock()
+ val sounds = mutableListOf<String>()
+ val e = engine(clock, sounds)
+ e.greet()
+ e.run(clock, 800)
+ assertTrue(e.hands > 0.9)
+ assertTrue(sounds.contains("greet"))
+ e.run(clock, 1600)
+ assertEquals(0.0, e.hands, 0.01)
+ }
+
+ @Test fun interruptedGreetDoesNotRaiseHandsLater() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.greet()
+ e.interruptGreet()
+ e.run(clock, 2500)
+ assertEquals(0.0, e.hands, 0.01)
+ }
+
+ @Test fun sleepingBreathesAndEmitsZs() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setState(BotState.SLEEPING)
+ e.run(clock, 3000)
+ assertTrue(e.particles.any { it.type == ParticleType.Z })
+ assertTrue(e.busy)
+ }
+
+ @Test fun idleSettlesAndStopsBeingBusy() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.run(clock, 10_000)
+ assertFalse("idle Mochi should let the frame loop sleep", e.busy)
+ }
+
+ @Test fun gulpOpensThenClosesTheSlot() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.animateMorph(1.0, 10.0)
+ e.gulp()
+ e.run(clock, 300)
+ assertTrue(e.slotH > 0.1)
+ e.run(clock, 2500)
+ assertEquals(0.0, e.slotH, 0.01)
+ assertFalse(e.isChewing)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/NavigationTest.kt b/android/app/src/test/kotlin/com/coucou/android/NavigationTest.kt
new file mode 100644
index 00000000..a7addf1f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/NavigationTest.kt
@@ -0,0 +1,58 @@
+package com.coucou.android
+
+import com.coucou.android.core.Nav
+import com.coucou.android.core.Screen
+import com.coucou.android.core.Tab
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class NavigationTest {
+ @Test fun theBarAlwaysHasHomeChatAndSettingsInThatOrder() {
+ assertEquals(listOf(Tab.HOME, Tab.CHAT, Tab.SETTINGS), Nav.tabs())
+ }
+
+ @Test fun theBarShowsOnTheThreeRootsOnly() {
+ for (s in listOf(Screen.HOME, Screen.CHAT, Screen.SETTINGS)) assertTrue("$s", Nav.barVisible(s, keyboardOpen = false))
+ for (s in listOf(Screen.HISTORY, Screen.GALLERY, Screen.DIAGNOSTICS, Screen.LICENCES, Screen.SESSION, Screen.SCAN)) assertFalse("$s", Nav.barVisible(s, false))
+ }
+
+ @Test fun theBarHidesWhileTheKeyboardIsOpen() {
+ for (s in Screen.entries) assertFalse("$s", Nav.barVisible(s, keyboardOpen = true))
+ }
+
+ @Test fun backGoesUpOneLevelAndLeavesFromHome() {
+ assertNull(Nav.back(Screen.HOME))
+ assertEquals(Screen.HOME, Nav.back(Screen.CHAT))
+ assertEquals(Screen.HOME, Nav.back(Screen.SETTINGS))
+ assertEquals(Screen.HOME, Nav.back(Screen.SESSION))
+ assertEquals(Screen.HOME, Nav.back(Screen.SCAN))
+ assertEquals(Screen.SETTINGS, Nav.back(Screen.HISTORY))
+ assertEquals(Screen.SETTINGS, Nav.back(Screen.GALLERY))
+ assertEquals(Screen.SETTINGS, Nav.back(Screen.DIAGNOSTICS))
+ }
+
+ @Test fun backAlwaysReachesHomeAndNeverLoops() {
+ for (start in Screen.entries) {
+ var s = start
+ var steps = 0
+ while (true) {
+ s = Nav.back(s) ?: break
+ assertTrue("loop from $start", ++steps < 10)
+ }
+ assertEquals("from $start", Screen.HOME, s)
+ }
+ }
+
+ @Test fun pagesBelowSettingsKeepSettingsHighlighted() {
+ for (s in listOf(Screen.SETTINGS, Screen.HISTORY, Screen.GALLERY, Screen.DIAGNOSTICS)) assertEquals(Tab.SETTINGS, Nav.tabOf(s))
+ assertNull(Nav.tabOf(Screen.SCAN))
+ assertNull(Nav.tabOf(Screen.SESSION))
+ }
+
+ @Test fun everyTabLeadsToItsOwnScreen() {
+ for (t in Tab.entries) assertEquals(t, Nav.tabOf(Nav.screenOf(t)))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/OverlayPolicyTest.kt b/android/app/src/test/kotlin/com/coucou/android/OverlayPolicyTest.kt
new file mode 100644
index 00000000..3082d081
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/OverlayPolicyTest.kt
@@ -0,0 +1,81 @@
+package com.coucou.android
+
+import com.coucou.android.core.OverlayChoice
+import com.coucou.android.core.OverlayPolicy
+import com.coucou.android.core.WishStore
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class OverlayPolicyTest {
+ @Test fun onlyShownWhenWantedPermittedAndYouAreElsewhere() {
+ assertTrue(OverlayPolicy.shouldShow(enabled = true, permitted = true, appInForeground = false))
+ assertFalse(OverlayPolicy.shouldShow(enabled = false, permitted = true, appInForeground = false))
+ assertFalse(OverlayPolicy.shouldShow(enabled = true, permitted = false, appInForeground = false))
+ assertFalse(OverlayPolicy.shouldShow(enabled = true, permitted = true, appInForeground = true))
+ }
+
+ @Test fun theReasonItStaysAwayIsNamed() {
+ assertEquals("switch is off", OverlayPolicy.blocker(false, true, false))
+ assertTrue(OverlayPolicy.blocker(true, false, false)!!.contains("not allowed"))
+ assertEquals("the app is on screen", OverlayPolicy.blocker(true, true, true))
+ assertEquals(null, OverlayPolicy.blocker(true, true, false))
+ }
+
+ private class Memory : WishStore {
+ var saved = false
+ var writes = 0
+ override fun read() = saved
+ override fun write(on: Boolean) { saved = on; writes++ }
+ }
+
+ @Test fun theWishIsSavedAtTheTapEvenIfThePermissionIsNotThereYet() {
+ val disk = Memory()
+ OverlayChoice(disk).choose(true) // tap; Android now opens its settings screen
+ assertTrue(disk.saved)
+ // Android killed and restarted the app while the user was in Settings: a new object, same disk.
+ val afterRestart = OverlayChoice(disk)
+ assertTrue(afterRestart.wished)
+ assertFalse(afterRestart.active(permitted = false)) // still waiting for the system permission
+ assertTrue(afterRestart.active(permitted = true)) // granted: works without another tap
+ }
+
+ @Test fun grantingThePermissionLaterFromAndroidSettingsIsEnough() {
+ val choice = OverlayChoice(Memory().apply { saved = true })
+ var permitted = false
+ assertFalse(choice.active(permitted))
+ permitted = true // the user allowed it in Android's own settings
+ assertTrue(choice.active(permitted))
+ }
+
+ @Test fun switchingOffIsRememberedAndNeverShowsAgain() {
+ val disk = Memory().apply { saved = true }
+ val choice = OverlayChoice(disk)
+ choice.choose(false)
+ assertFalse(OverlayChoice(disk).active(permitted = true))
+ }
+
+ @Test fun withThePillOnScreenTheNotificationIsQuiet() {
+ // Regression: the expanded pill and Android's heads-up notification overlapped at the top.
+ assertEquals(OverlayPolicy.ApprovalAlert.QUIET, OverlayPolicy.approvalAlert(pillShown = true))
+ assertEquals(OverlayPolicy.ApprovalAlert.HEADS_UP, OverlayPolicy.approvalAlert(pillShown = false))
+ }
+
+ @Test fun theHeadsUpComesBackWhenThePillCannotShow() {
+ for ((enabled, permitted, foreground) in listOf(
+ Triple(false, true, false), Triple(true, false, false), Triple(true, true, true),
+ )) {
+ val pill = OverlayPolicy.shouldShow(enabled, permitted, foreground)
+ assertEquals(OverlayPolicy.ApprovalAlert.HEADS_UP, OverlayPolicy.approvalAlert(pill))
+ }
+ }
+
+ @Test fun aTapInTheFirstMomentsIsIgnored() {
+ // Regression: a tap meant for the app underneath, while the pill slides in, hit Allow / open.
+ assertFalse(OverlayPolicy.tapAccepted(shownAtMs = 1_000.0, nowMs = 1_050.0))
+ assertFalse(OverlayPolicy.tapAccepted(shownAtMs = 1_000.0, nowMs = 1_599.0))
+ assertTrue(OverlayPolicy.tapAccepted(shownAtMs = 1_000.0, nowMs = 1_600.0))
+ assertTrue(OverlayPolicy.tapAccepted(shownAtMs = 1_000.0, nowMs = 9_000.0))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/PairingScanTest.kt b/android/app/src/test/kotlin/com/coucou/android/PairingScanTest.kt
new file mode 100644
index 00000000..7b17a673
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/PairingScanTest.kt
@@ -0,0 +1,71 @@
+package com.coucou.android
+
+import com.coucou.android.core.PairingScan
+import com.coucou.android.core.ScanDecision
+import com.coucou.android.core.ScanPermission
+import com.coucou.android.core.ScanPermission.State
+import com.coucou.android.link.PairingPayload
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PairingScanTest {
+ private val fp = "ab".repeat(32)
+ private val token = "T0ken_with-16plus_chars"
+ private fun link(extra: String = "", v: String = "1", host: String = "192.168.1.20") =
+ "coucou://pair?v=$v&host=$host&port=47821&fp=$fp&token=$token&name=My%20PC$extra"
+
+ @Test fun aPairingLinkIsAccepted_andReturnedAsIs() {
+ val d = PairingScan.decide(link()) as ScanDecision.Pairing
+ assertEquals(link(), d.link)
+ assertNotNull(PairingPayload.parse(d.link))
+ }
+
+ @Test fun surroundingWhitespaceIsTolerated() {
+ assertTrue(PairingScan.decide(" \n${link()}\r\n ") is ScanDecision.Pairing)
+ }
+
+ @Test fun scanningAndPastingAgree() {
+ // The same parser decides, so whatever pasting refuses a scan refuses too.
+ val samples = listOf(
+ link(), link(v = "2"), link(host = ""), "coucou://pair", "coucou://other?v=1", "https://example.com", "WIFI:S:home;T:WPA;P:secret;;",
+ "", " ", "coucou://pair?v=1&host=h&port=0&fp=$fp&token=$token", link().replace(fp, "zz"), link().replace(token, "short"),
+ )
+ for (s in samples) {
+ val scanned = PairingScan.decide(s) is ScanDecision.Pairing
+ assertEquals(s, PairingPayload.parse(s) != null, scanned)
+ }
+ }
+
+ @Test fun otherCodesAreIgnored() {
+ for (s in listOf(
+ "https://coucou.example/pair?host=x", "BEGIN:VCARD", "12345", "mailto:[email protected]", "tel:+123", "http://192.168.1.20:47821",
+ null, "", "coucou://pair/?", "COUCOU://PAIR?v=1",
+ )) assertEquals(s, ScanDecision.NotPairing, PairingScan.decide(s))
+ }
+
+ @Test fun anAbsurdlyLongCodeIsNotALink() {
+ assertEquals(ScanDecision.NotPairing, PairingScan.decide(link("&pad=" + "x".repeat(PairingScan.MAX_LINK))))
+ assertNull(null as String?)
+ }
+
+ // ── camera permission ───────────────────────────────────────────────────────────────
+
+ @Test fun grantedMeansScan_whateverElse() {
+ for (asked in listOf(true, false)) for (explain in listOf(true, false)) assertEquals(State.GRANTED, ScanPermission.state(true, asked, explain))
+ }
+
+ @Test fun theFirstTimeWeAsk() {
+ assertEquals(State.ASK, ScanPermission.state(false, askedBefore = false, canExplain = false))
+ }
+
+ @Test fun refusedOnceWeMayAskAgain() {
+ assertEquals(State.ASK, ScanPermission.state(false, askedBefore = true, canExplain = true))
+ }
+
+ @Test fun refusedForGoodMeansSettingsOrPasting() {
+ assertEquals(State.BLOCKED, ScanPermission.state(false, askedBefore = true, canExplain = false))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/PaletteTest.kt b/android/app/src/test/kotlin/com/coucou/android/PaletteTest.kt
new file mode 100644
index 00000000..ac49ad10
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/PaletteTest.kt
@@ -0,0 +1,35 @@
+package com.coucou.android
+
+import com.coucou.android.core.Palette
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** No dark text on a dark background: every text colour is readable on the surfaces it sits on (the app is dark only). */
+class PaletteTest {
+ private val themes = mapOf("dark" to Palette.DARK)
+
+ @Test fun contrastMath() {
+ assertEquals(21.0, Palette.contrast(0xFF000000, 0xFFFFFFFF), 0.01)
+ assertEquals(1.0, Palette.contrast(0xFF123456, 0xFF123456), 1e-9)
+ }
+
+ @Test fun textIsReadableOnThePageAndOnCards() {
+ for ((name, p) in themes) {
+ for (surface in listOf(p.background, p.card)) {
+ assertTrue("$name text", Palette.contrast(p.text, surface) >= 7.0)
+ assertTrue("$name dim text", Palette.contrast(p.textDim, surface) >= 4.5)
+ assertTrue("$name links", Palette.contrast(p.accent, surface) >= 4.5)
+ assertTrue("$name errors", Palette.contrast(p.error, surface) >= 4.5)
+ }
+ }
+ }
+
+ @Test fun buttonTextIsReadableOnTheAccent() {
+ for ((name, p) in themes) assertTrue("$name button", Palette.contrast(p.onAccent, p.accent) >= 4.5)
+ }
+
+ @Test fun cardsAreToldApartFromThePage() {
+ for ((name, p) in themes) assertTrue("$name border", Palette.contrast(p.line, p.card) >= 1.1)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/PendingLaunchTest.kt b/android/app/src/test/kotlin/com/coucou/android/PendingLaunchTest.kt
new file mode 100644
index 00000000..1a4bbf78
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/PendingLaunchTest.kt
@@ -0,0 +1,84 @@
+package com.coucou.android
+
+import com.coucou.android.core.PendingLaunch
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PendingLaunchTest {
+ private var now = 1_000L
+ private val launch = PendingLaunch { now }
+
+ @Test fun aRequestFromOurOwnTapIsTakenOnce() {
+ launch.request("fp-1", allow = true)
+ assertEquals(PendingLaunch.Request("fp-1", true), launch.take())
+ assertNull("only once", launch.take())
+ }
+
+ @Test fun nothingAskedMeansNothingToTake() {
+ // A foreign intent with the same extras never reaches here: MainActivity does not read them (see below),
+ // so with no tap on our own notification there is simply no request.
+ assertNull(launch.take())
+ }
+
+ @Test fun aStaleRequestIsDropped() {
+ launch.request("fp-1", allow = true)
+ now += PendingLaunch.TTL_MS + 1
+ assertNull(launch.take())
+ launch.request("fp-2", allow = true)
+ now += PendingLaunch.TTL_MS
+ assertEquals("fp-2", launch.take()!!.fingerprint)
+ }
+
+ @Test fun aBlankOrHugeFingerprintCanNeverAllow() {
+ launch.request("", allow = true)
+ assertNull(launch.take())
+ launch.request(null, allow = true)
+ assertNull(launch.take())
+ launch.request("x".repeat(PendingLaunch.MAX_FP + 1), allow = true)
+ assertNull(launch.take())
+ }
+
+ @Test fun aNewerRequestReplacesTheOlderOne() {
+ launch.request("old", allow = true)
+ launch.request("new", allow = false)
+ assertEquals(PendingLaunch.Request("new", false), launch.take())
+ }
+
+ private val main = "src/main/kotlin/com/coucou/android/"
+ private fun manifest() = File("src/main/AndroidManifest.xml").readText()
+
+ @Test fun theExportedActivityNeverReadsTheRequestFromItsIntent() {
+ val src = File(main + "MainActivity.kt").readText()
+ for (bad in listOf("EXTRA_FP", "EXTRA_ALLOW", "getStringExtra", "getBooleanExtra", "\"fingerprint\"", "\"allow\"")) {
+ assertFalse("MainActivity must not read $bad from an intent", src.contains(bad))
+ }
+ assertTrue(src.contains("model.launch.take()"))
+ }
+
+ @Test fun onlyTheNonExportedEntryActivityCanMakeARequest() {
+ val callers = File(main).walkTopDown().filter { it.extension == "kt" }
+ .filter { it.readText().contains("launch.request(") }.map { it.name }.toList()
+ assertEquals(listOf("LaunchActivity.kt"), callers)
+ val m = manifest()
+ val entry = m.substringAfter("""android:name=".app.LaunchActivity"""").substringBefore("/>")
+ assertTrue(entry.contains("""android:exported="false""""))
+ assertTrue("it is the only way the request reaches the app", m.contains(".app.LaunchActivity"))
+ }
+
+ @Test fun ourNotificationsAndTheIslandGoThroughIt() {
+ val n = File(main + "app/Notifications.kt").readText()
+ assertTrue(n.contains("LaunchActivity::class.java"))
+ // The only component that takes the fingerprint extra from the outside is the Deny receiver, which is not exported.
+ assertTrue(manifest().substringAfter(""".app.ActionReceiver"""").substringBefore("/>").contains("""android:exported="false""""))
+ }
+
+ @Test fun everyOtherComponentWithAnIntentFilterIsTheLauncher() {
+ val m = manifest()
+ val exported = Regex("""android:name="([^"]+)"[^>]*android:exported="true"""").findAll(m).map { it.groupValues[1] }.toSet()
+ assertEquals(setOf(".MainActivity", ".app.GlanceWidget", ".app.GlanceTile"), exported)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/PillsTest.kt b/android/app/src/test/kotlin/com/coucou/android/PillsTest.kt
new file mode 100644
index 00000000..f1453c0f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/PillsTest.kt
@@ -0,0 +1,40 @@
+package com.coucou.android
+
+import com.coucou.android.core.PillCategory
+import com.coucou.android.core.Pills
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Pill IDs are contract values: this fails if the catalog drifts from windows/src/core/pills.ts. */
+class PillsTest {
+ private data class Ref(val id: String, val name: String, val color: String, val category: String)
+
+ private fun reference(): List<Ref> {
+ val src = ReferenceFiles.read("windows/src/core/pills.ts")
+ val re = Regex("""\{\s*id:\s*"([^"]+)",\s*name:\s*"([^"]+)",\s*color:\s*([^,]+),\s*category:\s*"([^"]+)"""")
+ val accents = Regex("""(\w+):\s*"(#[0-9A-Fa-f]{6})"""").findAll(src.substringBefore("export const PILL_CATALOG"))
+ .associate { it.groupValues[1] to it.groupValues[2] }
+ return re.findAll(src).map { m ->
+ val raw = m.groupValues[3].trim()
+ val color = if (raw.startsWith("\"")) raw.trim('"') else accents.getValue(raw.removePrefix("ACCENT."))
+ Ref(m.groupValues[1], m.groupValues[2], color, m.groupValues[4])
+ }.toList()
+ }
+
+ @Test fun catalogMatchesDesktopExceptAppleMusic() {
+ val expected = reference().filter { it.id != "integration_music" }
+ assertTrue("parsed too few pills from pills.ts", expected.size >= 20)
+ assertEquals(expected.map { it.id }, Pills.catalog.map { it.id })
+ for ((ref, mine) in expected.zip(Pills.catalog)) {
+ assertEquals(ref.name, mine.name)
+ assertEquals(ref.color.uppercase(), mine.colorHex.uppercase())
+ assertEquals(ref.category, mine.category.name.lowercase())
+ }
+ }
+
+ @Test fun idsAreUniqueAndDefaultExists() {
+ assertEquals(Pills.catalog.size, Pills.catalog.map { it.id }.toSet().size)
+ assertEquals(PillCategory.WORKSPACE, Pills.byId(Pills.DEFAULT_MAIN_PILL)?.category)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/PlanTextTest.kt b/android/app/src/test/kotlin/com/coucou/android/PlanTextTest.kt
new file mode 100644
index 00000000..2ed5bd1c
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/PlanTextTest.kt
@@ -0,0 +1,49 @@
+package com.coucou.android
+
+import com.coucou.android.core.PlanText
+import com.coucou.android.link.PlanWindow
+import java.time.ZoneId
+import java.util.Locale
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Mirrors the rules of windows/src/core/plan.ts so the phone and the PC read the same numbers the same way. */
+class PlanTextTest {
+ private val now = 1_800_000_000_000L
+
+ @Test fun aWindowThatHasResetCountsAsZero() {
+ assertEquals(0, PlanText.effectivePct(PlanWindow(90, now - 1), now))
+ assertEquals(0, PlanText.effectivePct(PlanWindow(90, now), now))
+ assertEquals(90, PlanText.effectivePct(PlanWindow(90, now + 1), now))
+ }
+
+ @Test fun greenUnderFiftyOrangeUpToEightyRedAbove() {
+ assertEquals(PlanText.Level.LOW, PlanText.level(49))
+ assertEquals(PlanText.Level.MEDIUM, PlanText.level(50))
+ assertEquals(PlanText.Level.MEDIUM, PlanText.level(79))
+ assertEquals(PlanText.Level.HIGH, PlanText.level(80))
+ assertEquals(PlanText.Level.HIGH, PlanText.level(100))
+ assertEquals(PlanText.Level.LOW, PlanText.level(0))
+ }
+
+ @Test fun resetTimesReadLikeThePCs() {
+ assertEquals(PlanText.Reset.Now, PlanText.resetsIn(PlanWindow(1, now), now))
+ assertEquals(PlanText.Reset.InMinutes(5), PlanText.resetsIn(PlanWindow(1, now + 5 * 60_000 + 10_000), now))
+ assertEquals(PlanText.Reset.InHoursMinutes(1, 20), PlanText.resetsIn(PlanWindow(1, now + 80 * 60_000), now))
+ assertEquals(PlanText.Reset.InMinutes(0), PlanText.resetsIn(PlanWindow(1, now + 30_000), now))
+ }
+
+ @Test fun theWeekShowsADayAndATimeInTheLocalZone() {
+ // 2027-01-18 09:00 in Paris (UTC+1) is a Monday.
+ val w = PlanWindow(1, java.time.ZonedDateTime.of(2027, 1, 18, 9, 5, 0, 0, ZoneId.of("Europe/Paris")).toInstant().toEpochMilli())
+ assertEquals("Mon 9:05", PlanText.weekday(w, ZoneId.of("Europe/Paris"), Locale.ENGLISH))
+ assertTrue(PlanText.weekday(w, ZoneId.of("Asia/Tokyo"), Locale.ENGLISH).startsWith("Mon 17:05"))
+ }
+
+ @Test fun theLevelsAreTheOnesInThePCsSource() {
+ val ts = ReferenceFiles.read("windows/src/core/plan.ts")
+ assertTrue(ts.contains("if (pct < 50) return \"#22C55E\"") && ts.contains("if (pct < 80) return \"#F59E0B\""))
+ assertTrue(ts.contains("w.resetsAt <= now ? 0 : w.usedPct"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/QrDecoderTest.kt b/android/app/src/test/kotlin/com/coucou/android/QrDecoderTest.kt
new file mode 100644
index 00000000..f8b99cd2
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/QrDecoderTest.kt
@@ -0,0 +1,88 @@
+package com.coucou.android
+
+import com.coucou.android.scan.QrDecoder
+import com.google.zxing.BarcodeFormat
+import com.google.zxing.EncodeHintType
+import com.google.zxing.qrcode.QRCodeWriter
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/** The decoder against real QR codes made by zxing's own encoder, drawn as a camera would give them (brightness bytes). */
+class QrDecoderTest {
+ private val fp = "ab".repeat(32)
+ private val text = "coucou://pair?v=1&host=192.168.1.20&port=47821&fp=$fp&token=T0ken_with-16plus_chars&name=My%20PC"
+
+ private class Frame(val luma: ByteArray, val stride: Int, val w: Int, val h: Int)
+
+ /** The code drawn [scale] pixels per module on a light background with a quiet zone, padded to [stride]. */
+ private fun frame(content: String, scale: Int = 6, margin: Int = 4, inverted: Boolean = false, extraStride: Int = 0, rotate: Boolean = false): Frame {
+ val m = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 0, 0, mapOf(EncodeHintType.MARGIN to 0, EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M))
+ val n = m.width
+ var side = (n + 2 * margin) * scale
+ val img = Array(side) { IntArray(side) { 255 } }
+ for (y in 0 until n) for (x in 0 until n) if (m.get(x, y)) {
+ for (dy in 0 until scale) for (dx in 0 until scale) img[(y + margin) * scale + dy][(x + margin) * scale + dx] = 0
+ }
+ var rows = img
+ if (rotate) rows = Array(side) { y -> IntArray(side) { x -> img[side - 1 - x][y] } }
+ val stride = side + extraStride
+ val out = ByteArray(stride * side)
+ for (y in 0 until side) for (x in 0 until side) {
+ val v = if (inverted) 255 - rows[y][x] else rows[y][x]
+ out[y * stride + x] = v.toByte()
+ }
+ return Frame(out, stride, side, side)
+ }
+
+ private fun QrDecoder.read(f: Frame) = decode(f.luma, f.stride, f.w, f.h)
+
+ @Test fun readsAPairingCode() {
+ assertEquals(text, QrDecoder().read(frame(text)))
+ }
+
+ @Test fun readsASmallCodeToo() {
+ assertEquals(text, QrDecoder().read(frame(text, scale = 3)))
+ }
+
+ @Test fun readsACodeInAFrameWhoseRowsAreWiderThanTheImage() {
+ // Camera frames pad each row (rowStride > width): that must not skew the picture.
+ assertEquals(text, QrDecoder().read(frame(text, extraStride = 37)))
+ }
+
+ @Test fun readsACodeTurnedOnItsSide() {
+ assertEquals(text, QrDecoder().read(frame(text, rotate = true)))
+ }
+
+ @Test fun readsALightCodeOnADarkBackground() {
+ assertEquals(text, QrDecoder().read(frame(text, inverted = true)))
+ }
+
+ @Test fun readsOtherTextToo_decidingWhatItMeansIsNotItsJob() {
+ assertEquals("https://example.com/shop?id=1", QrDecoder().read(frame("https://example.com/shop?id=1")))
+ }
+
+ @Test fun anEmptyOrNoisyFrameHasNoCode() {
+ val d = QrDecoder()
+ assertNull(d.decode(ByteArray(640 * 480) { 128.toByte() }, 640, 640, 480))
+ val rnd = java.util.Random(1)
+ assertNull(d.decode(ByteArray(300 * 300).also { rnd.nextBytes(it) }, 300, 300, 300))
+ }
+
+ @Test fun badDimensionsNeverThrow() {
+ val d = QrDecoder()
+ assertNull(d.decode(ByteArray(0), 0, 0, 0))
+ assertNull(d.decode(ByteArray(10), 5, 10, 10))
+ assertNull(d.decode(ByteArray(100), 10, 20, 10)) // stride smaller than width
+ assertNull(d.decode(ByteArray(50), 10, 10, 10)) // buffer too short
+ }
+
+ @Test fun oneDecoderServesManyFramesInARow() {
+ val d = QrDecoder()
+ assertNull(d.decode(ByteArray(200 * 200) { 255.toByte() }, 200, 200, 200))
+ assertEquals(text, d.read(frame(text)))
+ assertNull(d.decode(ByteArray(200 * 200) { 0 }, 200, 200, 200))
+ assertEquals("second", d.read(frame("second")))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/QuestionFlowTest.kt b/android/app/src/test/kotlin/com/coucou/android/QuestionFlowTest.kt
new file mode 100644
index 00000000..49202266
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/QuestionFlowTest.kt
@@ -0,0 +1,99 @@
+package com.coucou.android
+
+import com.coucou.android.core.QuestionFlow
+import com.coucou.android.core.QuestionState
+import com.coucou.android.link.AskedOption
+import com.coucou.android.link.AskedQuestion
+import com.coucou.android.link.Protocol
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class QuestionFlowTest {
+ private fun opts(vararg l: String) = l.map { AskedOption(it, "") }
+ private val single = AskedQuestion("Which engine?", opts("Postgres", "Meilisearch", "Algolia"), multiSelect = false)
+ private val multi = AskedQuestion("Which extras?", opts("Typos", "Facets", "Synonyms"), multiSelect = true)
+ private val both = listOf(single, multi)
+
+ @Test fun aSingleChoiceKeepsOnlyTheLastTap() {
+ var s = QuestionFlow.start(both)
+ s = QuestionFlow.toggle(both, s, "Postgres")
+ s = QuestionFlow.toggle(both, s, "Algolia")
+ assertEquals(listOf("Algolia"), s.picks[0])
+ }
+
+ @Test fun aMultipleChoiceAddsAndRemovesAndKeepsTheOptionsOrder() {
+ var s = QuestionFlow.next(both, QuestionFlow.toggle(both, QuestionFlow.start(both), "Meilisearch"))
+ assertEquals(1, s.index)
+ s = QuestionFlow.toggle(both, s, "Synonyms")
+ s = QuestionFlow.toggle(both, s, "Typos")
+ assertEquals("order of the options, not of the taps", listOf("Typos", "Synonyms"), s.picks[1])
+ s = QuestionFlow.toggle(both, s, "Synonyms")
+ assertEquals(listOf("Typos"), s.picks[1])
+ s = QuestionFlow.toggle(both, s, "Typos")
+ assertTrue(s.picks[1].isEmpty())
+ }
+
+ @Test fun aLabelThatIsNotAnOptionNeverEntersAnAnswer() {
+ val s = QuestionFlow.start(both)
+ assertEquals(s, QuestionFlow.toggle(both, s, "Mongo"))
+ assertEquals(s, QuestionFlow.toggle(both, s, "postgres"))
+ assertEquals(s, QuestionFlow.toggle(both, s, ""))
+ }
+
+ @Test fun youCannotMoveOnWithoutAnAnswer() {
+ val s = QuestionFlow.start(both)
+ assertFalse(QuestionFlow.canAdvance(both, s))
+ assertEquals(s, QuestionFlow.next(both, s))
+ val picked = QuestionFlow.toggle(both, s, "Postgres")
+ assertTrue(QuestionFlow.canAdvance(both, picked))
+ assertEquals(1, QuestionFlow.next(both, picked).index)
+ }
+
+ @Test fun theLastQuestionDoesNotAdvanceAndBackStopsAtTheFirst() {
+ var s = QuestionFlow.toggle(both, QuestionFlow.start(both), "Postgres")
+ s = QuestionFlow.next(both, s)
+ assertTrue(QuestionFlow.isLast(both, s))
+ s = QuestionFlow.toggle(both, s, "Facets")
+ assertEquals(s, QuestionFlow.next(both, s))
+ assertEquals(0, QuestionFlow.back(QuestionFlow.back(s)).index)
+ assertEquals("the pick of the first question is kept", listOf("Postgres"), QuestionFlow.back(s).picks[0])
+ }
+
+ @Test fun anAnswerIsCompleteOnlyWhenEveryQuestionHasItsPicks() {
+ var s = QuestionFlow.start(both)
+ assertNull(QuestionFlow.picks(both, s))
+ s = QuestionFlow.toggle(both, s, "Postgres")
+ assertFalse(QuestionFlow.complete(both, s))
+ s = QuestionFlow.toggle(both, QuestionFlow.next(both, s), "Typos")
+ assertTrue(QuestionFlow.complete(both, s))
+ assertEquals(listOf(listOf("Postgres"), listOf("Typos")), QuestionFlow.picks(both, s))
+ }
+
+ @Test fun twoPicksForASingleChoiceOrDuplicatesAreNotComplete() {
+ assertFalse(QuestionFlow.complete(listOf(single), QuestionState(0, listOf(listOf("Postgres", "Algolia")))))
+ assertFalse(QuestionFlow.complete(listOf(multi), QuestionState(0, listOf(listOf("Typos", "Typos")))))
+ assertFalse(QuestionFlow.complete(listOf(multi), QuestionState(0, listOf(listOf("Nope")))))
+ assertFalse(QuestionFlow.complete(listOf(single), QuestionState(0, listOf(emptyList()))))
+ assertFalse(QuestionFlow.complete(both, QuestionState(0, listOf(listOf("Postgres")))))
+ }
+
+ @Test fun theLockPromptShowsWhatIsAboutToBeSent() {
+ var s = QuestionFlow.toggle(both, QuestionFlow.start(both), "Meilisearch")
+ s = QuestionFlow.toggle(both, QuestionFlow.next(both, s), "Typos")
+ s = QuestionFlow.toggle(both, s, "Facets")
+ assertEquals("Meilisearch; Typos, Facets", QuestionFlow.summary(both, s))
+ }
+
+ @Test fun aQuestionIsOfferedForTheSameTimeAsAnApproval() {
+ assertFalse(QuestionFlow.expired(1_000, 1_000 + Protocol.APPROVAL_TTL_MS))
+ assertTrue(QuestionFlow.expired(1_000, 1_001 + Protocol.APPROVAL_TTL_MS))
+ }
+
+ @Test fun onlyAMultiPartQuestionShowsAPosition() {
+ assertNull(QuestionFlow.position(listOf(single), QuestionFlow.start(listOf(single))))
+ assertEquals(1 to 2, QuestionFlow.position(both, QuestionFlow.start(both)))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ReferenceFiles.kt b/android/app/src/test/kotlin/com/coucou/android/ReferenceFiles.kt
new file mode 100644
index 00000000..32ea534c
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ReferenceFiles.kt
@@ -0,0 +1,18 @@
+package com.coucou.android
+
+import java.io.File
+
+/** Locates the desktop reference sources (windows/src/...) so tests can compare against them. */
+object ReferenceFiles {
+ private fun repoRoot(): File {
+ var dir: File? = File(System.getProperty("user.dir")).absoluteFile
+ while (dir != null) {
+ if (File(dir, "windows/src/core/pills.ts").exists()) return dir
+ dir = dir.parentFile
+ }
+ error("repo root with windows/src not found from ${System.getProperty("user.dir")}")
+ }
+
+ fun read(path: String): String = File(repoRoot(), path).readText()
+ fun file(path: String): File = File(repoRoot(), path)
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/RelayStatusTest.kt b/android/app/src/test/kotlin/com/coucou/android/RelayStatusTest.kt
new file mode 100644
index 00000000..f91c414b
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/RelayStatusTest.kt
@@ -0,0 +1,38 @@
+package com.coucou.android
+
+import com.coucou.android.core.RelayLineKind
+import com.coucou.android.core.RelayStatus
+import com.coucou.android.link.RelayIssue
+import com.coucou.android.link.Route
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class RelayStatusTest {
+ private fun kind(hasRelay: Boolean = true, use: Boolean = true, connected: Boolean = false, route: Route? = null, issue: RelayIssue = RelayIssue.NONE) =
+ RelayStatus.kind(hasRelay, use, connected, route, issue)
+
+ @Test fun aPairingWithoutARelayExplainsHowToGetOne() = assertEquals(RelayLineKind.NO_RELAY_IN_PAIRING, kind(hasRelay = false, connected = true))
+
+ @Test fun switchedOffSaysSo() = assertEquals(RelayLineKind.SWITCHED_OFF, kind(use = false, connected = true, route = Route.LAN))
+
+ @Test fun connectedSaysWhichWay() {
+ assertEquals(RelayLineKind.DIRECT, kind(connected = true, route = Route.LAN))
+ assertEquals(RelayLineKind.VIA_RELAY, kind(connected = true, route = Route.RELAY))
+ }
+
+ @Test fun notConnectedNamesTheReason() {
+ assertEquals(RelayLineKind.WAITING, kind())
+ assertEquals(RelayLineKind.ACCESS_REFUSED, kind(issue = RelayIssue.ACCESS_REFUSED))
+ assertEquals(RelayLineKind.ROOM_TAKEN, kind(issue = RelayIssue.ROOM_TAKEN))
+ assertEquals(RelayLineKind.RATE_LIMITED, kind(issue = RelayIssue.RATE_LIMITED))
+ assertEquals(RelayLineKind.UNREACHABLE, kind(issue = RelayIssue.UNREACHABLE))
+ assertEquals(RelayLineKind.COMPUTER_AWAY, kind(issue = RelayIssue.COMPUTER_AWAY))
+ }
+
+ @Test fun everyRelayIssueHasItsOwnSentence() {
+ val kinds = RelayIssue.values().map { kind(issue = it) }
+ assertEquals(kinds.size, kinds.toSet().size)
+ assertTrue(kinds.none { it == RelayLineKind.DIRECT || it == RelayLineKind.VIA_RELAY })
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ReleaseBuildTest.kt b/android/app/src/test/kotlin/com/coucou/android/ReleaseBuildTest.kt
new file mode 100644
index 00000000..3885ed13
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ReleaseBuildTest.kt
@@ -0,0 +1,87 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Guards for the release build type. Gradle and R8 run only in CI (where `lint` now needs a release build, see verifyReleaseNoLogs), so
+ * these read the build files and the sources for the rules that must not be lost by accident.
+ */
+class ReleaseBuildTest {
+ private val gradle = File("build.gradle.kts").readText()
+ private val rules = File("proguard-rules.pro").readText()
+ private val main = File("src/main/kotlin")
+ private fun sources() = main.walkTopDown().filter { it.extension == "kt" }.toList()
+
+ @Test fun theReleaseTypeShrinksObfuscatesAndIsNotDebuggable() {
+ val release = gradle.substringAfter("buildTypes {").substringBefore("buildFeatures")
+ assertTrue(release.contains("isMinifyEnabled = true"))
+ assertTrue(release.contains("isShrinkResources = true"))
+ assertTrue(release.contains("isDebuggable = false"))
+ assertTrue(release.contains("proguard-android-optimize.txt") && release.contains("\"proguard-rules.pro\""))
+ }
+
+ @Test fun signingComesFromTheEnvironmentOrGradlePropertiesNeverFromTheRepository() {
+ for (name in listOf("COUCOU_KEYSTORE_FILE", "COUCOU_KEYSTORE_PASSWORD", "COUCOU_KEY_ALIAS", "COUCOU_KEY_PASSWORD")) assertTrue(name, gradle.contains("\"$name\""))
+ assertTrue(gradle.contains("System.getenv(name) ?: providers.gradleProperty(name)"))
+ // no literal password, no key file path, and never the debug key for a release
+ assertFalse(Regex("""(storePassword|keyPassword)\s*=\s*"[^"]""").containsMatchIn(gradle))
+ assertFalse(gradle.contains("signingConfigs.getByName(\"debug\")") || gradle.contains("signingConfigs[\"debug\"]"))
+ assertTrue(gradle.contains("signingConfigs.findByName(\"release\")"))
+ }
+
+ @Test fun noKeyFileIsInTheRepositoryAndTheyAreIgnored() {
+ val android = File("..")
+ val found = android.walkTopDown().onEnter { it.name != "build" && it.name != ".gradle" && it.name != "node_modules" }
+ // src/test/resources holds a throw-away certificate for the fake computer in the tests, not a signing key
+ .filter { !it.path.replace('\\', '/').contains("src/test/resources") }.filter { it.isFile && it.extension in setOf("jks", "keystore", "p12", "pfx") }.toList()
+ assertEquals("a signing key must never be in the repository: $found", emptyList<File>(), found)
+ assertFalse(File("..").walkTopDown().onEnter { it.name != "build" && it.name != "node_modules" }.any { it.name == "keystore.properties" })
+ val ignore = File("../.gitignore").readText()
+ for (pattern in listOf("*.jks", "*.keystore", "*.p12", "keystore.properties")) assertTrue(pattern, ignore.lines().contains(pattern))
+ }
+
+ @Test fun everyLogCallIsRemovedFromTheReleaseAndCarriesNoSecret() {
+ for (level in listOf("v", "d", "i", "w", "e")) assertTrue(level, rules.contains("public static int $level(...);"))
+ assertTrue(rules.contains("-assumenosideeffects class android.util.Log"))
+ val logLines = sources().flatMap { f -> f.readLines().filter { it.contains("Log.") && !it.trimStart().startsWith("import") && !it.trimStart().startsWith("//") }.map { f.name to it } }
+ assertTrue("the test must see the log calls", logLines.size >= 10)
+ for ((file, line) in logLines) {
+ for (word in listOf("token", "secret", "fingerprint", "password", "command", "pairing", "access", "answer", "\${r.", "picks")) {
+ assertFalse("$file logs '$word': $line", line.contains(word, ignoreCase = true))
+ }
+ }
+ }
+
+ @Test fun nothingElseWritesToTheLogOrTheConsole() {
+ for (f in sources()) {
+ val text = f.readText()
+ assertFalse("${f.name}: println", Regex("""\bprintln\(""").containsMatchIn(text))
+ assertFalse("${f.name}: printStackTrace", text.contains("printStackTrace"))
+ assertFalse("${f.name}: System.out/err", text.contains("System.out") || text.contains("System.err"))
+ assertFalse("${f.name}: a logging library", text.contains("Timber") || text.contains("android.util.Printer"))
+ }
+ }
+
+ @Test fun theReleaseBuildIsProvedInCiWithoutTouchingTheWorkflow() {
+ assertTrue(gradle.contains("tasks.matching { it.name == \"lint\" }.configureEach { dependsOn(verifyReleaseNoLogs) }"))
+ assertTrue(gradle.contains("dependsOn(\"assembleRelease\")"))
+ // the tags and messages that must not survive in the dex are the ones the sources use
+ val tags = Regex("""(?<![A-Z_])TAG = "(\w+)"|Log\.\w\("(Coucou\w+)"""").findAll(sources().joinToString("\n") { it.readText() })
+ .flatMap { m -> m.groupValues.drop(1).filter { it.isNotEmpty() } }.toSet()
+ for (tag in tags) assertTrue("verifyReleaseNoLogs must look for $tag", gradle.contains("\"$tag\""))
+ }
+
+ @Test fun theRulesNeedNoKeepBecauseNothingIsReflected() {
+ assertFalse(rules.lines().any { it.trim().startsWith("-keep ") || it.trim().startsWith("-keepclass") })
+ for (f in sources()) {
+ val text = f.readText()
+ assertFalse("${f.name}: Class.forName", text.contains("Class.forName"))
+ assertFalse("${f.name}: reflection", text.contains("getDeclaredMethod") || text.contains("getDeclaredField") || text.contains("kotlin.reflect"))
+ assertFalse("${f.name}: getIdentifier", text.contains("getIdentifier("))
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/SafeTextTest.kt b/android/app/src/test/kotlin/com/coucou/android/SafeTextTest.kt
new file mode 100644
index 00000000..5d77670a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/SafeTextTest.kt
@@ -0,0 +1,110 @@
+package com.coucou.android
+
+import com.coucou.android.core.HomeText
+import com.coucou.android.core.SafeText
+import com.coucou.android.core.ToolLabels
+import com.coucou.android.link.SessionInfo
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SafeTextTest {
+ private val secrets = listOf("hunter2", "sk-live-4242", "ghp_ABCDEF", "s3cr3t", "AKIAIOSFODNN7", "p@ss", "/home/me", "C:\\Users", "token=", "Bearer")
+
+ private fun assertClean(s: String) { for (x in secrets) assertFalse("'$s' leaks $x", s.contains(x)) }
+
+ @Test fun theProgramIsTheFirstPlainWord() {
+ assertEquals("npm", SafeText.program("npm test"))
+ assertEquals("git", SafeText.program(" git push --force origin main"))
+ assertEquals("cargo", SafeText.program("cargo test --workspace"))
+ }
+
+ @Test fun flagsAndEnvironmentVariablesAreNeverTheProgram() {
+ assertNull(SafeText.program("--token=hunter2 run"))
+ assertNull(SafeText.program("-rf /"))
+ assertEquals("npm", SafeText.program("API_KEY=sk-live-4242 NODE_ENV=prod npm run build"))
+ assertNull(SafeText.program("API_KEY=sk-live-4242"))
+ assertNull(SafeText.program("password=hunter2"))
+ }
+
+ @Test fun aPathIsReducedToItsFileNameAndAUrlIsDropped() {
+ assertEquals("run.sh", SafeText.program("/home/me/secret/run.sh --go"))
+ assertEquals("tool.exe", SafeText.program("C:\\Users\\me\\bin\\tool.exe /x"))
+ assertNull(SafeText.program("https://user:[email protected]/x"))
+ assertNull(SafeText.program("ftp://admin:s3cr3t@host"))
+ assertNull(SafeText.program("user:p@ss@host"))
+ }
+
+ @Test fun theNameIsCutAtTwentyCharactersAndOddCharactersGiveNothing() {
+ assertEquals(20, SafeText.program("a".repeat(60))!!.length)
+ assertNull(SafeText.program("\$(curl evil)"))
+ assertNull(SafeText.program("echo;rm"))
+ assertNull(SafeText.program(""))
+ assertNull(SafeText.program(null))
+ }
+
+ @Test fun aRequestShowsALabelAndForAShellTheProgramOnly() {
+ val cmds = listOf(
+ "curl -H 'Authorization: Bearer ghp_ABCDEF' https://user:[email protected]/x",
+ "AWS_SECRET=AKIAIOSFODNN7 /home/me/bin/deploy --password s3cr3t",
+ "mysql -u root -phunter2 -h db",
+ )
+ assertEquals("Running a command · curl", SafeText.requestLabel("Bash", cmds[0]))
+ assertEquals("Running a command · deploy", SafeText.requestLabel("Bash", cmds[1]))
+ assertEquals("Running a command · mysql", SafeText.requestLabel("Bash", cmds[2]))
+ for (c in cmds) assertClean(SafeText.requestLabel("Bash", c))
+ }
+
+ @Test fun anotherToolNeverShowsItsArgument() {
+ assertEquals("Editing files", SafeText.requestLabel("Edit", "/home/me/.ssh/config"))
+ assertEquals("Editing files", SafeText.requestLabel("Write", "C:\\Users\\me\\secret.txt"))
+ assertEquals("Mcp github create issue", SafeText.requestLabel("mcp__github__create_issue", "title=hunter2"))
+ assertEquals("Working", SafeText.requestLabel("", "rm -rf /"))
+ }
+
+ @Test fun aStepFromTheComputerShowsNoCommandAndNoPath() {
+ val steps = listOf(
+ "Bash · curl -u admin:hunter2 https://x.example/api",
+ "Edit · /home/me/secret/plan.md",
+ "Read · C:\\Users\\me\\.aws\\credentials",
+ "Bash · TOKEN=sk-live-4242 ./deploy.sh",
+ )
+ val shown = steps.map { ToolLabels.label(it) }
+ assertEquals(listOf("Running a command · curl", "Editing files", "Reading files", "Running a command · deploy.sh"), shown)
+ for (s in shown) assertClean(s)
+ // Home's line for a working agent is the same label.
+ assertEquals("Running a command · curl", HomeText.line(SessionInfo("p", "A", BotState.WORKING, steps[0], 0, 0, 0L)))
+ }
+
+ @Test fun anAgentsLastMessageLosesPathsUrlsAndKeyValuePairs() {
+ val said = "Fixed it in /home/me/secret/app.rs, see https://user:[email protected]/x and set TOKEN=sk-live-4242 then C:\\Users\\me\\a.txt done."
+ val shown = SafeText.prose(said)
+ assertClean(shown)
+ assertTrue(shown, shown.startsWith("Fixed it in"))
+ assertTrue(shown, shown.endsWith("done."))
+ assertEquals("All tests pass.", SafeText.prose("All tests pass."))
+ val s = SessionInfo("p", "A", BotState.FINISHED, "", 0, 0, 0L, finalLine = said)
+ assertClean(HomeText.line(s)!!)
+ assertNull(HomeText.line(SessionInfo("p", "A", BotState.FINISHED, "", 0, 0, 0L, finalLine = "/home/me/secret/app.rs")))
+ }
+
+ @Test fun noSurfaceThatIsSeenWithoutATapPrintsTheCommand() {
+ val main = "src/main/kotlin/com/coucou/android/"
+ val n = java.io.File(main + "app/Notifications.kt").readText()
+ assertFalse(n.replace("SafeText.requestLabel(r.tool, r.command)", "").contains("r.command"))
+ assertFalse(n.contains("setSubText(statusText"))
+ for (f in listOf("ui/HomePanel.kt", "ui/SessionScreen.kt", "ui/IslandOverlay.kt", "core/IslandPlan.kt", "core/Glance.kt", "ui/UsagePanel.kt")) {
+ assertFalse("$f prints a command", java.io.File(main + f).readText().contains(".command"))
+ }
+ // The only screen that prints it sits behind "Show exact command" (a deliberate tap).
+ val sheets = java.io.File(main + "ui/Sheets.kt").readText()
+ val reveal = sheets.substringAfter("if (showCommand) {")
+ assertTrue(reveal.contains("r.command"))
+ assertFalse(sheets.substringBefore("if (showCommand) {").contains("r.command"))
+ // And the phone's own history keeps a label, not the command.
+ assertTrue(java.io.File(main + "app/AppModel.kt").readText().contains("SafeText.requestLabel(request.tool, request.command)"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ScanScreenTest.kt b/android/app/src/test/kotlin/com/coucou/android/ScanScreenTest.kt
new file mode 100644
index 00000000..96ab7bc2
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ScanScreenTest.kt
@@ -0,0 +1,101 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Source-level guards for scanning the pairing code (the camera and Compose cannot run in a JVM test). */
+class ScanScreenTest {
+ private fun file(path: String) = File(path).readText()
+ private fun src(name: String) = file("src/main/kotlin/com/coucou/android/$name")
+ private val kotlinFiles get() = File("src/main/kotlin").walkTopDown().filter { it.isFile && it.extension == "kt" }.toList()
+
+ @Test fun theCameraIsReleasedWhenTheScreenIsLeftAndAfterAnAcceptedCode() {
+ val ui = src("ui/ScanScreen.kt")
+ val dispose = ui.substring(ui.lastIndexOf("onDispose {")).substringBefore("\n }")
+ assertTrue(dispose.contains("provider?.unbindAll()"))
+ assertTrue(dispose.contains("analysis?.clearAnalyzer()"))
+ assertTrue(dispose.contains("executor.shutdown()"))
+ assertTrue("released at once when a code is accepted", ui.contains("done.set(true)") && ui.contains("provider?.unbindAll() }"))
+ assertTrue("every frame is closed", ui.contains("image.close()"))
+ assertTrue("bound to the screen's own lifecycle", ui.contains("bindToLifecycle(owner"))
+ }
+
+ @Test fun noPictureIsKeptOrSent() {
+ val ui = src("ui/ScanScreen.kt") + src("scan/QrDecoder.kt")
+ for (bad in listOf("ImageCapture", "VideoCapture", "\\bBitmap\\b", "compress\\(", "FileOutputStream", "openFileOutput", "MediaStore", "\\bURL\\(", "HttpURLConnection", "\\bSocket\\(")) {
+ assertFalse("the scanner must not use $bad", Regex(bad).containsMatchIn(ui))
+ }
+ assertTrue("only the brightness plane is read", ui.contains("image.planes[0]"))
+ }
+
+ @Test fun theCameraIsAskedForOnlyOnTheScanScreenAfterTheUserTappedScan() {
+ val ui = src("ui/ScanScreen.kt")
+ assertTrue(ui.contains("launcher.launch(Manifest.permission.CAMERA)"))
+ for (f in kotlinFiles.filter { it.name != "ScanScreen.kt" }) {
+ assertFalse("${f.name} must not ask for the camera", f.readText().contains("Manifest.permission.CAMERA"))
+ }
+ assertTrue("a short reason is shown first", ui.contains("R.string.scan_why"))
+ assertTrue("a way out when it is refused for good", ui.contains("ACTION_APPLICATION_DETAILS_SETTINGS") && ui.contains("R.string.scan_paste_instead"))
+ }
+
+ @Test fun theManifestAsksForTheCameraButDoesNotRequireOne_andKeepsTheCameraAppLink() {
+ val m = file("src/main/AndroidManifest.xml")
+ assertTrue(m.contains("android.permission.CAMERA"))
+ assertTrue(Regex("""uses-feature\s+android:name="android.hardware.camera"\s+android:required="false"""").containsMatchIn(m))
+ // the camera app's own scanner opens coucou://pair
+ assertTrue(m.contains("""android:scheme="coucou" android:host="pair""""))
+ assertTrue(m.contains("android.intent.category.BROWSABLE") && m.contains("android.intent.action.VIEW"))
+ }
+
+ @Test fun aLinkFromTheCameraAppAsksBeforeItPairs() {
+ val main = src("MainActivity.kt")
+ val handle = main.substringAfter("private fun handle(").substringBefore("val fp = i.getStringExtra")
+ assertTrue(handle.contains("model.requestPairing("))
+ assertFalse("a link must never pair without the user's OK", handle.contains("model.pair("))
+ assertTrue(main.contains("model.pairRequest?.let { PairConfirm(model, it) }"))
+ // and the confirmation names the computer, never the secret
+ val confirm = src("ui/PairConfirm.kt")
+ assertFalse(confirm.contains(".token") || confirm.contains("certSha256"))
+ assertTrue(confirm.contains("model.confirmPairing()"))
+ }
+
+ @Test fun aScannedCodeGoesThroughTheSamePairingPathAsAPastedOne() {
+ val model = src("app/AppModel.kt")
+ val confirm = model.substringAfter("fun confirmPairing()").substringBefore("fun cancelPairing")
+ assertTrue(confirm.contains("pair(link)"))
+ assertTrue(src("core/PairingScan.kt").contains("PairingPayload.parse(t)"))
+ assertTrue(src("MainActivity.kt").contains("onText = { text -> model.requestPairing(text)"))
+ }
+
+ @Test fun neitherTheTokenNorTheFingerprintNorTheScannedTextIsEverLogged() {
+ val secrets = Regex("""\b(token|certSha256|fingerprint|pairRequest|pairing\.|payload|link|text)\b""")
+ for (f in kotlinFiles) {
+ f.readLines().filter { it.contains("Log.") || it.contains("println(") }.forEach { line ->
+ // the arguments of the log call, without the tag
+ val msg = line.substringAfter("Log.", "").substringAfter("(", "")
+ assertFalse("${f.name}: $line", secrets.containsMatchIn(msg.substringAfter(",", msg)))
+ }
+ }
+ }
+
+ @Test fun theNewLibrariesAreCameraXAndZxingCoreOnly_noPlayServicesNoMlKit() {
+ val g = file("build.gradle.kts")
+ assertTrue(g.contains("androidx.camera:camera-core") && g.contains("com.google.zxing:core:"))
+ for (bad in listOf("com.google.android.gms", "play-services", "mlkit", "firebase", "admob", "billingclient", "crashlytics", "camera-mlkit")) {
+ assertFalse("build.gradle.kts must not mention $bad", g.contains(bad, ignoreCase = true))
+ }
+ assertTrue(File("../../.github/workflows/phone-link.yml").readText().contains("mlkit"))
+ }
+
+ @Test fun theScanButtonIsTheMainActionOfThePairingScreenAndPastingStays() {
+ val ui = src("ui/PairingScreen.kt")
+ assertTrue(ui.indexOf("R.string.scan_button") < ui.indexOf("R.string.pair_paste_short"))
+ assertTrue(ui.contains("PillKind.PRIMARY") && ui.contains("R.string.demo_try"))
+ assertTrue("paste lives in a sheet, with the clipboard shortcut", ui.contains("PasteSheet(") && ui.contains("R.string.pair_clipboard"))
+ // a pasted link is checked by the same parser before anything is paired
+ assertTrue(ui.contains("if (PairingPayload.parse(link) != null) { model.pair(link)"))
+ assertTrue(src("MainActivity.kt").contains("if (model.mode == Mode.NONE) PairingScreen("))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ScreenLayoutTest.kt b/android/app/src/test/kotlin/com/coucou/android/ScreenLayoutTest.kt
new file mode 100644
index 00000000..a87c3550
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ScreenLayoutTest.kt
@@ -0,0 +1,45 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Guards for where things live on screen (the Compose code cannot be rendered in a JVM test, so
+ * these read the sources). Home is the agent card; Settings holds the rest, including the notice
+ * Louis Raillé's permission requires, which must stay reachable and visible.
+ */
+class ScreenLayoutTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val main get() = src("MainActivity.kt")
+ private val settings get() = src("ui/SettingsScreens.kt")
+ private val homePanel get() = src("ui/HomePanel.kt")
+
+ @Test fun settingsHoldsDisconnectGalleryOverlayAndTheRequiredNotice() {
+ for (s in listOf(
+ "R.string.action_unpair", "R.string.demo_leave", "R.string.gallery", "R.string.overlay_title",
+ "R.string.about_unofficial", "R.string.about_repo", "R.string.about_assets", "R.string.settings_section_about",
+ )) assertTrue("Settings must carry $s", settings.contains(s))
+ }
+
+ @Test fun theNoticeNamesTheOriginalAuthorAndHisRepository() {
+ val xml = File("src/main/res/values/strings.xml").readText()
+ assertTrue(xml.contains("Coucou for Android, by Rhytam Biswas. Part of Coucou by Louis Raillé"))
+ assertTrue(xml.contains("github.com/Louis-CFM/coucou"))
+ assertTrue(xml.contains("© Louis Raillé"))
+ assertTrue(xml.contains("MIT License"))
+ }
+
+ @Test fun theHeroNeverShowsTheRawStatusText() {
+ assertTrue(homePanel.contains("HomeText.line("))
+ assertFalse("the raw text must not be drawn directly", Regex("""Text\(\s*(focus\??\.|detail = focus)?statusText""").containsMatchIn(homePanel))
+ }
+
+ @Test fun activityShowsSentencesNeverTheCommand() {
+ val history = settings.substringAfter("fun HistoryScreen")
+ assertTrue(history.contains("HomeText.decision("))
+ assertFalse("no raw command or tool: command line", history.contains("d.command") || history.contains("Monospace"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/SecureScreensTest.kt b/android/app/src/test/kotlin/com/coucou/android/SecureScreensTest.kt
new file mode 100644
index 00000000..3786c6a6
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/SecureScreensTest.kt
@@ -0,0 +1,39 @@
+package com.coucou.android
+
+import com.coucou.android.core.Screen
+import com.coucou.android.core.SecureScreens
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SecureScreensTest {
+ private fun needed(
+ screen: Screen, pairing: Boolean = false, approval: Boolean = false, question: Boolean = false, confirm: Boolean = false,
+ ) = SecureScreens.needed(screen, pairing, approval, question, confirm)
+
+ @Test fun pairingChatApprovalAndQuestionAreHidden() {
+ assertTrue("pairing screen", needed(Screen.HOME, pairing = true))
+ assertTrue("scanning the code", needed(Screen.SCAN))
+ assertTrue("chat", needed(Screen.CHAT))
+ assertTrue("approval over Home", needed(Screen.HOME, approval = true))
+ assertTrue("approval over Settings", needed(Screen.SETTINGS, approval = true))
+ assertTrue("question", needed(Screen.HOME, question = true))
+ assertTrue("pair confirmation", needed(Screen.HOME, confirm = true))
+ }
+
+ @Test fun otherScreensAreNotHidden() {
+ for (s in listOf(Screen.HOME, Screen.SETTINGS, Screen.HISTORY, Screen.GALLERY, Screen.WARDROBE, Screen.SESSION)) {
+ assertFalse("$s", needed(s))
+ }
+ }
+
+ @Test fun theActivityAppliesAndClearsTheFlagFromThatDecision() {
+ val src = File("src/main/kotlin/com/coucou/android/MainActivity.kt").readText()
+ assertTrue(src.contains("SecureScreens.needed("))
+ assertTrue(src.contains("window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)"))
+ assertTrue("cleared when the screen is no longer sensitive", src.contains("window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)"))
+ // The decision sees every sheet that exists: a new sheet must be added to it.
+ for (sheet in listOf("ApprovalSheet(", "QuestionSheet(", "PairConfirm(")) assertTrue(sheet, src.contains(sheet))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ServicesPanelTest.kt b/android/app/src/test/kotlin/com/coucou/android/ServicesPanelTest.kt
new file mode 100644
index 00000000..ceae9207
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ServicesPanelTest.kt
@@ -0,0 +1,27 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ServicesPanelTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+
+ @Test fun theCardsAreReadOnly() {
+ val p = src("ui/ServicesPanel.kt")
+ assertFalse("nothing in a card can be tapped", p.contains("clickable") || p.contains("onClick") || p.contains("openUri"))
+ assertFalse(p.contains("Log."))
+ }
+
+ @Test fun theyGoWhenTheLinkOrTheOfferDoes() {
+ val m = src("app/AppModel.kt")
+ assertTrue(m.substringAfter("private fun stopLink()").take(140).contains("services = emptyList()"))
+ assertTrue(m.contains("if (Protocol.CAP_SERVICES !in caps) services = emptyList()"))
+ assertFalse(m.substringAfter("override fun onServices").take(160).contains("kv.put"))
+ }
+
+ @Test fun homeShowsThemOnlyWhenThereAreSome() {
+ assertTrue(src("MainActivity.kt").contains("if (model.services.isNotEmpty()) item"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/SessionScreenTest.kt b/android/app/src/test/kotlin/com/coucou/android/SessionScreenTest.kt
new file mode 100644
index 00000000..fb3aa1fc
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/SessionScreenTest.kt
@@ -0,0 +1,35 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Source-level guards for the session detail screen (Compose cannot be rendered in a JVM test). */
+class SessionScreenTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val strings get() = File("src/main/res/values/strings.xml").readText()
+
+ @Test fun theCardOpensTheDetailsOnlyWhenTheyExist() {
+ val main = src("MainActivity.kt")
+ assertTrue(main.contains("onDetails = if (focus != null && HomePanel.hasDetails(focus))"))
+ assertTrue(main.contains("Screen.SESSION -> SessionScreen("))
+ val hero = src("ui/HomePanel.kt")
+ assertTrue("the Details pill exists only when there is something to open", hero.contains("if (onDetails != null)") && hero.contains("R.string.session_details), onDetails"))
+ }
+
+ @Test fun stepsAreShownInPlainWordsAndTheProjectIsOnlyAName() {
+ val ui = src("ui/SessionScreen.kt")
+ assertTrue(ui.contains("ToolLabels.label(step)"))
+ assertTrue(ui.contains("R.string.session_project"))
+ // the screen never draws a path or the raw step text
+ assertFalse(ui.contains("Environment") || ui.contains("filesDir") || ui.contains("File("))
+ }
+
+ @Test fun withoutTheSwitchTheScreenSaysWhereToTurnItOn() {
+ assertTrue(src("ui/SessionScreen.kt").contains("R.string.session_hint"))
+ assertTrue(strings.contains("Show session details on the phone"))
+ assertTrue(src("app/AppModel.kt").contains("detailsOffered = Protocol.CAP_DETAILS in caps"))
+ }
+
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/SheetsTest.kt b/android/app/src/test/kotlin/com/coucou/android/SheetsTest.kt
new file mode 100644
index 00000000..9b97472f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/SheetsTest.kt
@@ -0,0 +1,123 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Guards for the approval and question sheets (Compose cannot be rendered in a JVM test, so these read the
+ * sources). The point of the redesign here: no raw command on screen unless asked for, and nothing about Allow gets weaker.
+ */
+class SheetsTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+ private val sheets get() = src("ui/Sheets.kt")
+ private val main get() = src("MainActivity.kt")
+
+ @Test fun theCommandIsOnlyDrawnAfterShowExactCommand() {
+ assertEquals("the command is drawn in exactly one place", 1, Regex("""r\.command""").findAll(sheets).count())
+ val before = sheets.substringBefore("r.command")
+ assertTrue(before.substringAfterLast("if (showCommand)").length < 600)
+ assertTrue(before.contains("if (showCommand)"))
+ }
+
+ @Test fun aCutCommandIsSaidClearlyAndAllowIsOnlyOfferedWhenTheWholeCommandIsHere() {
+ assertTrue(sheets.contains("R.string.approval_too_long"))
+ // Allow is drawn only under the check, and the notice is not behind a tap.
+ assertTrue(sheets.substringAfter("val canAllow").substringBefore("PillKind.PRIMARY").contains("if (canAllow)"))
+ assertFalse(sheets.substringAfter("approval_too_long").substringBefore("canAllow").contains("showCommand"))
+ // The same rule at every door: the sheet's callback, the model, the notification and the island.
+ assertTrue(main.contains("ApprovalSheetPlan.canAllowHere(r)"))
+ assertTrue(src("app/AppModel.kt").substringAfter("fun decide(fingerprint").substringBefore("link?.decide").contains("canAllowHere(request)"))
+ assertTrue(src("app/Notifications.kt").contains("if (ApprovalSheetPlan.canAllowHere(r)) addAction"))
+ assertTrue(src("ui/IslandOverlay.kt").contains("if (s.canAllow)"))
+ }
+
+ @Test fun theCommandIsNeverCutByALineLimit() {
+ assertFalse(sheets.contains("maxLines = ApprovalSheetPlan.MAX"))
+ assertTrue(sheets.contains("verticalScroll(rememberScrollState())"))
+ }
+
+ @Test fun homeNoLongerDrawsARawCommand() {
+ // the only place left is the lock prompt, which must keep repeating the exact command
+ assertEquals(1, Regex("""r\.command""").findAll(main).count())
+ assertTrue(main.contains("\"${'$'}{r.tool}: ${'$'}{r.command}\""))
+ assertFalse(main.contains("fun ApprovalCard"))
+ assertFalse(src("ui/HomePanel.kt").contains(".command"))
+ }
+
+ @Test fun theSheetSaysTheKindOfActionAndNotTheTool() {
+ assertTrue(sheets.contains("ApprovalSheetPlan.action(r.tool)"))
+ assertTrue(sheets.contains("R.string.approval_wants"))
+ }
+
+ @Test fun allowStillGoesThroughTheLockAndDenyNeedsNone() {
+ assertFalse("the sheet never allows by itself", Regex("""allow\s*=\s*true""").containsMatchIn(sheets))
+ assertTrue(sheets.contains("onAllow(r)"))
+ assertTrue(main.contains("onAllow = ::approve"))
+ assertTrue(main.contains("BiometricGate.confirm("))
+ assertTrue(sheets.contains("model.decide(r.fingerprint, allow = false)"))
+ }
+
+ @Test fun bothButtonsIgnoreTapsDuringTheFirstMoments() {
+ assertTrue(sheets.contains("delay(ApprovalSheetPlan.GUARD_MS)"))
+ assertEquals(3, Regex("""enabled = armed""").findAll(sheets).count())
+ }
+
+ @Test fun theSheetCanBeClosedAndNeverCatchesTapsMeantForTheScrim() {
+ assertTrue(sheets.contains("BackHandler(onBack = onDismiss)"))
+ assertTrue(sheets.contains("detectTapGestures { }"))
+ assertTrue(main.contains("closedApproval = pending.fingerprint"))
+ assertTrue("Review request reopens it", main.contains("onReview = { closedApproval = null }"))
+ }
+
+ @Test fun aQuestionIsAnsweredOnlyAfterTheScreenLock() {
+ assertTrue(main.contains("focus.state == BotState.QUESTION"))
+ // The sheet never talks to the link itself: it hands the picks to the activity, which asks for the lock first.
+ assertFalse(sheets.contains("model.answerQuestion"))
+ val send = main.substringAfter("private fun sendAnswer").substringBefore("/** Allow:")
+ assertTrue(send.indexOf("BiometricGate.confirm") in 0 until send.indexOf("model.answerQuestion"))
+ assertTrue(send.contains("if (confirming) return"))
+ }
+
+ @Test fun thePicksAreNeverLoggedOrStored() {
+ val send = main.substringAfter("private fun sendAnswer").substringBefore("/** Allow:")
+ assertFalse(send.contains("Log."))
+ val flow = src("core/QuestionFlow.kt")
+ assertFalse(flow.contains("Log."))
+ assertFalse(sheets.substringAfter("fun QuestionSheet").contains("rememberSaveable"))
+ }
+
+ @Test fun theAnswerButtonHasTheSameTapGuardAsAllow() {
+ val q = sheets.substringAfter("fun QuestionSheet")
+ assertTrue(q.contains("ApprovalSheetPlan.GUARD_MS"))
+ assertTrue(q.contains("enabled = armed && QuestionFlow.complete"))
+ }
+ // ── the file-change sheet ──────────────────────────────────────────────────────
+
+ private val diffSheet get() = src("ui/DiffSheet.kt")
+
+ @Test fun theLinesOfAFileAreNeverLoggedStoredOrKeptAcrossRecreation() {
+ assertFalse(diffSheet.contains("Log."))
+ assertFalse(diffSheet.contains("rememberSaveable"))
+ val model = src("app/AppModel.kt")
+ val diffPart = model.substringAfter("A file's change (cap `diffs`)").substringBefore("override fun onApprovalResolved")
+ assertFalse(diffPart.contains("Log."))
+ assertFalse(diffPart.contains("kv.put") || diffPart.contains("store."))
+ assertTrue("closing the sheet forgets the lines", diffPart.contains("fun closeDiff()") && diffPart.contains("DiffState.Idle"))
+ }
+
+ @Test fun anAddedOrRemovedLineIsMarkedAndNotOnlyColoured() {
+ assertTrue(diffSheet.contains("'+' -> \"+\"") && diffSheet.contains("'-' -> \"−\""))
+ }
+
+ @Test fun unlinkingTheComputerClosesTheSheet() {
+ val model = src("app/AppModel.kt")
+ assertTrue(model.substringAfter("private fun stopLink()").take(120).contains("closeDiff()"))
+ }
+
+ @Test fun theSheetSaysWhenItCouldNotLoadOrWasCutOrIsTooLarge() {
+ for (s in listOf("file_failed", "file_gone", "file_too_large", "file_truncated", "file_loading")) assertTrue(s, diffSheet.contains("R.string.$s"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/TokensTest.kt b/android/app/src/test/kotlin/com/coucou/android/TokensTest.kt
new file mode 100644
index 00000000..f3d5f823
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/TokensTest.kt
@@ -0,0 +1,107 @@
+package com.coucou.android
+
+import com.coucou.android.core.IslandSurface
+import com.coucou.android.core.MotionSpec
+import com.coucou.android.core.Palette
+import com.coucou.android.core.StatusPalette
+import com.coucou.android.core.Radii
+import com.coucou.android.core.Spacing
+import com.coucou.android.core.Tokens
+import com.coucou.android.core.TypeScale
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The redesign's tokens: readable text on every surface it sits on, on the dark theme, and a scale that holds together. */
+class TokensTest {
+ private val themes = mapOf("dark" to Tokens.DARK)
+ private fun c(a: Long, b: Long) = Palette.contrast(a, b)
+
+ @Test fun primaryTextIsReadableOnEverySurface() {
+ for ((n, t) in themes) for (s in listOf(t.bg, t.panel, t.panel2, t.secondaryButton)) {
+ assertTrue("$n text on ${s.toString(16)}", c(t.text, s) >= 7.0)
+ assertTrue("$n dim text on ${s.toString(16)}", c(t.textDim, s) >= 4.5 || s == t.panel2 && c(t.textDim, s) >= 4.0)
+ }
+ }
+
+ @Test fun dimTextIsReadableOnThePageAndOnPanels() {
+ for ((n, t) in themes) for (s in listOf(t.bg, t.panel)) assertTrue("$n dim on ${s.toString(16)}", c(t.textDim, s) >= 4.5)
+ }
+
+ @Test fun faintTextIsOnlyForLargeTextAndIcons() {
+ for ((n, t) in themes) for (s in listOf(t.bg, t.panel)) assertTrue("$n faint", c(t.textFaint, s) >= 3.0)
+ }
+
+ @Test fun theMainButtonAndItsLabelAreReadable() {
+ for ((n, t) in themes) {
+ assertTrue("$n label", c(t.onPrimaryButton, t.primaryButton) >= 7.0)
+ assertTrue("$n button stands out from the panel", c(t.primaryButton, t.panel) >= 3.0)
+ }
+ }
+
+ @Test fun dangerTextIsReadableAndGreenIsVisibleAsADot() {
+ for ((n, t) in themes) for (s in listOf(t.bg, t.panel)) {
+ assertTrue("$n danger", c(t.danger, s) >= 4.5)
+ assertTrue("$n online dot", c(t.online, s) >= 3.0)
+ }
+ }
+
+ @Test fun panelsAreToldApartFromThePage() {
+ for ((n, t) in themes) {
+ assertTrue("$n panel border", c(t.line, t.panel) >= 1.1)
+ assertTrue("$n panel vs page", c(t.panel, t.bg) >= 1.05)
+ assertTrue("$n row vs panel", c(t.panel2, t.panel) >= 1.05)
+ }
+ }
+
+ @Test fun secondaryButtonsAreVisibleOnPanels() {
+ for ((n, t) in themes) assertTrue("$n secondary", c(t.secondaryButton, t.panel) >= 1.05)
+ }
+
+ @Test fun theAlwaysDarkIslandKeepsItsTextReadable() {
+ for (bg in listOf(IslandSurface.BLACK, IslandSurface.PANEL, IslandSurface.HERO)) {
+ assertTrue(c(IslandSurface.TEXT, bg) >= 7.0)
+ assertTrue(c(IslandSurface.TEXT_DIM, bg) >= 4.5)
+ }
+ }
+
+ @Test fun theWashIsSoft() {
+ assertTrue(Tokens.DARK.washAlpha in 0.3..0.6)
+ }
+
+ @Test fun spacingIsOneScaleOnAFourPointGrid() {
+ assertTrue(Spacing.SCALE.all { it % 4 == 0 })
+ assertEquals(Spacing.SCALE.sorted(), Spacing.SCALE)
+ assertTrue(Spacing.GUTTER in Spacing.SCALE && Spacing.GAP in Spacing.SCALE && Spacing.INSIDE in Spacing.SCALE)
+ assertEquals(48, Spacing.MIN_TOUCH)
+ }
+
+ @Test fun typeScaleGrowsAndHasRoomForItsLines() {
+ val sizes = TypeScale.ALL.map { it.sizeSp }
+ assertEquals(sizes.sortedDescending(), sizes)
+ for (t in TypeScale.ALL) {
+ assertTrue("${t.name} line height", t.lineSp >= t.sizeSp + 4)
+ assertTrue("${t.name} weight", t.weight in 400..700)
+ }
+ assertTrue("body text is at least 15 sp", TypeScale.BODY.sizeSp >= 15)
+ assertTrue("nothing under 12 sp", TypeScale.ALL.all { it.sizeSp >= 12 })
+ }
+
+ @Test fun radiiMatchThePc() {
+ assertEquals(20, Radii.PANEL)
+ assertEquals(22, Radii.ISLAND_EXPANDED)
+ assertEquals(14, Radii.ISLAND_COMPACT)
+ }
+
+ @Test fun statusDotsAreVisibleOnBlackAndDarkPanels() {
+ val surfaces = listOf(Tokens.DARK.bg, Tokens.DARK.panel, IslandSurface.HERO, IslandSurface.BLACK)
+ for (c in listOf(StatusPalette.ONLINE, StatusPalette.BUSY, StatusPalette.OFFLINE)) for (s in surfaces) {
+ assertTrue("${c.toString(16)} on ${s.toString(16)}", Palette.contrast(c, s) >= 3.0)
+ }
+ }
+
+ @Test fun reducedMotionFollowsTheAnimatorScale() {
+ assertTrue(MotionSpec.isReduced(0f))
+ assertTrue(!MotionSpec.isReduced(1f) && !MotionSpec.isReduced(0.5f))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/ToolLabelsTest.kt b/android/app/src/test/kotlin/com/coucou/android/ToolLabelsTest.kt
new file mode 100644
index 00000000..0648f25e
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/ToolLabelsTest.kt
@@ -0,0 +1,54 @@
+package com.coucou.android
+
+import com.coucou.android.core.ToolLabels
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Test
+
+class ToolLabelsTest {
+ @Test fun knownToolsBecomePlainSentences() {
+ assertEquals("Asking a question", ToolLabels.label("ask_question"))
+ assertEquals("Asking a question", ToolLabels.label("AskUserQuestion"))
+ assertEquals("Running a command", ToolLabels.label("Bash"))
+ assertEquals("Reading files", ToolLabels.label("Read"))
+ assertEquals("Editing files", ToolLabels.label("Edit"))
+ assertEquals("Editing files", ToolLabels.label("MultiEdit"))
+ assertEquals("Editing files", ToolLabels.label("write_file"))
+ assertEquals("Searching files", ToolLabels.label("Grep"))
+ assertEquals("Searching the web", ToolLabels.label("WebSearch"))
+ }
+
+ @Test fun caseAndSeparatorsDoNotMatter() {
+ assertEquals("Running a command", ToolLabels.label(" bash "))
+ assertEquals("Running a command", ToolLabels.label("BASH"))
+ assertEquals("Running a command", ToolLabels.label("run_shell_command"))
+ }
+
+ @Test fun anUnknownToolIsOnlyCleaned() {
+ assertEquals("Mcp github list issues", ToolLabels.label("mcp__github__list_issues"))
+ assertEquals("Foo bar", ToolLabels.label("FooBar"))
+ assertEquals("Deploy preview", ToolLabels.label("deploy-preview"))
+ assertFalse(ToolLabels.label("some_odd_tool").contains('_'))
+ }
+
+ @Test fun aShellStepShowsOnlyTheProgramAndOtherStepsNoDetailAtAll() {
+ assertEquals("Running a command · npm", ToolLabels.label("Bash · npm test"))
+ assertEquals("Reading files", ToolLabels.label("Read · "))
+ assertEquals("Editing files", ToolLabels.label("Edit · /home/me/secret/plan.md"))
+ assertEquals("Reading files", ToolLabels.label("Read · C:\\Users\\me\\.ssh\\id_rsa"))
+ }
+
+ @Test fun freeTextAndPastedSecretsGiveNothing() {
+ assertEquals("", ToolLabels.label("Running npm test"))
+ assertEquals("", ToolLabels.label("All done"))
+ assertEquals("", ToolLabels.label("src/main.rs"))
+ assertEquals("", ToolLabels.label("Build failed: 2 errors"))
+ assertEquals("", ToolLabels.label("sk-live-4242424242424242"))
+ assertEquals("", ToolLabels.label("AbCdEfGhIjKlMnOpQrStUvWxYz0123"))
+ }
+
+ @Test fun emptyStaysEmpty() {
+ assertEquals("", ToolLabels.label(""))
+ assertEquals("", ToolLabels.label(" "))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/UsagePanelTest.kt b/android/app/src/test/kotlin/com/coucou/android/UsagePanelTest.kt
new file mode 100644
index 00000000..09561479
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/UsagePanelTest.kt
@@ -0,0 +1,28 @@
+package com.coucou.android
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class UsagePanelTest {
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+
+ @Test fun everyBarSaysItsPercentageInWordsAndNotOnlyInColour() {
+ val panel = src("ui/UsagePanel.kt")
+ assertTrue(panel.contains("R.string.usage_pct"))
+ assertTrue(panel.contains("R.string.usage_desc"))
+ }
+
+ @Test fun nothingIsLoggedOrStoredAndItGoesWhenTheLinkOrTheOfferDoes() {
+ assertFalse(src("ui/UsagePanel.kt").contains("Log."))
+ val model = src("app/AppModel.kt")
+ assertTrue(model.substringAfter("private fun stopLink()").take(100).contains("usage = null"))
+ assertTrue(model.contains("if (Protocol.CAP_USAGE !in caps) usage = null"))
+ assertFalse(model.substringAfter("override fun onUsage").take(300).contains("kv.put"))
+ }
+
+ @Test fun homeShowsThePanelOnlyWhenThereIsUsage() {
+ assertTrue(src("MainActivity.kt").contains("if (model.usage != null) item"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/UserSettingsTest.kt b/android/app/src/test/kotlin/com/coucou/android/UserSettingsTest.kt
new file mode 100644
index 00000000..7a503a87
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/UserSettingsTest.kt
@@ -0,0 +1,185 @@
+package com.coucou.android
+
+import com.coucou.android.core.Announce
+import com.coucou.android.core.Decision
+import com.coucou.android.core.DecisionLog
+import com.coucou.android.core.HistoryDays
+import com.coucou.android.core.KeyValueStore
+import com.coucou.android.core.QuietHours
+import com.coucou.android.core.StatusPolicy
+import com.coucou.android.core.UserSettings
+import com.coucou.android.mochi.BotState
+import java.time.ZoneId
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class UserSettingsTest {
+ private class Memory : KeyValueStore {
+ val map = HashMap<String, Any>()
+ override fun getBoolean(key: String, default: Boolean) = map[key] as? Boolean ?: default
+ override fun getInt(key: String, default: Int) = map[key] as? Int ?: default
+ override fun getFloat(key: String, default: Float) = map[key] as? Float ?: default
+ override fun getString(key: String, default: String) = map[key] as? String ?: default
+ override fun put(key: String, value: Any) { map[key] = value }
+ }
+
+ private val noon = 12 * 60
+ private val night = 23 * 60
+ private val s = UserSettings()
+
+ // ── settings ────────────────────────────────────────────────────────────
+
+ @Test fun defaultsKeepTheAppAsItWas() {
+ val loaded = UserSettings.load(Memory())
+ assertTrue(loaded.soundOn)
+ assertEquals(0.12f, loaded.volume, 0f)
+ assertTrue(loaded.notifyDone)
+ assertFalse(loaded.quiet.enabled)
+ }
+
+ @Test fun theRelayIsUsedByDefaultAndTheChoiceSurvivesARestart() {
+ assertTrue("on by default: it only matters when the pairing has a relay", UserSettings.load(Memory()).useRelay)
+ val disk = Memory()
+ UserSettings.save(disk, UserSettings(useRelay = false))
+ assertFalse(UserSettings.load(disk).useRelay)
+ }
+
+ @Test fun settingsSurviveARestart() {
+ val disk = Memory()
+ UserSettings.save(disk, UserSettings(soundOn = false, volume = 0.05f, notifyDone = false, quiet = QuietHours(true, 21 * 60, 7 * 60 + 30)))
+ val back = UserSettings.load(disk)
+ assertFalse(back.soundOn)
+ assertEquals(0.05f, back.volume, 0f)
+ assertFalse(back.notifyDone)
+ assertEquals(QuietHours(true, 21 * 60, 7 * 60 + 30), back.quiet)
+ }
+
+ @Test fun volumeNeverExceedsTheSpecMaximum() {
+ val disk = Memory()
+ UserSettings.save(disk, UserSettings(volume = 9f))
+ assertEquals(0.2f, UserSettings.load(disk).volume, 0f)
+ }
+
+ @Test fun quietHoursCrossMidnight() {
+ val q = QuietHours(true, 22 * 60, 8 * 60)
+ assertTrue(q.isQuiet(23 * 60))
+ assertTrue(q.isQuiet(3 * 60))
+ assertFalse(q.isQuiet(8 * 60))
+ assertFalse(q.isQuiet(noon))
+ assertTrue(q.isQuiet(22 * 60))
+ }
+
+ @Test fun quietHoursWithinTheDayAndWhenOff() {
+ assertTrue(QuietHours(true, 13 * 60, 14 * 60).isQuiet(13 * 60 + 30))
+ assertFalse(QuietHours(true, 13 * 60, 14 * 60).isQuiet(noon))
+ assertFalse(QuietHours(false, 22 * 60, 8 * 60).isQuiet(night))
+ assertFalse(QuietHours(true, 9 * 60, 9 * 60).isQuiet(9 * 60)) // an empty window is never quiet
+ assertEquals(23 * 60 + 30, QuietHours.wrap(-30))
+ assertEquals(30, QuietHours.wrap(24 * 60 + 30))
+ }
+
+ // ── what to announce ────────────────────────────────────────────────────
+
+ @Test fun finishingAnnouncesWhenYouAreElsewhere() {
+ assertEquals(Announce(sound = true, notify = true, pill = true), StatusPolicy.announce(BotState.WORKING, BotState.FINISHED, s, noon, appInForeground = false))
+ assertEquals(Announce(sound = true, notify = true, pill = true), StatusPolicy.announce(BotState.WORKING, BotState.ERROR, s, noon, false))
+ }
+
+ @Test fun theFirstPictureAfterConnectingIsQuiet() {
+ for (st in listOf(BotState.FINISHED, BotState.ERROR, BotState.QUESTION, BotState.RATELIMIT)) {
+ assertEquals(Announce.NONE, StatusPolicy.announce(null, st, s, noon, false))
+ }
+ }
+
+ @Test fun ordinaryWorkIsNotNews() {
+ assertEquals(Announce.NONE, StatusPolicy.announce(BotState.IDLE, BotState.WORKING, s, noon, false))
+ assertEquals(Announce.NONE, StatusPolicy.announce(BotState.FINISHED, BotState.FINISHED, s, noon, false))
+ assertEquals(Announce.NONE, StatusPolicy.announce(BotState.WORKING, BotState.APPROVAL, s, noon, false))
+ }
+
+ @Test fun insideTheAppNothingPopsUpButTheSoundStays() {
+ assertEquals(Announce(sound = true, notify = false, pill = false), StatusPolicy.announce(BotState.WORKING, BotState.FINISHED, s, noon, appInForeground = true))
+ }
+
+ @Test fun theSwitchTurnsFinishedAndFailedOffButNotQuestions() {
+ val off = s.copy(notifyDone = false)
+ assertEquals(Announce.NONE, StatusPolicy.announce(BotState.WORKING, BotState.FINISHED, off, noon, false))
+ assertEquals(Announce.NONE, StatusPolicy.announce(BotState.WORKING, BotState.ERROR, off, noon, false))
+ assertTrue(StatusPolicy.announce(BotState.WORKING, BotState.QUESTION, off, noon, false).notify)
+ }
+
+ @Test fun quietHoursKeepTheNoticeInTheShadeWithoutSoundOrPill() {
+ val quiet = s.copy(quiet = QuietHours(true, 22 * 60, 8 * 60))
+ assertEquals(Announce(sound = false, notify = true, pill = false), StatusPolicy.announce(BotState.WORKING, BotState.FINISHED, quiet, night, false))
+ // A question needs the user: quiet hours do not hide it.
+ assertEquals(Announce(sound = true, notify = true, pill = true), StatusPolicy.announce(BotState.WORKING, BotState.QUESTION, quiet, night, false))
+ }
+
+ @Test fun soundOffMeansNoSoundAnywhere() {
+ val mute = s.copy(soundOn = false)
+ assertFalse(StatusPolicy.announce(BotState.WORKING, BotState.FINISHED, mute, noon, false).sound)
+ assertFalse(StatusPolicy.stateSoundWanted(BotState.WORKING, BotState.APPROVAL, mute))
+ assertTrue(StatusPolicy.stateSoundWanted(BotState.WORKING, BotState.APPROVAL, s))
+ assertFalse(StatusPolicy.stateSoundWanted(null, BotState.APPROVAL, s))
+ }
+
+ // ── decision history ────────────────────────────────────────────────────
+
+ @Test fun historyKeepsNewestFirstAndAtMostFifty() {
+ val log = DecisionLog(Memory())
+ for (i in 1..60) log.add(Decision("Claude", "Bash", "cmd $i", allowed = i % 2 == 0, atMs = i.toLong()))
+ val all = log.all()
+ assertEquals(DecisionLog.MAX, all.size)
+ assertEquals("cmd 60", all.first().command)
+ assertEquals("cmd 11", all.last().command)
+ assertTrue(all.first().allowed)
+ assertFalse(all[1].allowed)
+ }
+
+ @Test fun historyCutsLongCommandsAndSurvivesOddCharacters() {
+ val disk = Memory()
+ DecisionLog(disk).add(Decision("A\u001Eb", "Bash", "x".repeat(500) + "\u001Fy\nz", allowed = false, atMs = 5))
+ val d = DecisionLog(disk).all().single()
+ assertEquals(DecisionLog.COMMAND_MAX, d.command.length)
+ assertEquals("A b", d.agent)
+ assertFalse(d.allowed)
+ }
+
+ @Test fun clearingEmptiesTheHistory() {
+ val log = DecisionLog(Memory())
+ log.add(Decision("A", "Bash", "ls", true, 1))
+ log.clear()
+ assertTrue(log.all().isEmpty())
+ }
+
+ @Test fun historyIsGroupedByDay() {
+ val zone = ZoneId.of("UTC")
+ val now = java.time.ZonedDateTime.of(2026, 10, 9, 15, 0, 0, 0, zone).toInstant().toEpochMilli()
+ fun at(day: Int, hour: Int) = java.time.ZonedDateTime.of(2026, 10, day, hour, 0, 0, 0, zone).toInstant().toEpochMilli()
+ val list = listOf(
+ Decision("A", "Bash", "1", true, at(9, 14)), Decision("A", "Bash", "2", true, at(9, 1)),
+ Decision("A", "Bash", "3", false, at(8, 23)), Decision("A", "Bash", "4", false, at(2, 10)),
+ )
+ val groups = HistoryDays.group(list, now, zone)
+ assertEquals(listOf(HistoryDays.Day.TODAY, HistoryDays.Day.YESTERDAY, HistoryDays.Day.OTHER), groups.map { it.first.first })
+ assertEquals(listOf(2, 1, 1), groups.map { it.second.size })
+ }
+ @Test fun theOutfitChoiceIsKeptAndDefaultsToTheComputers() {
+ val m = Memory()
+ assertEquals("computer", UserSettings.load(m).outfit)
+ UserSettings.save(m, UserSettings(outfit = "crown"))
+ assertEquals("crown", UserSettings.load(m).outfit)
+ UserSettings.save(m, UserSettings(outfit = "auto"))
+ assertEquals("auto", UserSettings.load(m).outfit)
+ }
+
+ @Test fun anOutfitChoiceNoBuildKnowsFollowsTheComputer() {
+ val m = Memory()
+ m.map["outfit_choice"] = "topHat"
+ assertEquals("computer", UserSettings.load(m).outfit)
+ UserSettings.save(m, UserSettings(outfit = "<script>"))
+ assertEquals("computer", m.map["outfit_choice"])
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ApprovalBookTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ApprovalBookTest.kt
new file mode 100644
index 00000000..d0c4d93a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ApprovalBookTest.kt
@@ -0,0 +1,57 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class ApprovalBookTest {
+ private var now = 1_000_000L
+ private val book = ApprovalBook { now }
+ private fun req(fp: String, created: Long = now) = ApprovalRequest("p", fp, "Bash", "ls", created)
+
+ @Test fun claimedRequestCanOnlyBeDecidedOnce() {
+ book.add(req("a"))
+ assertNotNull(book.claim("a"))
+ assertNull(book.claim("a"))
+ }
+
+ @Test fun unknownRequestCannotBeDecided() {
+ assertNull(book.claim("never-seen"))
+ }
+
+ @Test fun expiresAfterTheTtl() {
+ book.add(req("a"))
+ now += Protocol.APPROVAL_TTL_MS - 1
+ assertEquals(1, book.active().size)
+ now += 1
+ assertEquals(0, book.active().size)
+ }
+
+ @Test fun theDesktopsClockDoesNotDecideWhetherARequestIsExpired() {
+ // A computer whose clock is 10 minutes behind (or ahead) of the phone's.
+ book.add(req("slow", created = now - 600_000))
+ book.add(req("fast", created = now + 600_000))
+ assertNotNull("a fresh request must be decidable", book.claim("slow"))
+ assertNotNull("a fresh request must be decidable", book.claim("fast"))
+ }
+
+ @Test fun aRequestSentAgainKeepsItsFirstArrivalTime() {
+ book.add(req("a"))
+ now += Protocol.APPROVAL_TTL_MS - 1_000
+ book.add(req("a")) // the link dropped and came back: the desktop offers it again
+ now += 1_000
+ assertNull("it must not live longer for having been sent twice", book.claim("a"))
+ }
+
+ @Test fun resolvedByTheDesktopDisappears() {
+ book.add(req("a"))
+ book.resolve("a")
+ assertNull(book.claim("a"))
+ }
+
+ @Test fun keepsArrivalOrder() {
+ book.add(req("a")); book.add(req("b")); book.add(req("c"))
+ assertEquals(listOf("a", "b", "c"), book.active().map { it.fingerprint })
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/DemoLinkTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/DemoLinkTest.kt
new file mode 100644
index 00000000..2e7044c2
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/DemoLinkTest.kt
@@ -0,0 +1,74 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class DemoLinkTest {
+ private class Rec : LinkListener {
+ val states = mutableListOf<LinkState>()
+ val sessions = mutableListOf<List<SessionInfo>>()
+ val approvals = mutableListOf<ApprovalRequest>()
+ val resolved = mutableListOf<String>()
+ override fun onState(state: LinkState) { states.add(state) }
+ override fun onSessions(sessions: List<SessionInfo>) { this.sessions.add(sessions) }
+ override fun onApproval(request: ApprovalRequest) { approvals.add(request) }
+ override fun onApprovalResolved(fingerprint: String) { resolved.add(fingerprint) }
+ }
+
+ private fun demo(rec: Rec) = DemoLink(rec, autoRun = false).also { it.start() }
+
+ @Test fun startsConnected() {
+ val rec = Rec()
+ demo(rec)
+ assertEquals(listOf(LinkState.CONNECTED), rec.states)
+ }
+
+ @Test fun scriptShowsEveryStateTheAppDraws() {
+ val rec = Rec()
+ val d = demo(rec)
+ repeat(DemoLink.STEPS) { d.step() }
+ val seen = rec.sessions.flatten().map { it.state }.toSet()
+ for (s in listOf(BotState.THINKING, BotState.WORKING, BotState.SEARCHING, BotState.APPROVAL, BotState.QUESTION,
+ BotState.ERROR, BotState.FINISHED, BotState.RATELIMIT, BotState.SLEEPING)) assertTrue("$s", s in seen)
+ }
+
+ @Test fun scriptLoopsForever() {
+ val rec = Rec()
+ val d = demo(rec)
+ repeat(DemoLink.STEPS * 3) { d.step() }
+ assertEquals(DemoLink.STEPS * 3, rec.sessions.size)
+ assertEquals(3, rec.approvals.size)
+ }
+
+ @Test fun demoApprovalCanBeAnsweredOnceLocally() {
+ val rec = Rec()
+ val d = demo(rec)
+ repeat(3) { d.step() }
+ val req = rec.approvals.single()
+ assertEquals(DemoLink.FINGERPRINT, req.fingerprint)
+ assertTrue(Wire.isFingerprint(req.fingerprint))
+ assertTrue(d.decide(req.fingerprint, allow = true))
+ assertFalse(d.decide(req.fingerprint, allow = true))
+ assertEquals(listOf(DemoLink.FINGERPRINT), rec.resolved)
+ }
+
+ @Test fun unansweredDemoApprovalIsRetractedAtTheEndOfTheLoop() {
+ val rec = Rec()
+ val d = demo(rec)
+ repeat(DemoLink.STEPS) { d.step() }
+ assertEquals(listOf(DemoLink.FINGERPRINT), rec.resolved)
+ assertTrue(d.approvals.active().isEmpty())
+ }
+
+ @Test fun stopClearsPendingApprovals() {
+ val rec = Rec()
+ val d = demo(rec)
+ repeat(3) { d.step() }
+ d.stop()
+ assertFalse(d.decide(DemoLink.FINGERPRINT, true))
+ assertEquals(LinkState.DISCONNECTED, rec.states.last())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/DevDesktopInteropTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/DevDesktopInteropTest.kt
new file mode 100644
index 00000000..54c42009
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/DevDesktopInteropTest.kt
@@ -0,0 +1,401 @@
+package com.coucou.android.link
+
+import com.coucou.android.ReferenceFiles
+import java.io.BufferedReader
+import java.io.InputStreamReader
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/**
+ * The real [LinkClient] against android/tools/dev-desktop.mjs, a separate implementation of the
+ * protocol (Node's TLS stack, its own certificate). Skipped when node or openssl is missing.
+ */
+class DevDesktopInteropTest {
+ private var proc: Process? = null
+ private val lines = LinkedBlockingQueue<String>()
+
+ @After fun cleanup() { proc?.destroyForcibly() }
+
+ // `openssl --version` is not a command (it is `openssl version`): the old check made these tests skip everywhere.
+ private fun have(cmd: String, versionArg: String = "--version") = try {
+ ProcessBuilder(cmd, versionArg).redirectErrorStream(true).start().also { it.inputStream.readBytes() }.waitFor() == 0
+ } catch (_: Exception) { false }
+
+ private fun startDesktop(vararg extra: String): JSONObject {
+ assumeTrue("node not available", have("node"))
+ assumeTrue("openssl not available", have("openssl", "version"))
+ val script = ReferenceFiles.file("android/tools/dev-desktop.mjs").absolutePath
+ proc = ProcessBuilder(listOf("node", script, "--host", "127.0.0.1", "--port", "0", "--quiet", "--step", "300") + extra)
+ .redirectErrorStream(true).start()
+ Thread {
+ BufferedReader(InputStreamReader(proc!!.inputStream)).forEachLine { lines.add(it) }
+ }.apply { isDaemon = true; start() }
+ val first = lines.poll(20, TimeUnit.SECONDS)
+ assertNotNull("dev desktop did not start", first)
+ return JSONObject(first!!)
+ }
+
+ private class Rec : LinkListener {
+ val welcome = LinkedBlockingQueue<String>()
+ val sessions = LinkedBlockingQueue<List<SessionInfo>>()
+ val approvals = LinkedBlockingQueue<ApprovalRequest>()
+ val resolved = LinkedBlockingQueue<String>()
+ val errors = LinkedBlockingQueue<String>()
+ override fun onWelcome(desktopName: String, os: String) { welcome.add(desktopName) }
+ override fun onSessions(sessions: List<SessionInfo>) { this.sessions.add(sessions) }
+ override fun onApproval(request: ApprovalRequest) { approvals.add(request) }
+ override fun onApprovalResolved(fingerprint: String) { resolved.add(fingerprint) }
+ override fun onError(code: String, message: String) { errors.add(code) }
+ val serviceCards = LinkedBlockingQueue<List<ServiceCard>>()
+ override fun onServices(cards: List<ServiceCard>) { serviceCards.add(cards) }
+ val usages = LinkedBlockingQueue<UsageSnapshot>()
+ override fun onUsage(usage: UsageSnapshot) { usages.add(usage) }
+ val diffParts = LinkedBlockingQueue<ServerMsg.Diff>()
+ override fun onDiff(part: ServerMsg.Diff) { diffParts.add(part) }
+ val questions = LinkedBlockingQueue<QuestionRequest>()
+ override fun onQuestion(request: QuestionRequest) { questions.add(request) }
+ val caps = LinkedBlockingQueue<Set<String>>()
+ val chat = LinkedBlockingQueue<String>()
+ override fun onCaps(caps: Set<String>) { this.caps.add(caps) }
+ override fun onChatModels(models: List<ChatModel>) { chat.add("models:" + models.joinToString(",") { it.id }) }
+ override fun onChatDelta(id: String, text: String) { chat.add("delta:$id:$text") }
+ override fun onChatDone(id: String, text: String?) { chat.add("done:$id:${text ?: "-"}") }
+ override fun onChatError(id: String, reason: String, message: String) { chat.add("error:$id:$reason") }
+
+ /** Everything of one answer until its end. */
+ fun answer(id: String, seconds: Long = 10): Pair<String, String> {
+ val text = StringBuilder()
+ val deadline = System.currentTimeMillis() + seconds * 1000
+ while (System.currentTimeMillis() < deadline) {
+ val e = chat.poll(200, TimeUnit.MILLISECONDS) ?: continue
+ when {
+ e.startsWith("delta:$id:") -> text.append(e.removePrefix("delta:$id:"))
+ e.startsWith("done:$id:") -> return text.toString() to ("done:" + e.removePrefix("done:$id:"))
+ e.startsWith("error:$id:") -> return text.toString() to e
+ }
+ }
+ error("no end of answer for $id")
+ }
+ }
+
+ private fun chatClient(info: JSONObject, rec: Rec, caps: List<String> = Protocol.CAPABILITIES): LinkClient =
+ LinkClient(PairingPayload.parse(info.getString("link"))!!, "Interop Pixel", rec, readTimeoutMs = 5_000, caps = caps)
+
+ @Test fun pairsReceivesSessionsAndApprovalAndDecides() {
+ val info = startDesktop("--once")
+ val pairing = PairingPayload.parse(info.getString("link"))
+ assertNotNull("pairing link not parsed: ${info.getString("link")}", pairing)
+ val rec = Rec()
+ val client = LinkClient(pairing!!, "Interop Pixel", rec, readTimeoutMs = 5_000)
+ try {
+ client.start()
+ assertNotNull(rec.welcome.poll(10, TimeUnit.SECONDS))
+ assertTrue(rec.sessions.poll(10, TimeUnit.SECONDS)!!.isNotEmpty())
+ val req = rec.approvals.poll(10, TimeUnit.SECONDS)
+ assertNotNull("no approval request arrived", req)
+ // The fingerprint must be the one the Mac-compatible derivation yields for these fields.
+ assertTrue(Wire.isFingerprint(req!!.fingerprint))
+ assertTrue(client.decide(req.fingerprint, allow = true))
+ assertEquals(req.fingerprint, rec.resolved.poll(10, TimeUnit.SECONDS))
+ val deadline = System.currentTimeMillis() + 10_000
+ var sawDecision = false
+ while (!sawDecision && System.currentTimeMillis() < deadline) {
+ val l = lines.poll(1, TimeUnit.SECONDS) ?: continue
+ if (l == "DECISION allow ${req.fingerprint}") sawDecision = true
+ }
+ assertTrue("desktop never logged the decision", sawDecision)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun wrongTokenIsRejectedByTheNodeDesktop() {
+ val info = startDesktop()
+ val good = PairingPayload.parse(info.getString("link"))!!
+ val rec = Rec()
+ val client = LinkClient(good.copy(token = "x".repeat(24)), "Interop Pixel", rec, readTimeoutMs = 5_000)
+ try {
+ client.start()
+ assertEquals("auth", rec.errors.poll(10, TimeUnit.SECONDS))
+ assertTrue(rec.welcome.isEmpty())
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── answering a question, against the fake question of the Node desktop ─────────
+
+ @Test fun aQuestionIsAnsweredAndRemovedOnTheNodeDesktop() {
+ val info = startDesktop("--answers", "--once")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("answers"), rec.caps.poll(10, TimeUnit.SECONDS))
+ val q = rec.questions.poll(20, TimeUnit.SECONDS)
+ assertNotNull("no question arrived", q)
+ assertEquals(2, q!!.questions.size)
+ assertEquals(true, q.questions[1].multiSelect)
+ // Refused by the desktop: a label it never offered, then two picks for a single choice.
+ assertTrue(client.answer(q.fingerprint, listOf(listOf("nope"), listOf("Lint"))))
+ assertTrue(client.answer(q.fingerprint, listOf(listOf("main", "develop"), listOf("Lint"))))
+ assertNull(rec.resolved.poll(1, TimeUnit.SECONDS))
+ assertTrue(client.answer(q.fingerprint, listOf(listOf("develop"), listOf("Lint", "Build"))))
+ assertEquals(q.fingerprint, rec.resolved.poll(10, TimeUnit.SECONDS))
+ val deadline = System.currentTimeMillis() + 10_000
+ val seen = mutableListOf<String>()
+ while (System.currentTimeMillis() < deadline && seen.none { it.startsWith("ANSWER accepted") }) {
+ lines.poll(1, TimeUnit.SECONDS)?.let { seen.add(it) }
+ }
+ assertEquals(2, seen.count { it.startsWith("ANSWER refused") })
+ assertTrue(seen.any { it.startsWith("ANSWER accepted") })
+ assertTrue("the picked labels must not be logged", seen.none { it.contains("Build") || it.contains("develop") })
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun theServiceCardsComeWithTheSwitchOnTheNodeDesktop() {
+ val info = startDesktop("--services")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("services"), rec.caps.poll(10, TimeUnit.SECONDS))
+ val cards = rec.serviceCards.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(listOf("integration_stripe", "integration_notion"), cards.map { it.id })
+ assertEquals("Roadmap", cards[1].items[0].label)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun theUsageComesWithTheSwitchOnTheNodeDesktop() {
+ val info = startDesktop("--usage")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("usage"), rec.caps.poll(10, TimeUnit.SECONDS))
+ val u = rec.usages.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(21, u.claude!!.sevenDay!!.pct)
+ assertEquals(2, u.codex!!.resetCredits)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun filesAreListedAndTheirLinesComeInPartsOnTheNodeDesktop() {
+ val info = startDesktop("--diffs")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("diffs"), rec.caps.poll(10, TimeUnit.SECONDS))
+ val files = generateSequence { rec.sessions.poll(10, TimeUnit.SECONDS) }.take(5).first { l -> l.any { it.files.isNotEmpty() } }
+ .first { it.files.isNotEmpty() }.files
+ assertEquals(listOf("app.ts", "long-file.ts", "generated.json"), files.map { it.name })
+ assertTrue(files[2].tooLarge)
+
+ assertTrue(client.getDiff("integration_claude", 1))
+ val small = rec.diffParts.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(5, small.lines.size)
+ assertEquals('@', small.lines[0].kind)
+
+ assertTrue(client.getDiff("integration_claude", 2))
+ val a = rec.diffParts.poll(10, TimeUnit.SECONDS)!!
+ val b = rec.diffParts.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(listOf(0 to 2, 1 to 2), listOf(a.part to a.parts, b.part to b.parts))
+ assertEquals(200, a.lines.size + b.lines.size)
+ assertTrue(a.truncated)
+ assertTrue("a long line is cut", (a.lines + b.lines).all { it.text.length <= Protocol.MAX_DIFF_LINE_CHARS })
+
+ assertTrue(client.getDiff("integration_claude", 99))
+ assertTrue(rec.diffParts.poll(10, TimeUnit.SECONDS)!!.gone)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withoutTheSwitchTheNodeDesktopListsNoFilesAndAnswersNoRequest() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertNotNull(rec.welcome.poll(10, TimeUnit.SECONDS))
+ assertTrue(!client.getDiff("integration_claude", 1))
+ assertNull(rec.diffParts.poll(2, TimeUnit.SECONDS))
+ assertTrue(generateSequence { rec.sessions.poll(1, TimeUnit.SECONDS) }.take(3).all { l -> l.all { it.files.isEmpty() } })
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withoutTheSwitchTheNodeDesktopOffersNoQuestion() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertNotNull(rec.welcome.poll(10, TimeUnit.SECONDS))
+ assertNull(rec.questions.poll(3, TimeUnit.SECONDS))
+ assertTrue(!client.answer("a".repeat(64), listOf(listOf("x"))))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── chat, against the fake provider of the Node desktop ─────────────────────────
+
+ @Test fun chatWorksAgainstTheFakeProvider() {
+ val info = startDesktop("--fake-chat")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("chat"), rec.caps.poll(10, TimeUnit.SECONDS))
+ assertEquals("models:fake/echo,fake/other", rec.chat.poll(10, TimeUnit.SECONDS))
+ assertTrue(client.chatSend("c1", "fake/echo", "hello there"))
+ val (text, end) = rec.answer("c1")
+ assertEquals("Fake answer to: hello there", text)
+ assertEquals("done:-", end)
+
+ // the desktop's own refusals arrive as codes
+ client.chatSend("c2", "fake/echo", "/error")
+ assertEquals("error:c2:provider", rec.answer("c2").second)
+ client.chatSend("c3", "fake/echo", "/auth")
+ assertEquals("error:c3:auth", rec.answer("c3").second)
+ client.chatSend("c4", "not/allowed", "hi")
+ assertEquals("error:c4:not_allowed", rec.answer("c4").second)
+ client.chatSend("c5", "fake/echo", "x".repeat(Protocol.CHAT_MAX_TEXT + 1))
+ assertEquals("error:c5:too_long", rec.answer("c5").second)
+
+ // a long answer arrives in pieces that add up
+ client.chatSend("c6", "fake/echo", "/long")
+ val (long, longEnd) = rec.answer("c6")
+ assertEquals("done:-", longEnd)
+ assertEquals(750 * "Lorem ipsum dolor sit amet. ".length, long.length)
+
+ // a rewritten answer is replaced by the final one
+ client.chatSend("c7", "fake/echo", "/rewrite")
+ assertEquals("done:Answer", rec.answer("c7").second)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun oneAnswerAtATimeAndCancelStopsIt() {
+ val info = startDesktop("--fake-chat")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertNotNull(rec.caps.poll(10, TimeUnit.SECONDS))
+ client.chatSend("s1", "fake/echo", "/slow")
+ assertTrue("never started", generateSequence { rec.chat.poll(5, TimeUnit.SECONDS) }.take(20).any { it.startsWith("delta:s1:") })
+ client.chatSend("s2", "fake/echo", "second")
+ assertEquals("error:s2:busy", rec.answer("s2").second)
+ client.chatCancel("s1")
+ assertEquals("error:s1:canceled", rec.answer("s1").second)
+ client.chatSend("s3", "fake/echo", "after")
+ assertEquals("Fake answer to: after", rec.answer("s3").first)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun anOlderAppOrAnOlderComputerSeesNoChat() {
+ // The desktop has chat but the app asks for nothing (an older app): not offered, nothing sent.
+ val info = startDesktop("--fake-chat")
+ val rec = Rec()
+ val client = chatClient(info, rec, caps = emptyList())
+ try {
+ client.start()
+ assertEquals(emptySet<String>(), rec.caps.poll(10, TimeUnit.SECONDS))
+ client.chatSend("o1", "fake/echo", "hi")
+ assertNull(rec.chat.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun aDesktopWithoutTheFakeProviderOffersNoChat() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(emptySet<String>(), rec.caps.poll(10, TimeUnit.SECONDS))
+ assertNull(rec.chat.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── session details, against the Node desktop ─────────────────────────────────────────
+
+ /** The first sessions message that has Claude Code in it. */
+ private fun claudeSession(rec: Rec): SessionInfo {
+ val deadline = System.currentTimeMillis() + 15_000
+ while (System.currentTimeMillis() < deadline) {
+ val list = rec.sessions.poll(1, TimeUnit.SECONDS) ?: continue
+ list.firstOrNull { it.pillId == "integration_claude" }?.let { return it }
+ }
+ error("no Claude Code session arrived")
+ }
+
+ @Test fun detailsArriveWhenTheDesktopOffersThem() {
+ val info = startDesktop("--details")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(setOf("details"), rec.caps.poll(10, TimeUnit.SECONDS))
+ val s = claudeSession(rec)
+ assertTrue(s.steps.isNotEmpty() && s.steps.first().startsWith("Read"))
+ assertEquals("coucou", s.project)
+ assertEquals("#2DD4BF", s.color)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun anOlderAppGetsPlainSessionsFromADesktopThatHasDetails() {
+ val info = startDesktop("--details")
+ val rec = Rec()
+ val client = chatClient(info, rec, caps = emptyList())
+ try {
+ client.start()
+ assertEquals(emptySet<String>(), rec.caps.poll(10, TimeUnit.SECONDS))
+ val s = claudeSession(rec)
+ assertEquals(emptyList<String>(), s.steps)
+ assertNull(s.project); assertNull(s.color); assertNull(s.finalLine)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun aDesktopWithoutDetailsSendsNoneEvenToAnAppThatAsks() {
+ val info = startDesktop() // no --details: an older desktop
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ client.start()
+ assertEquals(emptySet<String>(), rec.caps.poll(10, TimeUnit.SECONDS))
+ val s = claudeSession(rec)
+ assertEquals(emptyList<String>(), s.steps)
+ assertNull(s.project)
+ } finally {
+ client.stop()
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/DiagnosticsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/DiagnosticsTest.kt
new file mode 100644
index 00000000..777ae68a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/DiagnosticsTest.kt
@@ -0,0 +1,142 @@
+package com.coucou.android.link
+
+import java.net.ServerSocket
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** "Can't connect?": every check against a fake computer and fake network sources. */
+class DiagnosticsTest {
+ private val closeables = mutableListOf<AutoCloseable>()
+ @After fun cleanup() = closeables.forEach { runCatching { it.close() } }
+ private fun <T : AutoCloseable> T.track(): T { closeables.add(this); return this }
+
+ private val token = "T".repeat(20)
+ private fun pairing(d: FakeDesktop, fp: String = d.certSha256, tok: String = token, host: String = "127.0.0.1") =
+ PairingPayload(host, d.port, fp, tok, "My private PC name")
+
+ private fun env(
+ p: PairingPayload, wifi: Boolean = true, cellular: Boolean = false, found: List<Found> = emptyList(),
+ relay: (() -> DiagResult)? = null,
+ ) = LanDiagnostics(p, { wifi }, { cellular }, { found }, PinnedTls.connector(p), relay, timeoutMs = 1_500)
+
+ private fun results(e: DiagEnv) = Diagnostics.run(e).toMap()
+
+ @Test fun everythingGreenWhenTheComputerIsThereAndPaired() {
+ val d = FakeDesktop(tls = true).track()
+ val p = pairing(d)
+ val found = listOf(Found("PC", "127.0.0.1", d.port, Discovery.fingerprintId(d.certSha256), Discovery.TXT_VERSION))
+ val r = results(env(p, found = found))
+ for (step in listOf(DiagStep.NETWORK, DiagStep.ADDRESS, DiagStep.DISCOVERY, DiagStep.SECURE, DiagStep.TOKEN)) assertTrue("$step: ${r[step]}", r[step] is DiagResult.Ok)
+ assertFalse(r.containsKey(DiagStep.RELAY))
+ }
+
+ @Test fun noWifiMeansTheLaterLocalStepsAreSkippedNotGuessed() {
+ val d = FakeDesktop(tls = true).track()
+ val r = results(env(pairing(d), wifi = false))
+ assertTrue(r[DiagStep.NETWORK] is DiagResult.Problem)
+ assertTrue(r[DiagStep.ADDRESS] is DiagResult.Skipped)
+ assertTrue(r[DiagStep.DISCOVERY] is DiagResult.Skipped)
+ assertTrue(r[DiagStep.SECURE] is DiagResult.Skipped)
+ assertTrue(r[DiagStep.TOKEN] is DiagResult.Skipped)
+ }
+
+ @Test fun mobileDataIsFineWhenThePairingHasARelay() {
+ val d = FakeDesktop(tls = true).track()
+ val relay = RelayPairing("wss://relay.example.com", RelayCrypto.base64UrlEncode(ByteArray(16)), RelayCrypto.base64UrlEncode(ByteArray(32)), RelayCrypto.base64UrlEncode(ByteArray(32)))
+ val e = env(pairing(d).copy(relay = relay), wifi = false, cellular = true, relay = { DiagResult.Ok("The relay answers") })
+ val r = results(e)
+ assertTrue(r[DiagStep.NETWORK] is DiagResult.Ok)
+ assertEquals(DiagResult.Ok("The relay answers"), r[DiagStep.RELAY])
+ }
+
+ @Test fun aClosedPortIsAnAddressProblemAndStopsTheSecureSteps() {
+ val closed = ServerSocket(0).use { it.localPort }
+ val p = PairingPayload("127.0.0.1", closed, "ab".repeat(32), token, "PC")
+ val r = results(env(p))
+ val a = r[DiagStep.ADDRESS] as DiagResult.Problem
+ assertTrue(a.problem.contains("127.0.x.x"))
+ assertTrue(r[DiagStep.SECURE] is DiagResult.Skipped)
+ assertTrue(r[DiagStep.TOKEN] is DiagResult.Skipped)
+ }
+
+ @Test fun anotherCertificateIsNamedAsSuchAndTheTokenIsNeverSent() {
+ val d = FakeDesktop(tls = true).track()
+ val r = results(env(pairing(d, fp = "00".repeat(32))))
+ val s = r[DiagStep.SECURE] as DiagResult.Problem
+ assertTrue(s.problem.contains("not the computer you paired with"))
+ assertTrue(r[DiagStep.TOKEN] is DiagResult.Skipped)
+ assertTrue("no hello reached the computer", d.received.none { it.contains("hello") })
+ }
+
+ @Test fun aWrongPairingCodeIsToldApartFromEverythingElse() {
+ val d = FakeDesktop(tls = true).track()
+ val r = results(env(pairing(d, tok = "W".repeat(20))))
+ assertTrue(r[DiagStep.SECURE] is DiagResult.Ok)
+ val t = r[DiagStep.TOKEN] as DiagResult.Problem
+ assertTrue(t.problem.contains("pairing code was refused"))
+ }
+
+ @Test fun aComputerThatSpeaksAnotherVersionIsToldApart() {
+ val d = FakeDesktop(tls = true).track()
+ d.welcomeVersion = 2
+ val t = results(env(pairing(d)))[DiagStep.TOKEN] as DiagResult.Problem
+ assertTrue(t.problem.contains("version 2"))
+ }
+
+ @Test fun discoveryTellsAMovedComputerFromAMissingOne() {
+ val d = FakeDesktop(tls = true).track()
+ val p = pairing(d)
+ val id = Discovery.fingerprintId(d.certSha256)
+ val moved = listOf(Found("PC", "192.168.7.7", 47821, id, Discovery.TXT_VERSION))
+ assertTrue((results(env(p, found = moved))[DiagStep.DISCOVERY] as DiagResult.Problem).problem.contains("192.168.x.x"))
+ assertTrue((results(env(p, found = emptyList()))[DiagStep.DISCOVERY] as DiagResult.Problem).problem.contains("not announcing"))
+ val lookalike = listOf(Found("PC", "192.168.7.7", 47821, "deadbeef", Discovery.TXT_VERSION))
+ assertTrue("another computer's announcement does not count", results(env(p, found = lookalike))[DiagStep.DISCOVERY] is DiagResult.Problem)
+ }
+
+ @Test fun aCheckThatThrowsBecomesAProblemNotACrash() {
+ val broken = object : DiagEnv {
+ override fun network() = DiagResult.Ok("ok")
+ override fun address(): DiagResult = error("boom")
+ override fun discovery() = DiagResult.Ok("ok")
+ override fun secure() = DiagResult.Ok("ok")
+ override fun token() = DiagResult.Ok("ok")
+ override fun relay(): DiagResult? = null
+ }
+ val r = Diagnostics.run(broken).toMap()
+ assertTrue((r[DiagStep.ADDRESS] as DiagResult.Problem).problem.contains("IllegalStateException"))
+ assertTrue(r[DiagStep.SECURE] is DiagResult.Skipped)
+ }
+
+ @Test fun theReportNeverContainsASecretTheNameOrTheFullAddress() {
+ val d = FakeDesktop(tls = true).track()
+ val p = pairing(d, host = "192.168.1.20")
+ val fakeAddress = Diagnostics.maskHost(p.host)
+ assertEquals("192.168.x.x", fakeAddress)
+ assertEquals("a name (hidden)", Diagnostics.maskHost("my-pc.local"))
+ val results = Diagnostics.run(env(p.copy(host = "127.0.0.1")).also { }, { _, _ -> })
+ val text = Diagnostics.report("0.1.0", "13", "SM-A127F", results, fakeAddress, "relay")
+ for (secret in listOf(token, p.certSha256, p.desktopName, "192.168.1.20", "127.0.0.1")) assertFalse("report mentions $secret", text.contains(secret))
+ assertTrue(text.startsWith("Coucou for Android 0.1.0 · Android 13 · SM-A127F"))
+ assertTrue(text.contains("Computer: 192.168.x.x · connected via: relay"))
+ assertTrue(text.lines().drop(2).all { it.startsWith("OK ") || it.startsWith("PROBLEM ") || it.startsWith("SKIPPED ") })
+ }
+
+ @Test fun theStepsRunInOrderAndEachIsReportedAsItFinishes() {
+ val d = FakeDesktop(tls = true).track()
+ val seen = mutableListOf<DiagStep>()
+ Diagnostics.run(env(pairing(d))) { step, _ -> seen += step }
+ assertEquals(listOf(DiagStep.NETWORK, DiagStep.ADDRESS, DiagStep.DISCOVERY, DiagStep.SECURE, DiagStep.TOKEN), seen)
+ }
+
+ @Test fun theSourceNeverPutsThePairingCodeInAResult() {
+ val src = java.io.File("src/main/kotlin/com/coucou/android/link/Diagnostics.kt").readText()
+ // The token is only ever read to build the hello; no result string interpolates it, and nothing logs.
+ assertEquals(1, Regex("""p\.token""").findAll(src).count())
+ assertFalse(src.contains("Log.") || src.contains("println"))
+ assertFalse(Regex("""DiagResult\.\w+\([^)]*\$\{?p\.(token|certSha256)""").containsMatchIn(src))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/DiscoveryTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/DiscoveryTest.kt
new file mode 100644
index 00000000..c1464aab
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/DiscoveryTest.kt
@@ -0,0 +1,286 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+private const val CERT = "ab12cd34ef56ab78901234567890abcdef1234567890abcdef1234567890abcd"
+private const val OTHER_CERT = "ab12cd34ef56ab78ffffffffffffffffffffffffffffffffffffffffffffffff" // same first 16: a lookalike
+private const val TOKEN = "secret_token_1234567"
+
+private fun paired(host: String = "192.168.10.6", port: Int = 47821) =
+ PairingPayload(host, port, CERT, TOKEN, "My PC")
+
+private fun found(host: String, id: String? = "ab12cd34ef56ab78", port: Int = 47821, name: String = "My PC", v: String? = "1") =
+ Found(name, host, port, id, v)
+
+class DiscoveryMatchingTest {
+ @Test fun theIdIsTheFirstSixteenHexOfTheCertificate() {
+ assertEquals("ab12cd34ef56ab78", Discovery.fingerprintId(CERT))
+ assertEquals("ab12cd34ef56ab78", Discovery.fingerprintId(CERT.uppercase()))
+ assertNull(Discovery.fingerprintId("not hex at all, long enough"))
+ assertNull(Discovery.fingerprintId("abcd"))
+ }
+
+ @Test fun onlyTheFingerprintIdDecidesWhoIsMyComputer() {
+ val p = paired()
+ assertTrue(Discovery.matches(found("10.154.121.113"), p))
+ assertTrue("the name does not matter", Discovery.matches(found("10.154.121.113", name = "Something else"), p))
+ assertFalse("another computer", Discovery.matches(found("10.154.121.113", id = "0000000000000000"), p))
+ assertFalse("no id announced", Discovery.matches(found("10.154.121.113", id = null), p))
+ assertFalse("same name, other id", Discovery.matches(found("10.154.121.113", id = "ffffffffffffffff", name = "My PC"), p))
+ }
+
+ @Test fun aVersionWeDoNotSpeakIsNotAMatch() {
+ assertTrue(Discovery.matches(found("10.0.0.5", v = null), paired()))
+ assertFalse(Discovery.matches(found("10.0.0.5", v = "2"), paired()))
+ }
+
+ @Test fun twoComputersThatMatchNoFingerprintGiveNoCandidate() {
+ val seen = listOf(found("192.168.1.5", id = "1111111111111111", name = "PC A"), found("192.168.1.6", id = "2222222222222222", name = "PC B"))
+ assertTrue(Discovery.candidates(seen, paired()).isEmpty())
+ }
+
+ @Test fun theSamePairedFingerprintTwiceKeepsBothInOrderWithoutDuplicates() {
+ val seen = listOf(found("192.168.1.5"), found("192.168.1.5"), found("10.0.0.9"))
+ assertEquals(listOf("192.168.1.5", "10.0.0.9"), Discovery.candidates(seen, paired()).map { it.host })
+ }
+
+ @Test fun onlyLocalAddressesAreEverTried() {
+ for (ok in listOf("192.168.0.2", "10.154.121.113", "172.16.5.5", "172.31.255.1", "169.254.3.4", "127.0.0.1", "100.64.1.1")) assertTrue(ok, Discovery.isLocalHost(ok))
+ for (bad in listOf("8.8.8.8", "172.32.0.1", "192.169.0.1", "100.128.0.1", "example.com", "1.2.3", "256.1.1.1", "", "fe80::1")) assertFalse(bad, Discovery.isLocalHost(bad))
+ assertTrue(Discovery.candidates(listOf(found("8.8.8.8")), paired()).isEmpty())
+ }
+
+ @Test fun anAddressChangeKeepsTheTokenAndThePinnedCertificate() {
+ val p = paired()
+ val q = Discovery.withAddress(p, "10.154.121.113", 47900)
+ assertEquals("10.154.121.113", q.host)
+ assertEquals(47900, q.port)
+ assertEquals(p.token, q.token)
+ assertEquals(p.certSha256, q.certSha256)
+ assertEquals(p.desktopName, q.desktopName)
+ }
+}
+
+class AddressParsingTest {
+ @Test fun anAddressWithOrWithoutAPort() {
+ assertEquals("192.168.1.20" to 47821, Discovery.parseAddress("192.168.1.20"))
+ assertEquals("192.168.1.20" to 5000, Discovery.parseAddress(" 192.168.1.20:5000 "))
+ assertEquals("my-pc.local" to 47821, Discovery.parseAddress("my-pc.local"))
+ assertEquals("my-pc.local" to 1, Discovery.parseAddress("my-pc.local:1"))
+ }
+
+ @Test fun thingsThatCannotBeAnAddressAreRefused() {
+ for (bad in listOf("", " ", "192.168.1", "256.1.1.1", "192.168.1.20:0", "192.168.1.20:70000", "192.168.1.20:", "host:abc", "a b", "http://x", "x/y", "user@host", "[::1]:47821", "::1", "-bad.local", "a..b", "host:1:2")) {
+ assertNull("'$bad'", Discovery.parseAddress(bad))
+ }
+ }
+}
+
+class DiscoveryPolicyTest {
+ @Test fun theSavedAddressGetsTwoSecondsAndOneFailureBeforeTheNetworkIsSearched() {
+ assertEquals(2_000, DiscoveryPolicy.SAVED_CONNECT_TIMEOUT_MS)
+ assertEquals(1, DiscoveryPolicy.FAILURES_BEFORE_DISCOVERY)
+ assertEquals(15_000L, DiscoveryPolicy.WINDOW_MS)
+ }
+
+ @Test fun backoffNeverSpeedsUpAndStopsAtFiveMinutes() {
+ val delays = (0..12).map { DiscoveryPolicy.delayBeforeRound(it) }
+ assertEquals(0L, delays[0])
+ assertEquals(delays.sorted(), delays)
+ assertEquals(300_000L, delays.last())
+ assertEquals(0L, DiscoveryPolicy.delayBeforeRound(-3))
+ }
+
+ @Test fun nothingIsSearchedWhenConnectedOrWithoutWifiOrWithoutAComputerOrInTheDemo() {
+ assertTrue(DiscoveryPolicy.mayDiscover(paired = true, demo = false, wifiUp = true, linkConnected = false))
+ assertFalse(DiscoveryPolicy.mayDiscover(paired = true, demo = false, wifiUp = true, linkConnected = true))
+ assertFalse(DiscoveryPolicy.mayDiscover(paired = true, demo = false, wifiUp = false, linkConnected = false))
+ assertFalse(DiscoveryPolicy.mayDiscover(paired = false, demo = false, wifiUp = true, linkConnected = false))
+ assertFalse(DiscoveryPolicy.mayDiscover(paired = true, demo = true, wifiUp = true, linkConnected = false))
+ }
+}
+
+/** A fake clock that runs scheduled tasks when time is moved, and a fake network source: no real network anywhere. */
+private class Fixture(var pairing: PairingPayload? = paired(), var allowed: Boolean = true) {
+ class Task(val at: Long, val task: () -> Unit) : Cancelable { var live = true; override fun cancel() { live = false } }
+ var now = 0L
+ val tasks = ArrayList<Task>()
+ val scheduler = Scheduler { d, t -> Task(now + d, t).also { tasks.add(it) } }
+ fun advance(ms: Long) {
+ val end = now + ms
+ while (true) {
+ val next = tasks.filter { it.live && it.at <= end }.minByOrNull { it.at } ?: break
+ now = next.at; next.live = false; next.task()
+ }
+ now = end
+ }
+
+ var onFound: ((Found) -> Unit)? = null
+ var started = 0
+ var stopped = 0
+ val source = object : DiscoverySource {
+ override fun start(onFound: (Found) -> Unit) { started++; [email protected] = onFound }
+ override fun stop() { stopped++; onFound = null }
+ }
+ val probed = ArrayList<Triple<String, Int, String>>()
+ val results = HashMap<String, ProbeResult>()
+ val probe = Probe { h, p, c -> probed.add(Triple(h, p, c)); results[h] ?: ProbeResult.UNREACHABLE }
+ val addresses = ArrayList<Pair<String, Int>>()
+ val states = ArrayList<DiscoveryState>()
+ val finder = AddressFinder(source, probe, { pairing }, { allowed }, { h, p -> addresses.add(h to p) }, { states.add(it) }, scheduler) { it() }
+ fun see(f: Found) = onFound?.invoke(f)
+}
+
+class AddressFinderTest {
+ @Test fun theMatchingComputerThatPassesThePinIsHandedBackAndTheSearchStops() {
+ val f = Fixture()
+ f.results["10.154.121.113"] = ProbeResult.MATCH
+ f.finder.request()
+ assertEquals(DiscoveryState.LOOKING, f.finder.current)
+ f.see(found("10.154.121.113"))
+ assertEquals(listOf("10.154.121.113" to 47821), f.addresses)
+ assertEquals(DiscoveryState.IDLE, f.finder.current)
+ assertEquals(1, f.stopped)
+ }
+
+ @Test fun aLookalikeWithTheSameIdButAnotherCertificateIsDroppedAndNeverSaved() {
+ val f = Fixture()
+ f.results["192.168.1.99"] = ProbeResult.PIN_MISMATCH // same id announced, different certificate
+ f.finder.request()
+ f.see(found("192.168.1.99"))
+ f.see(found("192.168.1.99")) // announced again: not tried again
+ assertTrue("nothing is saved", f.addresses.isEmpty())
+ assertEquals("tried once only", 1, f.probed.size)
+ assertEquals(DiscoveryState.LOOKING, f.finder.current)
+ }
+
+ @Test fun theCheckIsGivenTheFullPinnedCertificateAndNoTokenCanBeInIt() {
+ val f = Fixture()
+ f.results["10.0.0.7"] = ProbeResult.MATCH
+ f.finder.request()
+ f.see(found("10.0.0.7"))
+ val (host, port, cert) = f.probed.single()
+ assertEquals("10.0.0.7", host); assertEquals(47821, port); assertEquals(CERT, cert)
+ // by construction: the probe's parameters are host, port and the certificate, never the token
+ assertFalse(listOf(host, port.toString(), cert).any { TOKEN in it })
+ }
+
+ @Test fun whenTheSameFingerprintAppearsTwiceTheFirstOneThatPassesWins() {
+ val f = Fixture()
+ f.results["192.168.1.5"] = ProbeResult.PIN_MISMATCH
+ f.results["192.168.1.6"] = ProbeResult.MATCH
+ f.results["192.168.1.7"] = ProbeResult.MATCH
+ f.finder.request()
+ f.see(found("192.168.1.5")); f.see(found("192.168.1.6")); f.see(found("192.168.1.7"))
+ assertEquals(listOf("192.168.1.6" to 47821), f.addresses)
+ }
+
+ @Test fun aComputerThatMatchesNoFingerprintIsNeverProbed() {
+ val f = Fixture()
+ f.finder.request()
+ f.see(found("192.168.1.5", id = "1111111111111111"))
+ f.see(found("192.168.1.6", id = null))
+ assertTrue(f.probed.isEmpty() && f.addresses.isEmpty())
+ }
+
+ @Test fun anUnreachableAnnouncementMayBeTriedAgainWhenItIsAnnouncedAgain() {
+ val f = Fixture()
+ f.finder.request()
+ f.see(found("192.168.1.5"))
+ f.results["192.168.1.5"] = ProbeResult.MATCH
+ f.see(found("192.168.1.5"))
+ assertEquals(2, f.probed.size)
+ assertEquals(1, f.addresses.size)
+ }
+
+ @Test fun nothingFoundInFifteenSecondsIsNotFoundAndTheNextSearchWaits() {
+ val f = Fixture()
+ f.finder.request()
+ f.advance(14_999)
+ assertEquals(DiscoveryState.LOOKING, f.finder.current)
+ f.advance(1)
+ assertEquals(DiscoveryState.NOT_FOUND, f.finder.current)
+ assertEquals(1, f.started)
+ assertEquals("the source is stopped between searches", 1, f.stopped)
+ f.advance(19_999)
+ assertEquals("still waiting (20 s)", 1, f.started)
+ f.advance(1)
+ assertEquals(2, f.started)
+ assertEquals(DiscoveryState.LOOKING, f.finder.current)
+ }
+
+ @Test fun theWaitsBetweenSearchesGrowAndNothingScansAroundTheClock() {
+ val f = Fixture()
+ f.finder.request()
+ var searches = 0
+ var lastStart = f.started
+ val starts = ArrayList<Long>()
+ repeat(40) {
+ f.advance(10_000)
+ if (f.started != lastStart) { starts.add(f.now); lastStart = f.started; searches++ }
+ }
+ // 400 s of simulated time: well under one search per 15 s window
+ assertTrue("searches in 400 s: $searches", searches <= 6)
+ val gaps = starts.zipWithNext { a, b -> b - a }
+ assertEquals(gaps.sorted(), gaps)
+ }
+
+ @Test fun aNetworkChangeSearchesAtOnceAndResetsTheWaiting() {
+ val f = Fixture()
+ f.finder.request(); f.advance(15_000) // not found, waiting 20 s
+ assertEquals(DiscoveryState.NOT_FOUND, f.finder.current)
+ f.finder.networkChanged()
+ assertEquals(DiscoveryState.LOOKING, f.finder.current)
+ assertEquals(2, f.started)
+ }
+
+ @Test fun requestingWhileSearchingOrWaitingDoesNotStartASecondSearch() {
+ val f = Fixture()
+ f.finder.request(); f.finder.request()
+ assertEquals(1, f.started)
+ f.advance(15_000)
+ f.finder.request() // waiting for the next one
+ assertEquals(1, f.started)
+ }
+
+ @Test fun whenTheLinkIsUpEverythingStopsAndNothingIsScheduled() {
+ val f = Fixture()
+ f.finder.request(); f.advance(15_000)
+ f.finder.connected()
+ assertEquals(DiscoveryState.IDLE, f.finder.current)
+ f.advance(600_000)
+ assertEquals("no search ever started again", 1, f.started)
+ }
+
+ @Test fun noPairingOrNotAllowedMeansNoSearch() {
+ val none = Fixture(pairing = null)
+ none.finder.request()
+ assertEquals(0, none.started)
+ val off = Fixture(allowed = false)
+ off.finder.request()
+ assertEquals(0, off.started)
+ assertEquals(DiscoveryState.IDLE, off.finder.current)
+ }
+
+ @Test fun aResultThatArrivesAfterTheSearchEndedIsIgnored() {
+ val f = Fixture()
+ f.finder.request()
+ val late = f.onFound!!
+ f.advance(15_000)
+ f.results["10.0.0.7"] = ProbeResult.MATCH
+ late(found("10.0.0.7"))
+ assertTrue(f.addresses.isEmpty())
+ }
+
+ @Test fun theUserSeesLookingThenFoundAsStates() {
+ val f = Fixture()
+ f.results["10.0.0.7"] = ProbeResult.MATCH
+ f.finder.request()
+ f.see(found("10.0.0.7"))
+ assertEquals(listOf(DiscoveryState.LOOKING, DiscoveryState.IDLE), f.states)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/LinkAnswersTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/LinkAnswersTest.kt
new file mode 100644
index 00000000..a3fdf7cd
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/LinkAnswersTest.kt
@@ -0,0 +1,99 @@
+package com.coucou.android.link
+
+import java.io.BufferedReader
+import java.io.InputStreamReader
+import java.net.ServerSocket
+import java.net.Socket
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The client against a plain-socket pretend computer: a question is surfaced and answered only when `answers` was offered. */
+class LinkAnswersTest {
+ private val fp = "cd".repeat(32)
+ private val server = ServerSocket(0)
+ private val received = LinkedBlockingQueue<String>()
+ private var welcomeCaps = """["answers"]"""
+ private var sendQuestion = true
+ private val pairing get() = PairingPayload("127.0.0.1", server.localPort, "ab".repeat(32), "T".repeat(20), "PC")
+
+ private val questions = CopyOnWriteArrayList<QuestionRequest>()
+ private val welcome = CountDownLatch(1)
+ private val question = CountDownLatch(1)
+ private val listener = object : LinkListener {
+ override fun onWelcome(desktopName: String, os: String) { welcome.countDown() }
+ override fun onQuestion(request: QuestionRequest) { questions.add(request); question.countDown() }
+ }
+
+ init {
+ Thread {
+ try {
+ val s: Socket = server.accept()
+ val r = BufferedReader(InputStreamReader(s.getInputStream()))
+ val out = s.getOutputStream()
+ fun send(line: String) { out.write((line + "\n").toByteArray()); out.flush() }
+ while (true) {
+ val line = r.readLine() ?: break
+ received.add(line)
+ if (line.contains("\"type\":\"hello\"")) {
+ send("""{"type":"welcome","v":1,"desktop":"PC","os":"windows","caps":$welcomeCaps}""")
+ if (sendQuestion) {
+ send("""{"type":"question","pillId":"integration_claude","fingerprint":"$fp","createdAt":1,"questions":[{"question":"Which?","multiSelect":false,"options":[{"label":"A","description":""},{"label":"B","description":""}]}]}""")
+ }
+ }
+ }
+ } catch (_: Exception) { }
+ }.apply { isDaemon = true; start() }
+ }
+
+ private var client: LinkClient? = null
+
+ @After fun stop() { client?.stop(); runCatching { server.close() } }
+
+ private fun start(caps: List<String> = Protocol.CAPABILITIES): LinkClient {
+ val c = LinkClient(pairing, "test", listener, connector = { Socket("127.0.0.1", server.localPort) }, backoffMs = longArrayOf(50), caps = caps)
+ client = c
+ c.start()
+ assertTrue(welcome.await(5, TimeUnit.SECONDS))
+ return c
+ }
+
+ @Test fun aQuestionIsSurfacedAndAnAnswerIsSentWhenAnswersWasOffered() {
+ val c = start()
+ assertTrue(question.await(5, TimeUnit.SECONDS))
+ assertEquals("Which?", questions[0].questions[0].question)
+ assertTrue(c.answer(fp, listOf(listOf("B"))))
+ var sent: String? = null
+ repeat(20) { if (sent == null) sent = received.poll(250, TimeUnit.MILLISECONDS)?.takeIf { it.contains("\"type\":\"answer\"") } }
+ val o = org.json.JSONObject(sent!!)
+ assertEquals("answer", o.getString("type"))
+ assertEquals(fp, o.getString("fingerprint"))
+ assertEquals("""[["B"]]""", o.getJSONArray("picks").toString())
+ }
+
+ @Test fun withoutTheOfferTheQuestionIsIgnoredAndNothingCanBeSent() {
+ welcomeCaps = "[]"
+ val c = start()
+ assertFalse("a computer that did not offer answers: its question is not surfaced", question.await(700, TimeUnit.MILLISECONDS))
+ assertFalse(c.answer(fp, listOf(listOf("A"))))
+ assertTrue(received.none { it.contains("\"type\":\"answer\"") })
+ }
+
+ @Test fun anAppThatDidNotAskNeverSendsAnAnswer() {
+ val c = start(caps = listOf("chat"))
+ assertFalse(question.await(700, TimeUnit.MILLISECONDS))
+ assertFalse(c.answer(fp, listOf(listOf("A"))))
+ }
+
+ @Test fun theHelloAsksForAnswers() {
+ start()
+ val hello = received.poll(2, TimeUnit.SECONDS)!!
+ assertTrue(hello, hello.contains("\"answers\""))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/LinkClientTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/LinkClientTest.kt
new file mode 100644
index 00000000..8c7c341e
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/LinkClientTest.kt
@@ -0,0 +1,451 @@
+package com.coucou.android.link
+
+import java.io.BufferedReader
+import java.io.InputStreamReader
+import java.net.ServerSocket
+import java.net.Socket
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import javax.net.ssl.KeyManagerFactory
+import javax.net.ssl.SSLContext
+import javax.net.ssl.SSLServerSocket
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** A pretend desktop: real TLS with the test certificate, speaking the v1 protocol. */
+internal class FakeDesktop(tls: Boolean) : AutoCloseable {
+ val server: ServerSocket
+ val certSha256: String
+ val received = LinkedBlockingQueue<String>()
+ @Volatile var peer: Socket? = null
+ val peerClosed = CountDownLatch(1)
+ @Volatile var welcomeVersion = Protocol.VERSION
+ @Volatile var expectedToken = "T".repeat(20)
+ /** False: the desktop reads everything and answers nothing, like a connection that died quietly. */
+ @Volatile var answerPings = true
+ /** Extra JSON in the welcome, such as `,"caps":["chat"]`. */
+ @Volatile var welcomeExtra = ""
+ private val fp = "f".repeat(64)
+
+ init {
+ val ks = KeyStore.getInstance("PKCS12")
+ javaClass.getResourceAsStream("/test-desktop.p12").use { ks.load(it, "changeit".toCharArray()) }
+ certSha256 = MessageDigest.getInstance("SHA-256")
+ .digest(ks.getCertificate("desktop").encoded).joinToString("") { "%02x".format(it) }
+ server = if (tls) {
+ val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(ks, "changeit".toCharArray()) }
+ val ctx = SSLContext.getInstance("TLS").apply { init(kmf.keyManagers, null, null) }
+ (ctx.serverSocketFactory.createServerSocket(0) as SSLServerSocket)
+ } else ServerSocket(0)
+ Thread {
+ try {
+ while (true) serve(server.accept())
+ } catch (_: Exception) { }
+ }.apply { isDaemon = true; start() }
+ }
+
+ val port get() = server.localPort
+
+ private fun serve(s: Socket) {
+ peer = s
+ Thread {
+ try {
+ val r = BufferedReader(InputStreamReader(s.getInputStream()))
+ val out = s.getOutputStream()
+ fun send(line: String) { out.write((line + "\n").toByteArray()); out.flush() }
+ while (true) {
+ val line = r.readLine() ?: break
+ received.add(line)
+ if (line.contains("\"type\":\"hello\"")) {
+ if (!line.contains("\"token\":\"$expectedToken\"")) { send("""{"type":"error","code":"auth","message":"bad token"}"""); break }
+ send("""{"type":"welcome","v":$welcomeVersion,"desktop":"Test PC","os":"windows"$welcomeExtra}""")
+ send("""{"type":"sessions","sessions":[{"pillId":"agent_codex","state":"working"}]}""")
+ }
+ if (answerPings && line.contains("\"type\":\"ping\"")) send("""{"type":"pong"}""")
+ }
+ } catch (_: Exception) { } finally { runCatching { s.close() }; peerClosed.countDown() }
+ }.apply { isDaemon = true; start() }
+ }
+
+ fun push(line: String) { peer!!.getOutputStream().apply { write((line + "\n").toByteArray()); flush() } }
+ fun approvalJson(created: Long) =
+ """{"type":"approval","pillId":"agent_codex","fingerprint":"$fp","tool":"Bash","command":"ls","createdAt":$created}"""
+ val approvalFingerprint get() = fp
+ fun dropConnection() { peer?.close() }
+ override fun close() { runCatching { peer?.close() }; runCatching { server.close() } }
+}
+
+private class Recorder : LinkListener {
+ val states = CopyOnWriteArrayList<LinkState>()
+ val sessions = LinkedBlockingQueue<List<SessionInfo>>()
+ val approvals = LinkedBlockingQueue<ApprovalRequest>()
+ val resolved = LinkedBlockingQueue<String>()
+ val errors = LinkedBlockingQueue<String>()
+ val lost = LinkedBlockingQueue<LostReason>()
+ val connected = CountDownLatch(1)
+ @Volatile var desktop: String? = null
+ override fun onState(state: LinkState) { states.add(state) }
+ override fun onWelcome(desktopName: String, os: String) { desktop = desktopName; connected.countDown() }
+ override fun onSessions(sessions: List<SessionInfo>) { this.sessions.add(sessions) }
+ override fun onApproval(request: ApprovalRequest) { approvals.add(request) }
+ override fun onApprovalResolved(fingerprint: String) { resolved.add(fingerprint) }
+ override fun onError(code: String, message: String) { errors.add(code) }
+ override fun onLinkLost(reason: LostReason) { lost.add(reason) }
+ val caps = LinkedBlockingQueue<Set<String>>()
+ val chatEvents = LinkedBlockingQueue<String>()
+ override fun onCaps(caps: Set<String>) { this.caps.add(caps) }
+ override fun onChatModels(models: List<ChatModel>) { chatEvents.add("models:" + models.joinToString(",") { it.id }) }
+ override fun onChatDelta(id: String, text: String) { chatEvents.add("delta:$id:$text") }
+ override fun onChatDone(id: String, text: String?) { chatEvents.add("done:$id:${text ?: "-"}") }
+ override fun onChatError(id: String, reason: String, message: String) { chatEvents.add("error:$id:$reason") }
+}
+
+class LinkClientTest {
+ private val closeables = mutableListOf<AutoCloseable>()
+ private var now = System.currentTimeMillis()
+ private val token = "T".repeat(20)
+
+ @After fun cleanup() = closeables.forEach { runCatching { it.close() } }
+
+ private fun <T : AutoCloseable> T.track(): T { closeables.add(this); return this }
+
+ private fun payload(d: FakeDesktop, fp: String = d.certSha256) = PairingPayload("127.0.0.1", d.port, fp, token, "Test PC")
+
+ private fun client(d: FakeDesktop, rec: Recorder, p: PairingPayload = payload(d), plain: Boolean = false, backoff: LongArray = longArrayOf(50), readTimeoutMs: Int = 2_000): LinkClient {
+ val connector = if (plain) Connector { ms -> Socket().apply { connect(java.net.InetSocketAddress(p.host, p.port), ms) } } else PinnedTls.connector(p)
+ return LinkClient(p, "Pixel", rec, connector, clockMs = { now }, readTimeoutMs = readTimeoutMs, pingEveryMs = 100, backoffMs = backoff, pongWaitMs = 300)
+ .also { closeables.add(AutoCloseable { it.stop() }) }
+ }
+
+ @Test fun connectsOverPinnedTlsAndReceivesSessions() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue("never connected", rec.connected.await(5, TimeUnit.SECONDS))
+ assertEquals("Test PC", rec.desktop)
+ val s = rec.sessions.poll(5, TimeUnit.SECONDS)
+ assertEquals("agent_codex", s!![0].pillId)
+ assertTrue(rec.states.contains(LinkState.CONNECTED))
+ assertTrue(d.received.poll(2, TimeUnit.SECONDS)!!.contains("\"device\":\"Pixel\""))
+ }
+
+ @Test fun refusesADesktopWithAnotherCertificate() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec, payload(d, fp = "00".repeat(32))).start()
+ assertFalse("connected to an unpinned desktop", rec.connected.await(1500, TimeUnit.MILLISECONDS))
+ assertNull(d.received.poll(200, TimeUnit.MILLISECONDS))
+ assertFalse(rec.states.contains(LinkState.CONNECTED))
+ }
+
+ @Test fun neverSendsTheTokenInTheClear() {
+ // A plain-text server must not be able to complete the pinned-TLS connector's handshake.
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ client(d, rec, payload(d)).start()
+ assertFalse(rec.connected.await(1500, TimeUnit.MILLISECONDS))
+ assertTrue("token leaked: ${d.received.toList()}", d.received.none { it.contains("token") })
+ }
+
+ @Test fun approvalCanBeAllowedOnceAndTheDesktopReceivesIt() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.push(d.approvalJson(now))
+ val req = rec.approvals.poll(5, TimeUnit.SECONDS)
+ assertNotNull(req)
+ assertTrue(c.decide(req!!.fingerprint, allow = true))
+ assertFalse("second decision for the same request", c.decide(req.fingerprint, allow = false))
+ val decision = generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.first { it.contains("decision") }
+ assertTrue(decision.contains("\"decision\":\"allow\"") && decision.contains(req.fingerprint))
+ }
+
+ @Test fun cannotDecideAnUnknownRequest() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ assertFalse(c.decide("e".repeat(64), allow = true))
+ }
+
+ @Test fun expiredApprovalIsRefused() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.push(d.approvalJson(now))
+ val req = rec.approvals.poll(5, TimeUnit.SECONDS)!!
+ now += Protocol.APPROVAL_TTL_MS
+ assertFalse(c.decide(req.fingerprint, allow = true))
+ assertTrue("no decision must reach the desktop", d.received.none { it.contains("\"type\":\"decision\"") })
+ }
+
+ @Test fun desktopResolvingTheApprovalRemovesIt() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.push(d.approvalJson(now))
+ val req = rec.approvals.poll(5, TimeUnit.SECONDS)!!
+ d.push("""{"type":"approvalResolved","fingerprint":"${req.fingerprint}"}""")
+ assertEquals(req.fingerprint, rec.resolved.poll(5, TimeUnit.SECONDS))
+ assertFalse(c.decide(req.fingerprint, allow = true))
+ }
+
+ @Test fun reconnectsAfterTheLinkDrops() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ rec.sessions.poll(5, TimeUnit.SECONDS)
+ d.dropConnection()
+ val again = rec.sessions.poll(8, TimeUnit.SECONDS)
+ assertNotNull("did not reconnect", again)
+ assertTrue(rec.states.count { it == LinkState.CONNECTED } >= 2)
+ }
+
+ @Test fun wrongTokenGetsAnAuthErrorAndTheClientStopsRetrying() {
+ val d = FakeDesktop(tls = true).track().also { it.expectedToken = "other-token-123456789" }
+ val rec = Recorder()
+ client(d, rec).start()
+ assertEquals("auth", rec.errors.poll(5, TimeUnit.SECONDS))
+ assertFalse(rec.connected.await(300, TimeUnit.MILLISECONDS))
+ Thread.sleep(600) // the backoff is 50 ms here: a retrying client would have said hello again by now
+ assertEquals(1, d.received.count { it.contains("\"type\":\"hello\"") })
+ assertEquals(LinkState.DISCONNECTED, rec.states.last())
+ }
+
+ @Test fun versionMismatchIsReportedAndNotRetried() {
+ val d = FakeDesktop(tls = true).track().also { it.welcomeVersion = 99 }
+ val rec = Recorder()
+ client(d, rec).start()
+ assertEquals("version", rec.errors.poll(5, TimeUnit.SECONDS))
+ assertFalse(rec.states.contains(LinkState.CONNECTED))
+ Thread.sleep(600)
+ assertEquals(1, d.received.count { it.contains("\"type\":\"hello\"") })
+ }
+
+ @Test fun sendsKeepAlivePings() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ val ping = generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.take(10).any { it.contains("\"type\":\"ping\"") }
+ assertTrue(ping)
+ }
+
+ @Test fun decisionsAndStopNeverTouchTheNetworkOnTheCallersThread() {
+ // Android throws NetworkOnMainThreadException if the UI thread writes to a socket.
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ val writers = CopyOnWriteArrayList<Pair<String, Thread>>()
+ val p = payload(d)
+ val connector = Connector { ms ->
+ object : Socket() {
+ override fun getOutputStream(): java.io.OutputStream {
+ val real = super.getOutputStream()
+ return object : java.io.OutputStream() {
+ override fun write(b: Int) = real.write(b)
+ override fun write(b: ByteArray, off: Int, len: Int) {
+ writers.add(String(b, off, len) to Thread.currentThread())
+ real.write(b, off, len)
+ }
+ override fun flush() = real.flush()
+ }
+ }
+ }.apply { connect(java.net.InetSocketAddress(p.host, p.port), ms) }
+ }
+ val c = LinkClient(p, "Pixel", rec, connector, clockMs = { now }, readTimeoutMs = 2_000, pingEveryMs = 60_000)
+ closeables.add(AutoCloseable { c.stop() })
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.push(d.approvalJson(now))
+ val req = rec.approvals.poll(5, TimeUnit.SECONDS)!!
+ val caller = Thread.currentThread()
+ assertTrue(c.decide(req.fingerprint, allow = false))
+ c.stop()
+ assertTrue(generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.take(6).any { it.contains("\"decision\":\"deny\"") })
+ assertTrue("nothing was written", writers.isNotEmpty())
+ assertTrue("a write happened on the caller's thread", writers.none { it.second === caller && it.first.contains("decision") })
+ }
+
+ @Test fun stopEndsTheLinkAndStaysStopped() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ c.stop() // "bye" is best effort; the desktop must at least see the connection end
+ assertTrue("desktop never saw the link close", d.peerClosed.await(5, TimeUnit.SECONDS))
+ assertFalse(c.decide("a".repeat(64), true))
+ val deadline = System.currentTimeMillis() + 3000
+ while (rec.states.lastOrNull() != LinkState.DISCONNECTED && System.currentTimeMillis() < deadline) Thread.sleep(20)
+ assertEquals(LinkState.DISCONNECTED, rec.states.last())
+ }
+
+ // ── chat ────────────────────────────────────────────────────────────────
+
+ @Test fun theHelloAsksForChatUnlessTheAppAsksForNothing() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ assertTrue(d.received.poll(2, TimeUnit.SECONDS)!!.contains("\"caps\":[\"chat\",\"details\",\"answers\",\"prefs\",\"diffs\",\"usage\",\"services\",\"relay\"]"))
+
+ val old = FakeDesktop(tls = true).track()
+ val rec2 = Recorder()
+ val p = payload(old)
+ LinkClient(p, "Pixel", rec2, PinnedTls.connector(p), caps = emptyList(), readTimeoutMs = 2_000)
+ .also { closeables.add(AutoCloseable { it.stop() }) }.start()
+ assertTrue(rec2.connected.await(5, TimeUnit.SECONDS))
+ val hello = old.received.poll(2, TimeUnit.SECONDS)!!
+ assertFalse("an app with no optional features sends the plain v1 hello: $hello", hello.contains("caps"))
+ }
+
+ @Test fun aWelcomeWithoutCapsOffersNoChatAndTheModelsAreNotAsked() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ assertEquals(emptySet<String>(), rec.caps.poll(5, TimeUnit.SECONDS))
+ Thread.sleep(300)
+ assertTrue(d.received.none { it.contains("chatModels") })
+ }
+
+ @Test fun whenChatIsOfferedTheModelsAreAskedForAtOnce() {
+ val d = FakeDesktop(tls = true).track().also { it.welcomeExtra = ""","caps":["chat"]""" }
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ assertEquals(setOf("chat"), rec.caps.poll(5, TimeUnit.SECONDS))
+ val asked = generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.take(6).firstOrNull { it.contains("chatModels") }
+ assertNotNull("the models were never asked for", asked)
+ }
+
+ @Test fun chatMessagesReachTheListener() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ client(d, rec).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.push("""{"type":"chatModels","models":[{"id":"openai/gpt","provider":"openai","label":"GPT"}]}""")
+ d.push("""{"type":"chatDelta","id":"c1","text":"Hel"}""")
+ d.push("""{"type":"chatDelta","id":"c1","text":"lo"}""")
+ d.push("""{"type":"chatDone","id":"c1"}""")
+ d.push("""{"type":"chatError","id":"c2","reason":"rate","message":"x"}""")
+ d.push("""{"type":"chatDelta","id":"bad id","text":"ignored"}""")
+ d.push("""{"type":"ping"}""") // an unknown type in the middle changes nothing
+ val got = (1..5).map { rec.chatEvents.poll(5, TimeUnit.SECONDS) }
+ assertEquals(listOf("models:openai/gpt", "delta:c1:Hel", "delta:c1:lo", "done:c1:-", "error:c2:rate"), got)
+ assertNull(rec.chatEvents.poll(300, TimeUnit.MILLISECONDS))
+ }
+
+ @Test fun chatSendIsWrittenOffTheCallersThreadAndOnlyWhileConnected() {
+ val d = FakeDesktop(tls = true).track()
+ val rec = Recorder()
+ val c = client(d, rec)
+ assertFalse("not connected yet", c.chatSend("c0", "openai/gpt", "early"))
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ assertTrue(c.chatSend("c1", "openai/gpt", "hello \"there\""))
+ c.chatCancel("c1")
+ c.chatReset()
+ c.chatModels()
+ val lines = generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.take(12).toList()
+ val chat = lines.filter { it.contains("\"type\":\"chat") }
+ assertEquals(
+ listOf("chatSend", "chatCancel", "chatReset", "chatModels"),
+ chat.map { org.json.JSONObject(it).getString("type") },
+ )
+ assertEquals("hello \"there\"", org.json.JSONObject(chat[0]).getString("text"))
+ assertTrue(chat.none { it.contains("early") })
+ }
+
+ @Test fun theDemoOffersNoChat() {
+ val demo = DemoLink(object : LinkListener {}, autoRun = false)
+ assertFalse(demo.chatSend("c1", "a/b", "hi"))
+ }
+
+ // ── Keeping the link alive while the phone sleeps ──
+
+ @Test fun aLivenessCheckDropsAConnectionThatStoppedAnsweringAndReconnects() {
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ // A read timeout of 30 s: only the liveness check can notice the silence within this test.
+ client(d, rec, plain = true, backoff = longArrayOf(30), readTimeoutMs = 30_000).also { it.start() }.let { c ->
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.answerPings = false
+ // A pong already on its way would count as "heard from it since the question": let the in-flight ones land first.
+ Thread.sleep(500)
+ now += 10_000 // the test's clock only moves when told to
+ c.checkNow()
+ assertEquals(LostReason.SILENT, rec.lost.poll(10, TimeUnit.SECONDS))
+ d.answerPings = true
+ // And it came back by itself with a new hello.
+ val hellos = generateSequence { d.received.poll(3, TimeUnit.SECONDS) }.take(40).count { it.contains("\"type\":\"hello\"") }
+ assertTrue("a second hello after the drop", hellos >= 2)
+ }
+ }
+
+ @Test fun aLivenessCheckLeavesAHealthyConnectionAlone() {
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ val c = client(d, rec, plain = true)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ repeat(3) { now += 10_000; c.checkNow(); Thread.sleep(150) }
+ Thread.sleep(600)
+ assertNull("no loss", rec.lost.poll())
+ assertEquals(LinkState.CONNECTED, rec.states.last())
+ }
+
+ @Test fun aLivenessCheckWhileDisconnectedReconnectsAtOnceInsteadOfWaitingOutTheBackoff() {
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ val c = client(d, rec, plain = true, backoff = longArrayOf(60_000))
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.dropConnection()
+ assertEquals(LostReason.CLOSED, rec.lost.poll(3, TimeUnit.SECONDS))
+ Thread.sleep(200) // now it waits 60 s
+ val before = d.received.count { it.contains("\"type\":\"hello\"") }
+ c.checkNow()
+ val deadline = System.currentTimeMillis() + 3_000
+ var after = before
+ while (after <= before && System.currentTimeMillis() < deadline) { Thread.sleep(50); after = d.received.count { it.contains("\"type\":\"hello\"") } }
+ assertTrue("reconnected without waiting", after > before)
+ }
+
+ @Test fun aSilentConnectionIsReportedAsSilentAndAClosedOneAsClosed() {
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ client(d, rec, plain = true, backoff = longArrayOf(30)).start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ d.answerPings = false // the 2 s read timeout is what notices this one
+ assertEquals(LostReason.SILENT, rec.lost.poll(5, TimeUnit.SECONDS))
+ }
+
+ @Test fun nothingIsReportedWhenTheUserStopsTheLink() {
+ val d = FakeDesktop(tls = false).track()
+ val rec = Recorder()
+ val c = client(d, rec, plain = true)
+ c.start()
+ assertTrue(rec.connected.await(5, TimeUnit.SECONDS))
+ c.stop()
+ Thread.sleep(400)
+ assertNull(rec.lost.poll())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/LinkDiffsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/LinkDiffsTest.kt
new file mode 100644
index 00000000..62c96557
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/LinkDiffsTest.kt
@@ -0,0 +1,99 @@
+package com.coucou.android.link
+
+import java.io.BufferedReader
+import java.io.InputStreamReader
+import java.net.ServerSocket
+import java.net.Socket
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The client against a plain-socket pretend computer: a diff is asked for and delivered only when `diffs` was offered. */
+class LinkDiffsTest {
+ private val server = ServerSocket(0)
+ private val received = LinkedBlockingQueue<String>()
+ private var welcomeCaps = """["diffs"]"""
+ private val pairing get() = PairingPayload("127.0.0.1", server.localPort, "ab".repeat(32), "T".repeat(20), "PC")
+
+ private val parts = CopyOnWriteArrayList<ServerMsg.Diff>()
+ private val welcome = CountDownLatch(1)
+ private val gotPart = CountDownLatch(1)
+ private val capsKnown = CountDownLatch(1)
+ private val listener = object : LinkListener {
+ override fun onWelcome(desktopName: String, os: String) { welcome.countDown() }
+ override fun onCaps(caps: Set<String>) { capsKnown.countDown() }
+ override fun onDiff(part: ServerMsg.Diff) { parts.add(part); gotPart.countDown() }
+ }
+
+ init {
+ Thread {
+ try {
+ val s: Socket = server.accept()
+ val r = BufferedReader(InputStreamReader(s.getInputStream()))
+ val out = s.getOutputStream()
+ fun send(line: String) { out.write((line + "\n").toByteArray()); out.flush() }
+ while (true) {
+ val line = r.readLine() ?: break
+ received.add(line)
+ if (line.contains("\"type\":\"hello\"")) {
+ send("""{"type":"welcome","v":1,"desktop":"PC","os":"windows","caps":$welcomeCaps}""")
+ // sent whether or not it was asked for: a client must not surface what it did not ask for
+ send("""{"type":"diff","pillId":"integration_claude","fileId":7,"name":"app.ts","part":0,"parts":1,"lines":[["+","x"]]}""")
+ }
+ }
+ } catch (_: Exception) { }
+ }.apply { isDaemon = true; start() }
+ }
+
+ private var client: LinkClient? = null
+
+ @After fun stop() { client?.stop(); runCatching { server.close() } }
+
+ private fun start(caps: List<String> = Protocol.CAPABILITIES): LinkClient {
+ val c = LinkClient(pairing, "test", listener, connector = { Socket("127.0.0.1", server.localPort) }, backoffMs = longArrayOf(50), caps = caps)
+ client = c
+ c.start()
+ assertTrue(welcome.await(5, TimeUnit.SECONDS))
+ // The welcome is told before the offered capabilities are stored: wait for them too.
+ assertTrue(capsKnown.await(5, TimeUnit.SECONDS))
+ return c
+ }
+
+ @Test fun aDiffIsAskedForByFileAndDelivered() {
+ val c = start()
+ assertTrue(c.getDiff("integration_claude", 7))
+ var sent: String? = null
+ repeat(20) { if (sent == null) sent = received.poll(250, TimeUnit.MILLISECONDS)?.takeIf { it.contains("\"type\":\"getDiff\"") } }
+ val o = org.json.JSONObject(sent!!)
+ assertEquals("integration_claude", o.getString("pillId"))
+ assertEquals(7L, o.getLong("fileId"))
+ assertTrue(gotPart.await(5, TimeUnit.SECONDS))
+ assertEquals("x", parts[0].lines[0].text)
+ }
+
+ @Test fun withoutTheOfferNothingCanBeAskedAndAnUnaskedDiffIsIgnored() {
+ welcomeCaps = "[]"
+ val c = start()
+ assertFalse(gotPart.await(700, TimeUnit.MILLISECONDS))
+ assertFalse(c.getDiff("integration_claude", 7))
+ assertTrue(received.none { it.contains("getDiff") })
+ }
+
+ @Test fun anAppThatDidNotAskNeverAsks() {
+ val c = start(caps = listOf("chat"))
+ assertFalse(gotPart.await(700, TimeUnit.MILLISECONDS))
+ assertFalse(c.getDiff("integration_claude", 7))
+ }
+
+ @Test fun theHelloAsksForDiffs() {
+ start()
+ val hello = received.poll(2, TimeUnit.SECONDS)!!
+ assertTrue(hello, hello.contains("\"diffs\""))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/LinkHealthTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/LinkHealthTest.kt
new file mode 100644
index 00000000..b7080480
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/LinkHealthTest.kt
@@ -0,0 +1,92 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LinkHealthTest {
+ private val min = 60_000L
+
+ @Test fun theTimeAgoIsInPlainWords() {
+ assertEquals("less than a minute", LinkHealthText.ago(0))
+ assertEquals("less than a minute", LinkHealthText.ago(59_999))
+ assertEquals("1 min", LinkHealthText.ago(min))
+ assertEquals("2 min", LinkHealthText.ago(2 * min + 5_000))
+ assertEquals("59 min", LinkHealthText.ago(59 * min))
+ assertEquals("1 h", LinkHealthText.ago(60 * min))
+ assertEquals("1 h 5 min", LinkHealthText.ago(65 * min))
+ assertEquals("3 h", LinkHealthText.ago(180 * min))
+ assertEquals("less than a minute", LinkHealthText.ago(-5))
+ }
+
+ @Test fun homeSaysWhatHappenedAndHowLongAgo() {
+ val h = LinkHealth().lost(atMs = 1_000_000, why = LostReason.SILENT, screenWasOff = true)
+ val (head, why) = LinkHealthText.lines(connected = false, health = h, nowMs = 1_000_000 + 2 * min)!!
+ assertEquals("Connection lost 2 min ago, reconnecting", head)
+ assertTrue(why.contains("phone slept"))
+ assertTrue(LinkHealthText.lines(false, h.copy(reason = LostReason.CLOSED), 1_000_000)!!.second.contains("closed"))
+ assertTrue(LinkHealthText.lines(false, h.copy(reason = LostReason.NETWORK), 1_000_000)!!.second.contains("network"))
+ }
+
+ @Test fun nothingIsSaidWhenConnectedOrWhenNothingWasLost() {
+ val h = LinkHealth().lost(1_000, LostReason.NETWORK, false)
+ assertNull(LinkHealthText.lines(connected = true, health = h, nowMs = 5_000))
+ assertNull(LinkHealthText.lines(connected = false, health = LinkHealth(), nowMs = 5_000))
+ assertNull(LinkHealthText.lines(connected = false, health = h.recovered(), nowMs = 5_000))
+ }
+
+ @Test fun repeatedFailuresAreCountedAfterTheThird() {
+ val h = LinkHealth().lost(0, LostReason.NETWORK, false)
+ assertFalse(LinkHealthText.lines(false, h.failedAttempt(2), 0)!!.first.contains("tries"))
+ assertTrue(LinkHealthText.lines(false, h.failedAttempt(5), 0)!!.first.endsWith("(5 tries)"))
+ }
+
+ @Test fun theDropsWhileTheScreenWasOffAreCountedAndSurviveARecovery() {
+ var h = LinkHealth()
+ h = h.lost(1, LostReason.SILENT, screenWasOff = false)
+ assertEquals(0, h.dropsWhileScreenOff)
+ h = h.recovered().lost(2, LostReason.SILENT, screenWasOff = true)
+ h = h.recovered().lost(3, LostReason.CLOSED, screenWasOff = true)
+ assertEquals(2, h.dropsWhileScreenOff)
+ assertEquals(2, h.recovered().dropsWhileScreenOff)
+ assertNull(h.recovered().lostAtMs)
+ }
+
+ // ── the alarm and the battery hint ──
+
+ @Test fun theAlarmIsArmedOnlyForARealPairing() {
+ assertTrue(KeepAlivePolicy.shouldArm(paired = true, demo = false))
+ assertFalse(KeepAlivePolicy.shouldArm(paired = false, demo = false))
+ assertFalse(KeepAlivePolicy.shouldArm(paired = true, demo = true))
+ }
+
+ @Test fun theComputerToleratesSeveralMissedChecks() {
+ assertTrue(KeepAlivePolicy.COMPUTER_IDLE_MS >= 4 * KeepAlivePolicy.INTERVAL_MS)
+ assertTrue("Doze can stretch the alarm to about 15 minutes", KeepAlivePolicy.COMPUTER_IDLE_MS > 15 * min)
+ assertTrue(KeepAlivePolicy.WAKE_LOCK_MS <= 30_000)
+ }
+
+ @Test fun theBatteryHintComesOnlyWhenItWouldHelp() {
+ val dropped = LinkHealth(dropsWhileScreenOff = 1)
+ fun show(paired: Boolean = true, h: LinkHealth = dropped, ignoring: Boolean = false, snoozed: Long? = null, now: Long = 10_000_000_000) =
+ BatteryHint.shouldShow(paired, h, ignoring, snoozed, now)
+ assertTrue(show())
+ assertFalse("never dropped", show(h = LinkHealth()))
+ assertFalse("already unrestricted", show(ignoring = true))
+ assertFalse("not paired", show(paired = false))
+ assertFalse("said not now yesterday", show(snoozed = 10_000_000_000 - 24 * 3_600_000L))
+ assertTrue("asks again after a week", show(snoozed = 10_000_000_000 - BatteryHint.SNOOZE_MS))
+ }
+
+ @Test fun samsungGetsTheTwoPlacesAndOthersOne() {
+ assertTrue(BatteryHint.isSamsung("samsung"))
+ assertTrue(BatteryHint.isSamsung("Samsung"))
+ assertFalse(BatteryHint.isSamsung("Google"))
+ val s = BatteryHint.steps(samsung = true)
+ assertEquals(2, s.size)
+ assertTrue(s[0].contains("Unrestricted") && s[1].contains("Sleeping apps") && s[1].contains("Never sleeping apps"))
+ assertEquals(1, BatteryHint.steps(samsung = false).size)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/LinkRetryTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/LinkRetryTest.kt
new file mode 100644
index 00000000..804c63ab
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/LinkRetryTest.kt
@@ -0,0 +1,57 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The reconnect loop's two additions for finding the computer again: it reports failures, and a retry can cut the wait short. */
+class LinkRetryTest {
+ private val pairing = PairingPayload("192.168.10.6", 47821, "ab".repeat(32), "T".repeat(20), "PC")
+
+ private class Listener : LinkListener {
+ val failures = CopyOnWriteArrayList<Int>()
+ val tick = CountDownLatch(3)
+ override fun onConnectFailed(consecutive: Int) { failures.add(consecutive); tick.countDown() }
+ }
+
+ @Test fun everyFailedAttemptIsReportedWithARunningCount() {
+ val l = Listener()
+ val attempts = CopyOnWriteArrayList<Int>()
+ val c = LinkClient(
+ pairing, "test", l, connector = { timeout -> attempts.add(timeout); throw IOException("no route") },
+ backoffMs = longArrayOf(5), caps = emptyList(),
+ )
+ c.start()
+ assertTrue(l.tick.await(5, TimeUnit.SECONDS))
+ c.stop()
+ assertEquals(listOf(1, 2, 3), l.failures.take(3))
+ assertTrue("the saved address gets the short timeout", attempts.all { it == DiscoveryPolicy.SAVED_CONNECT_TIMEOUT_MS })
+ }
+
+ @Test fun retryNowCutsALongBackoffShort() {
+ val l = object : LinkListener {
+ val second = CountDownLatch(2)
+ override fun onConnectFailed(consecutive: Int) { second.countDown() }
+ }
+ val c = LinkClient(pairing, "test", l, connector = { throw IOException("no route") }, backoffMs = longArrayOf(60_000), caps = emptyList())
+ c.start()
+ Thread.sleep(300) // first attempt failed, now waiting a minute
+ assertEquals(1L, l.second.count)
+ c.retryNow()
+ assertTrue("the second attempt follows at once", l.second.await(3, TimeUnit.SECONDS))
+ c.stop()
+ }
+
+ @Test fun stoppingEndsTheWaitToo() {
+ val c = LinkClient(pairing, "test", object : LinkListener {}, connector = { throw IOException("x") }, backoffMs = longArrayOf(60_000), caps = emptyList())
+ c.start()
+ Thread.sleep(200)
+ val t0 = System.nanoTime()
+ c.stop()
+ assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0) < 1_000)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/PairingTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/PairingTest.kt
new file mode 100644
index 00000000..e465dd7f
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/PairingTest.kt
@@ -0,0 +1,51 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+import java.security.cert.CertificateException
+
+class PairingTest {
+ private val fp = "ab".repeat(32)
+ private val token = "A1b2C3d4E5f6G7h8I9j0"
+ private val good = "coucou://pair?v=1&host=192.168.1.20&port=47821&fp=$fp&token=$token&name=My%20PC"
+
+ @Test fun parsesAWellFormedLink() {
+ val p = PairingPayload.parse(good)!!
+ assertEquals("192.168.1.20", p.host)
+ assertEquals(47821, p.port)
+ assertEquals(fp, p.certSha256)
+ assertEquals(token, p.token)
+ assertEquals("My PC", p.desktopName)
+ }
+
+ @Test fun toleratesSurroundingWhitespace() {
+ assertNotNull(PairingPayload.parse(" $good\n"))
+ }
+
+ @Test fun rejectsEverythingElse() {
+ val bad = listOf(
+ "", "https://pair?v=1", "coucou://other?v=1&host=h&port=1&fp=$fp&token=$token",
+ good.replace("v=1", "v=2"), good.replace("port=47821", "port=0"), good.replace("port=47821", "port=70000"),
+ good.replace("port=47821", "port=abc"), good.replace("fp=$fp", "fp=short"), good.replace("host=192.168.1.20&", ""),
+ good.replace("token=$token", "token=short"), good.replace("token=$token", "token=${"a".repeat(129)}"),
+ good.replace("token=$token", "token=bad%20chars%21%21%21%21%21%21"),
+ )
+ for (b in bad) assertNull(b, PairingPayload.parse(b))
+ }
+
+ @Test fun uppercaseFingerprintIsNormalised() {
+ assertEquals(fp, PairingPayload.parse(good.replace(fp, fp.uppercase()))!!.certSha256)
+ }
+
+ @Test fun pinnedTrustManagerRejectsNonMatchingAndEmptyChains() {
+ val tm = PinnedTrustManager(fp)
+ try { tm.checkServerTrusted(emptyArray(), "ECDHE_ECDSA"); fail("empty chain accepted") } catch (_: CertificateException) { }
+ try { tm.checkServerTrusted(null, "ECDHE_ECDSA"); fail("null chain accepted") } catch (_: CertificateException) { }
+ try { tm.checkClientTrusted(emptyArray(), "x"); fail("client certs accepted") } catch (_: CertificateException) { }
+ assertTrue(tm.acceptedIssuers.isEmpty())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/PinnedProbeTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/PinnedProbeTest.kt
new file mode 100644
index 00000000..6cd397c0
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/PinnedProbeTest.kt
@@ -0,0 +1,97 @@
+package com.coucou.android.link
+
+import java.io.File
+import java.net.InetAddress
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.util.concurrent.atomic.AtomicInteger
+import javax.net.ssl.KeyManagerFactory
+import javax.net.ssl.SSLContext
+import javax.net.ssl.SSLServerSocket
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/**
+ * The rule that matters most: a lookalike on the network cannot get the token. These tests run real TLS on the loopback
+ * with two throwaway self-signed certificates (made with the JDK's keytool; skipped where it is missing).
+ */
+class PinnedProbeTest {
+ private class Server(val sha256: String, val socket: SSLServerSocket) {
+ /** Bytes of application data this server received after the handshake: the token would be in them. */
+ val received = AtomicInteger()
+ @Volatile var handshakes = 0
+ val thread = Thread {
+ try {
+ while (true) {
+ val c = socket.accept()
+ try {
+ (c as javax.net.ssl.SSLSocket).startHandshake()
+ handshakes++
+ c.soTimeout = 400
+ val buf = ByteArray(256)
+ while (true) { val n = c.getInputStream().read(buf); if (n < 0) break; received.addAndGet(n) }
+ } catch (_: Exception) {
+ } finally { runCatching { c.close() } }
+ }
+ } catch (_: Exception) {
+ }
+ }.apply { isDaemon = true; start() }
+ val port get() = socket.localPort
+ fun close() = runCatching { socket.close() }
+ }
+
+ private fun server(dir: File, alias: String): Server? {
+ val file = File(dir, "$alias.p12")
+ val p = runCatching {
+ ProcessBuilder(
+ "keytool", "-genkeypair", "-alias", alias, "-keyalg", "EC", "-groupname", "secp256r1", "-dname", "CN=$alias",
+ "-validity", "3650", "-storetype", "PKCS12", "-keystore", file.path, "-storepass", "changeit", "-keypass", "changeit",
+ ).redirectErrorStream(true).start()
+ }.getOrNull() ?: return null
+ p.inputStream.readBytes()
+ if (p.waitFor() != 0) return null
+ val ks = KeyStore.getInstance("PKCS12").apply { file.inputStream().use { load(it, "changeit".toCharArray()) } }
+ val sha = MessageDigest.getInstance("SHA-256").digest(ks.getCertificate(alias).encoded).joinToString("") { "%02x".format(it) }
+ val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(ks, "changeit".toCharArray()) }
+ val ctx = SSLContext.getInstance("TLS").apply { init(kmf.keyManagers, null, null) }
+ val ss = ctx.serverSocketFactory.createServerSocket(0, 5, InetAddress.getByName("127.0.0.1")) as SSLServerSocket
+ return Server(sha, ss)
+ }
+
+ private fun dir() = java.nio.file.Files.createTempDirectory("coucou-probe").toFile()
+
+ @Test fun theRealComputerPassesAndALookalikeDoesNot() {
+ val d = dir()
+ val real = server(d, "real"); val fake = server(d, "fake")
+ assumeTrue("keytool needed", real != null && fake != null)
+ try {
+ assertEquals(ProbeResult.MATCH, PinnedProbe.check("127.0.0.1", real!!.port, real.sha256))
+ // the lookalike answers on its own port with its own certificate: the pinned fingerprint is the real one's
+ assertEquals(ProbeResult.PIN_MISMATCH, PinnedProbe.check("127.0.0.1", fake!!.port, real.sha256))
+ assertEquals("the probe sends no application data at all, so no token", 0, real.received.get() + fake.received.get())
+ } finally { real?.close(); fake?.close() }
+ }
+
+ @Test fun nothingListeningIsUnreachableNotAMismatch() {
+ val s = java.net.ServerSocket(0).also { it.close() } // a port that was free a moment ago
+ assertEquals(ProbeResult.UNREACHABLE, PinnedProbe.check("127.0.0.1", s.localPort, "ab".repeat(32)))
+ }
+
+ @Test fun theRealLinkNeverSendsTheTokenToAMismatchingCertificate() {
+ val d = dir()
+ val real = server(d, "real2"); val fake = server(d, "fake2")
+ assumeTrue("keytool needed", real != null && fake != null)
+ try {
+ val token = "secret_token_1234567"
+ // paired with the real certificate, but the address found points at the lookalike
+ val pairing = PairingPayload("127.0.0.1", fake!!.port, real!!.sha256, token, "PC")
+ val failed = runCatching { PinnedTls.connector(pairing).connect(2_000) }
+ assertTrue("the handshake must fail", failed.isFailure)
+ Thread.sleep(300)
+ assertEquals("the lookalike received nothing", 0, fake.received.get())
+ assertEquals("and never completed a handshake with us", 0, fake.handshakes)
+ } finally { real?.close(); fake?.close() }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolAnswersTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolAnswersTest.kt
new file mode 100644
index 00000000..0b5b22a8
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolAnswersTest.kt
@@ -0,0 +1,63 @@
+package com.coucou.android.link
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolAnswersTest {
+ private val fp = "ab".repeat(32)
+
+ private fun question(vararg q: String, extra: String = "") =
+ """{"type":"question","pillId":"integration_claude","fingerprint":"$fp","createdAt":1700000000000,"questions":[${q.joinToString(",")}]$extra}"""
+
+ private fun q(text: String, vararg labels: String, multi: Boolean = false) =
+ """{"question":"$text","multiSelect":$multi,"options":[${labels.joinToString(",") { """{"label":"$it","description":"about $it"}""" }}]}"""
+
+ @Test fun aQuestionIsDecodedWithItsOptions() {
+ val m = Wire.decodeServer(question(q("Which?", "A", "B"), q("Extras?", "X", "Y", multi = true))) as ServerMsg.Question
+ assertEquals("integration_claude", m.request.pillId)
+ assertEquals(fp, m.request.fingerprint)
+ assertEquals(2, m.request.questions.size)
+ assertEquals(listOf("A", "B"), m.request.questions[0].options.map { it.label })
+ assertEquals("about A", m.request.questions[0].options[0].description)
+ assertTrue(m.request.questions[1].multiSelect)
+ assertFalse(m.request.questions[0].multiSelect)
+ }
+
+ @Test fun aQuestionThatBreaksTheLimitsIsDroppedNotCrashed() {
+ assertNull("no questions", Wire.decodeServer(question()))
+ assertNull("no option", Wire.decodeServer(question(q("Which?"))))
+ assertNull("twin labels", Wire.decodeServer(question(q("Which?", "A", "A"))))
+ assertNull("blank label", Wire.decodeServer(question(q("Which?", "A", " "))))
+ assertNull("blank question", Wire.decodeServer(question(q(" ", "A"))))
+ assertNull("too many questions", Wire.decodeServer(question(*Array(5) { q("Q$it?", "A") })))
+ assertNull("too many options", Wire.decodeServer(question(q("Which?", *Array(9) { "o$it" }))))
+ assertNull("not a fingerprint", Wire.decodeServer(question(q("Which?", "A")).replace(fp, "nope")))
+ assertNull("wrong shape", Wire.decodeServer("""{"type":"question","pillId":"p","fingerprint":"$fp","questions":"x"}"""))
+ }
+
+ @Test fun anAnswerIsOneListOfLabelsPerQuestionAndNothingElse() {
+ val line = Wire.encode(ClientMsg.Answer(fp, listOf(listOf("B"), listOf("X", "Y"))))
+ val o = JSONObject(line)
+ assertEquals("answer", o.getString("type"))
+ assertEquals(fp, o.getString("fingerprint"))
+ assertEquals("""[["B"],["X","Y"]]""", o.getJSONArray("picks").toString())
+ assertEquals(setOf("type", "fingerprint", "picks"), o.keys().asSequence().toSet())
+ }
+
+ @Test fun theHelloAsksForAnswersAmongTheOtherCapabilities() {
+ assertTrue(Protocol.CAP_ANSWERS in Protocol.CAPABILITIES)
+ val hello = JSONObject(Wire.encode(ClientMsg.Hello(1, "T".repeat(20), "Phone", Protocol.CAPABILITIES)))
+ assertTrue(hello.getJSONArray("caps").toString().contains("answers"))
+ // an app asking for nothing sends the v1 hello unchanged
+ assertFalse(JSONObject(Wire.encode(ClientMsg.Hello(1, "T".repeat(20), "Phone"))).has("caps"))
+ }
+
+ @Test fun anOldComputerThatSendsNoQuestionChangesNothing() {
+ // unknown to an old phone, ignored by a new one when it was not offered (see LinkAnswersTest)
+ assertEquals(setOf("chat", "details", "answers", "prefs", "diffs", "usage", "services", "relay"), Protocol.CAPABILITIES.toSet())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolChatTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolChatTest.kt
new file mode 100644
index 00000000..65d45a00
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolChatTest.kt
@@ -0,0 +1,82 @@
+package com.coucou.android.link
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The chat part of the wire format, and that nothing else about it changed. */
+class ProtocolChatTest {
+ @Test fun aHelloWithNoCapsIsExactlyTheOldHello() {
+ val o = JSONObject(Wire.encode(ClientMsg.Hello(1, "tok", "Pixel")))
+ assertEquals(setOf("type", "v", "token", "device"), o.keys().asSequence().toSet())
+ }
+
+ @Test fun aHelloAsksForTheOptionalFeaturesTheAppHas() {
+ val o = JSONObject(Wire.encode(ClientMsg.Hello(1, "tok", "Pixel", Protocol.CAPABILITIES)))
+ assertEquals(listOf("chat", "details", "answers", "prefs", "diffs", "usage", "services", "relay"), (0 until o.getJSONArray("caps").length()).map { o.getJSONArray("caps").getString(it) })
+ }
+
+ @Test fun aWelcomeWithoutCapsOffersNothing() {
+ val w = Wire.decodeServer("""{"type":"welcome","v":1,"desktop":"PC","os":"windows"}""") as ServerMsg.Welcome
+ assertEquals(emptySet<String>(), w.caps)
+ }
+
+ @Test fun aWelcomeOffersTheCapsItNames_ignoringJunk() {
+ val w = Wire.decodeServer("""{"type":"welcome","v":1,"desktop":"PC","os":"x","caps":["chat","details",5,"",null]}""") as ServerMsg.Welcome
+ assertTrue("chat" in w.caps && "details" in w.caps)
+ assertFalse("" in w.caps)
+ val odd = Wire.decodeServer("""{"type":"welcome","v":1,"desktop":"PC","os":"x","caps":"chat"}""") as ServerMsg.Welcome
+ assertEquals(emptySet<String>(), odd.caps)
+ }
+
+ @Test fun chatMessagesToTheComputer() {
+ assertEquals("""{"type":"chatModels"}""", Wire.encode(ClientMsg.ChatModels))
+ assertEquals("""{"type":"chatReset"}""", Wire.encode(ClientMsg.ChatReset))
+ val send = JSONObject(Wire.encode(ClientMsg.ChatSend("c1", "openai/gpt", "héllo \"q\"\nnew line")))
+ assertEquals("chatSend", send.getString("type"))
+ assertEquals("c1", send.getString("id"))
+ assertEquals("openai/gpt", send.getString("model"))
+ assertEquals("héllo \"q\"\nnew line", send.getString("text"))
+ assertFalse("a message is one line", Wire.encode(ClientMsg.ChatSend("c1", "m/x", "a\nb")).contains('\n'))
+ assertEquals("c9", JSONObject(Wire.encode(ClientMsg.ChatCancel("c9"))).getString("id"))
+ }
+
+ @Test fun theModelListKeepsIdsProvidersAndLabels() {
+ val m = Wire.decodeServer(
+ """{"type":"chatModels","models":[{"id":"openai/gpt-4o","provider":"openai","label":"OpenAI · gpt-4o"},{"id":"ollama/llama3"},{"id":"noslash"},{"id":""},{"label":"x"}]}""",
+ ) as ServerMsg.ChatModels
+ assertEquals(
+ listOf(ChatModel("openai/gpt-4o", "openai", "OpenAI · gpt-4o"), ChatModel("ollama/llama3", "ollama", "ollama/llama3")),
+ m.models,
+ )
+ assertEquals(emptyList<ChatModel>(), (Wire.decodeServer("""{"type":"chatModels","models":[]}""") as ServerMsg.ChatModels).models)
+ }
+
+ @Test fun anAnswerArrivesAsDeltasThenDoneOrAnError() {
+ assertEquals(ServerMsg.ChatDelta("c1", "Hel"), Wire.decodeServer("""{"type":"chatDelta","id":"c1","text":"Hel"}"""))
+ assertEquals(ServerMsg.ChatDone("c1", null), Wire.decodeServer("""{"type":"chatDone","id":"c1"}"""))
+ assertEquals(ServerMsg.ChatDone("c1", "Full"), Wire.decodeServer("""{"type":"chatDone","id":"c1","text":"Full"}"""))
+ assertEquals(
+ ServerMsg.ChatError("c1", "rate", "Too many messages."),
+ Wire.decodeServer("""{"type":"chatError","id":"c1","reason":"rate","message":"Too many messages."}"""),
+ )
+ // a reason the app does not know is kept as it is; a missing one is "internal"
+ assertEquals("internal", (Wire.decodeServer("""{"type":"chatError","id":"c1"}""") as ServerMsg.ChatError).reason)
+ }
+
+ @Test fun malformedChatLinesNeverThrow() {
+ for (bad in listOf(
+ """{"type":"chatDelta","id":"c1"}""", """{"type":"chatDelta","text":"x"}""", """{"type":"chatDelta","id":"","text":"x"}""",
+ """{"type":"chatDelta","id":"a b","text":"x"}""", """{"type":"chatDelta","id":"${"a".repeat(65)}","text":"x"}""",
+ """{"type":"chatDone"}""", """{"type":"chatError","reason":"x"}""", """{"type":"chatModels"}""", """{"type":"chatModels","models":5}""",
+ )) assertNull(bad, Wire.decodeServer(bad))
+ }
+
+ @Test fun chatIds() {
+ for (ok in listOf("c1", "abc-DEF_09", "a".repeat(64))) assertTrue(ok, Wire.isChatId(ok))
+ for (bad in listOf("", "a b", "é", "a/b", "a".repeat(65), "a\n")) assertFalse(bad, Wire.isChatId(bad))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDetailsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDetailsTest.kt
new file mode 100644
index 00000000..ea8fd117
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDetailsTest.kt
@@ -0,0 +1,69 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Session details (cap `details`) on the wire, and that a v1 session still reads exactly as before. */
+class ProtocolDetailsTest {
+ private fun session(json: String): SessionInfo =
+ (Wire.decodeServer("""{"type":"sessions","sessions":[$json]}""") as ServerMsg.Sessions).sessions.single()
+
+ @Test fun aV1SessionHasNoDetails() {
+ val s = session("""{"pillId":"agent_codex","agent":"Codex","state":"working","statusText":"Editing","stepIndex":2,"stepCount":5,"updatedAt":1700}""")
+ assertEquals(emptyList<String>(), s.steps)
+ assertNull(s.finalLine); assertNull(s.project); assertNull(s.color)
+ assertEquals(BotState.WORKING, s.state)
+ }
+
+ @Test fun detailsAreReadWhenPresent() {
+ val s = session(
+ """{"pillId":"p","state":"finished","steps":["Read · a.rs","Edit · a.rs"],"finalLine":"All done","project":"coucou","color":"#2DD4BF"}""",
+ )
+ assertEquals(listOf("Read · a.rs", "Edit · a.rs"), s.steps)
+ assertEquals("All done", s.finalLine)
+ assertEquals("coucou", s.project)
+ assertEquals("#2DD4BF", s.color)
+ }
+
+ @Test fun theWelcomeNamesDetails() {
+ val w = Wire.decodeServer("""{"type":"welcome","v":1,"desktop":"PC","os":"x","caps":["details"]}""") as ServerMsg.Welcome
+ assertTrue(Protocol.CAP_DETAILS in w.caps && Protocol.CAP_CHAT !in w.caps)
+ }
+
+ @Test fun aProjectIsNeverAPathEvenIfTheComputerSendsOne() {
+ for ((raw, want) in listOf(
+ "/home/me/secret/app" to "app", "C:\\Users\\me\\app" to "app", "C:\\Users\\me\\app\\" to "app", "app/" to "app", "app" to "app",
+ )) {
+ val s = session("""{"pillId":"p","project":${org.json.JSONObject.quote(raw)}}""")
+ assertEquals(raw, want, s.project)
+ }
+ for (none in listOf("", "/", "..", "/a/..", ".", " ")) {
+ assertNull(none, session("""{"pillId":"p","project":${org.json.JSONObject.quote(none)}}""").project)
+ }
+ assertEquals(Protocol.MAX_PROJECT_CHARS, session("""{"pillId":"p","project":"${"x".repeat(300)}"}""").project!!.length)
+ }
+
+ @Test fun onlyASixDigitColourIsKept() {
+ for (ok in listOf("#8AB4F8", "#000000", "#abcdef")) assertEquals(ok, session("""{"pillId":"p","color":"$ok"}""").color)
+ for (bad in listOf("", "red", "8AB4F8", "#12", "#GGGGGG", "#12345678", "url(x)")) assertNull(bad, session("""{"pillId":"p","color":"$bad"}""").color)
+ }
+
+ @Test fun stepsAreCappedAndOddEntriesSkipped() {
+ val many = (1..40).joinToString(",") { "\"s$it\"" }
+ val s = session("""{"pillId":"p","steps":[$many,5,null,"",{"a":1},"${"x".repeat(500)}"]}""")
+ assertEquals(Protocol.MAX_STEPS, s.steps.size)
+ assertEquals("s1", s.steps.first())
+ val long = session("""{"pillId":"p","steps":["${"y".repeat(500)}"]}""").steps.single()
+ assertEquals(Protocol.MAX_STEP_CHARS, long.length)
+ assertEquals(emptyList<String>(), session("""{"pillId":"p","steps":"not a list"}""").steps)
+ }
+
+ @Test fun anEmptyFinalLineIsNoFinalLine() {
+ assertNull(session("""{"pillId":"p","finalLine":" "}""").finalLine)
+ assertFalse(session("""{"pillId":"p","finalLine":"x"}""").finalLine.isNullOrBlank())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDiffsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDiffsTest.kt
new file mode 100644
index 00000000..55e7d2dc
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolDiffsTest.kt
@@ -0,0 +1,92 @@
+package com.coucou.android.link
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolDiffsTest {
+ private fun sessionWith(files: String) = Wire.decodeServer(
+ """{"type":"sessions","sessions":[{"pillId":"integration_claude","agent":"Claude Code","state":"working","statusText":"x","stepIndex":1,"stepCount":2,"files":$files}]}""",
+ ) as ServerMsg.Sessions
+
+ @Test fun aSessionWithoutFilesHasNone() {
+ assertEquals(emptyList<FileChange>(), sessionWith("[]").sessions[0].files)
+ val plain = Wire.decodeServer("""{"type":"sessions","sessions":[{"pillId":"a","agent":"x","state":"idle"}]}""") as ServerMsg.Sessions
+ assertEquals(emptyList<FileChange>(), plain.sessions[0].files)
+ }
+
+ @Test fun filesAreReadAsNamesAndCounts() {
+ val f = sessionWith("""[{"id":3,"name":"app.ts","added":2,"removed":1},{"id":4,"name":"n.md","added":9,"removed":0,"tooLarge":true,"isNew":true}]""").sessions[0].files
+ assertEquals(FileChange(3, "app.ts", 2, 1), f[0])
+ assertEquals(FileChange(4, "n.md", 9, 0, tooLarge = true, isNew = true), f[1])
+ }
+
+ @Test fun evenIfAPathIsSentOnlyTheNameIsKept() {
+ val f = sessionWith("""[{"id":1,"name":"/home/me/secret/app.ts"},{"id":2,"name":"C:\\Users\\me\\notes.md"},{"id":3,"name":"dir/"}]""").sessions[0].files
+ assertEquals(listOf("app.ts", "notes.md", "dir"), f.map { it.name })
+ assertFalse(f.toString().contains("secret") || f.toString().contains("Users"))
+ }
+
+ @Test fun anEntryWithoutAnIdOrANameIsSkippedAndCountsCannotBeNegative() {
+ val f = sessionWith("""[{"name":"a"},{"id":1},{"id":2,"name":""},{"id":3,"name":".."},{"id":-4,"name":"neg"},{"id":5,"name":"ok","added":-3,"removed":-1},"junk",7]""").sessions[0].files
+ assertEquals(listOf(FileChange(5, "ok", 0, 0)), f)
+ }
+
+ @Test fun atMostTwentyFilesTheNewest() {
+ val many = (0 until 30).joinToString(",", "[", "]") { """{"id":$it,"name":"f$it"}""" }
+ val f = sessionWith(many).sessions[0].files
+ assertEquals(20, f.size)
+ assertEquals(10L, f.first().id)
+ assertEquals(29L, f.last().id)
+ }
+
+ @Test fun aLongNameIsCut() {
+ val f = sessionWith("""[{"id":1,"name":"${"n".repeat(300)}"}]""").sessions[0].files
+ assertEquals(Protocol.MAX_FILE_NAME_CHARS, f[0].name.length)
+ }
+
+ @Test fun getDiffIsEncoded() {
+ val o = JSONObject(Wire.encode(ClientMsg.GetDiff("integration_claude", 7)))
+ assertEquals("getDiff", o.getString("type"))
+ assertEquals("integration_claude", o.getString("pillId"))
+ assertEquals(7L, o.getLong("fileId"))
+ }
+
+ private fun diff(extra: String = "", lines: String = """[["+","a"],["-","b"]]""", part: Int = 0, parts: Int = 1) = Wire.decodeServer(
+ """{"type":"diff","pillId":"integration_claude","fileId":7,"name":"/x/app.ts","added":1,"removed":1,"tooLarge":false,"gone":false,"truncated":false,"part":$part,"parts":$parts,"lines":$lines$extra}""",
+ )
+
+ @Test fun aDiffPartIsRead() {
+ val d = diff() as ServerMsg.Diff
+ assertEquals("app.ts", d.name)
+ assertEquals(listOf(DiffRow('+', "a"), DiffRow('-', "b")), d.lines)
+ assertEquals(7L, d.fileId)
+ }
+
+ @Test fun anUnknownKindIsAContextLineAndLongTextIsCut() {
+ val d = diff(lines = """[["x","y"],["+","${"z".repeat(900)}"],["@@","h"]]""") as ServerMsg.Diff
+ assertEquals(' ', d.lines[0].kind)
+ assertEquals(Protocol.MAX_DIFF_LINE_CHARS, d.lines[1].text.length)
+ assertEquals(' ', d.lines[2].kind)
+ }
+
+ @Test fun aPartBeyondTheComputersLimitsIsDropped() {
+ val tooMany = (0..100).joinToString(",", "[", "]") { """["+","l"]""" }
+ assertNull(diff(lines = tooMany))
+ assertNotNull(diff(lines = (0 until 100).joinToString(",", "[", "]") { """["+","l"]"""}))
+ assertNull(diff(part = 1, parts = 1))
+ assertNull(diff(part = 0, parts = 0))
+ assertNull(diff(part = 0, parts = 5))
+ assertNull(diff(part = -1, parts = 2))
+ assertNull(Wire.decodeServer("""{"type":"diff","pillId":"a","fileId":1,"part":0,"parts":1}"""))
+ assertNull(diff(lines = """[["+"]]"""))
+ }
+
+ @Test fun theHelloAsksForDiffs() {
+ assertTrue(Protocol.CAP_DIFFS in Protocol.CAPABILITIES)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolPrefsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolPrefsTest.kt
new file mode 100644
index 00000000..289decd0
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolPrefsTest.kt
@@ -0,0 +1,36 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.outfit.Wardrobe
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolPrefsTest {
+ @Test fun everyWardrobeValueIsRead() {
+ for (v in Wardrobe.SELECTIONS) {
+ assertEquals(ServerMsg.Prefs(v), Wire.decodeServer("""{"type":"prefs","outfit":"$v"}"""))
+ }
+ }
+
+ @Test fun aValueThisBuildDoesNotKnowIsDroppedNotGuessed() {
+ for (bad in listOf("topHat", "", "Beanie", "beanie ", "../x")) {
+ assertNull(bad, Wire.decodeServer("""{"type":"prefs","outfit":"$bad"}"""))
+ }
+ assertNull(Wire.decodeServer("""{"type":"prefs"}"""))
+ assertNull(Wire.decodeServer("""{"type":"prefs","outfit":5}"""))
+ assertNull(Wire.decodeServer("""{"type":"prefs","outfit":null}"""))
+ }
+
+ @Test fun theHelloAsksForPrefs() {
+ assertTrue(Protocol.CAP_PREFS in Protocol.CAPABILITIES)
+ val o = JSONObject(Wire.encode(ClientMsg.Hello(1, "T".repeat(20), "Phone", Protocol.CAPABILITIES)))
+ assertTrue(o.getJSONArray("caps").toString().contains("prefs"))
+ }
+
+ @Test fun nothingIsSentBackAboutIt() {
+ assertFalse(Wire.encode(ClientMsg.Ping).contains("prefs"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolServicesTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolServicesTest.kt
new file mode 100644
index 00000000..2152be0e
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolServicesTest.kt
@@ -0,0 +1,54 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolServicesTest {
+ private fun cards(json: String) = (Wire.decodeServer("""{"type":"services","services":$json}""") as ServerMsg.Services).cards
+
+ @Test fun aCardIsRead() {
+ val c = cards("""[{"id":"integration_stripe","title":"Stripe","headline":"12.50 EUR","reason":"Payments","items":[{"label":"Payment","detail":"+9.00 · 2m"}]}]""")
+ assertEquals(ServiceCard("integration_stripe", "Stripe", "12.50 EUR", "Payments", listOf(ServiceLine("Payment", "+9.00 · 2m"))), c[0])
+ }
+
+ @Test fun anEmptyListTakesTheCardsAway() {
+ assertEquals(emptyList<ServiceCard>(), cards("[]"))
+ }
+
+ @Test fun onlyTheKnownServicesAndOnceEach() {
+ val c = cards("""[{"id":"integration_evil","title":"x","headline":"y"},{"id":"integration_stripe","title":"S","headline":"1"},{"id":"integration_stripe","title":"again","headline":"2"},5,"junk"]""")
+ assertEquals(listOf("integration_stripe"), c.map { it.id })
+ assertEquals("S", c[0].title)
+ }
+
+ @Test fun textsAreOneShortLineAndThereAreAtMostThreeLines() {
+ val long = "x".repeat(300)
+ val c = cards(
+ """[{"id":"integration_github","title":"G","headline":"$long\n\u0007","reason":" ","items":[{"label":"a","detail":"1"},{"label":"b","detail":"2"},{"label":"","detail":"empty"},{"label":"c","detail":"3"},{"label":"d","detail":"4"}]}]""",
+ )[0]
+ assertEquals(Protocol.MAX_SERVICE_TEXT, c.headline.length)
+ assertFalse(c.headline.any { it.isISOControl() })
+ assertEquals(null, c.reason)
+ assertEquals(listOf("a", "b", "c"), c.items.map { it.label })
+ }
+
+ @Test fun aCardMissingItsFieldsStillReads() {
+ val c = cards("""[{"id":"integration_calcom"}]""")[0]
+ assertEquals("", c.headline)
+ assertEquals(emptyList<ServiceLine>(), c.items)
+ }
+
+ @Test fun theHelloAsksForServices() {
+ assertTrue(Protocol.CAP_SERVICES in Protocol.CAPABILITIES)
+ }
+
+ @Test fun theKnownIdsAreThoseOfTheCatalog() {
+ val ts = com.coucou.android.ReferenceFiles.read("windows/src/core/pills.ts")
+ for (id in listOf("integration_stripe", "integration_github", "integration_vercel", "integration_n8n", "integration_resend", "integration_notion", "integration_calcom")) {
+ assertTrue(id, ts.contains("\"$id\""))
+ assertEquals(id, 1, cards("""[{"id":"$id","title":"t","headline":"h"}]""").size)
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolTest.kt
new file mode 100644
index 00000000..69ce3667
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolTest.kt
@@ -0,0 +1,85 @@
+package com.coucou.android.link
+
+import com.coucou.android.mochi.BotState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolTest {
+ private val fp = "0b2944f472c9dda6c1d369e7c161730641be8e67174c8eb67c887a2fe0ccd30d"
+
+ @Test fun fingerprintMatchesTheMacDerivation() {
+ // Vector computed independently with Node's crypto over the U+001F-joined fields.
+ assertEquals(fp, Fingerprint.of("agent_codex", "sess-1", "Bash", "rm -rf build", "k1"))
+ }
+
+ @Test fun fingerprintChangesWithAnyField() {
+ val base = Fingerprint.of("p", "s", "t", "c", "i")
+ assertFalse(base == Fingerprint.of("p", "s", "t", "c2", "i"))
+ assertFalse(base == Fingerprint.of("p", "s2", "t", "c", "i"))
+ // Field boundaries matter: moving text between fields is a different request.
+ assertFalse(Fingerprint.of("a", "bc", "t", "c", "i") == Fingerprint.of("ab", "c", "t", "c", "i"))
+ }
+
+ @Test fun encodesClientMessages() {
+ val d = org.json.JSONObject(Wire.encode(ClientMsg.Decision(fp, true)))
+ assertEquals("decision", d.getString("type")); assertEquals(fp, d.getString("fingerprint")); assertEquals("allow", d.getString("decision"))
+ assertTrue(Wire.encode(ClientMsg.Decision(fp, false)).contains(""""decision":"deny""""))
+ assertEquals("ping", org.json.JSONObject(Wire.encode(ClientMsg.Ping)).getString("type"))
+ val hello = Wire.encode(ClientMsg.Hello(1, "tok", "Pixel"))
+ assertTrue(hello.contains(""""type":"hello"""") && hello.contains(""""token":"tok""""))
+ }
+
+ @Test fun decodesSessions() {
+ val m = Wire.decodeServer(
+ """{"type":"sessions","sessions":[{"pillId":"agent_codex","agent":"Codex","state":"working","statusText":"Editing","stepIndex":2,"stepCount":5,"updatedAt":1700}]}""",
+ ) as ServerMsg.Sessions
+ assertEquals(1, m.sessions.size)
+ with(m.sessions[0]) {
+ assertEquals("agent_codex", pillId)
+ assertEquals(BotState.WORKING, state)
+ assertEquals(2, stepIndex)
+ assertEquals(5, stepCount)
+ }
+ }
+
+ @Test fun unknownStateFallsBackToIdle() {
+ val m = Wire.decodeServer("""{"type":"sessions","sessions":[{"pillId":"p","state":"levitating"}]}""") as ServerMsg.Sessions
+ assertEquals(BotState.IDLE, m.sessions[0].state)
+ }
+
+ @Test fun decodesApprovalAndRejectsBadFingerprints() {
+ val ok = Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"$fp","tool":"Bash","command":"ls","createdAt":5}""")
+ assertTrue(ok is ServerMsg.Approval)
+ assertNull(Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"nothex","tool":"Bash","command":"ls","createdAt":5}"""))
+ assertNull(Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"${fp.uppercase()}","tool":"Bash","command":"ls","createdAt":5}"""))
+ }
+
+ @Test fun aCutCommandIsFlaggedAndAnOldComputerMeansNotCut() {
+ val cut = Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"$fp","tool":"Bash","command":"ls","truncated":true,"createdAt":5}""") as ServerMsg.Approval
+ assertTrue(cut.request.truncated)
+ val whole = Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"$fp","tool":"Bash","command":"ls","truncated":false,"createdAt":5}""") as ServerMsg.Approval
+ assertFalse(whole.request.truncated)
+ // A computer from before the flag sends nothing: that is how it always was, so not cut.
+ val old = Wire.decodeServer("""{"type":"approval","pillId":"p","fingerprint":"$fp","tool":"Bash","command":"ls","createdAt":5}""") as ServerMsg.Approval
+ assertFalse(old.request.truncated)
+ }
+
+ @Test fun malformedInputNeverThrows() {
+ for (bad in listOf("", "not json", "{}", """{"type":1}""", """{"type":"sessions"}""", """{"type":"welcome"}""", """{"type":"nope"}""", "[]")) {
+ assertNull(bad, Wire.decodeServer(bad))
+ }
+ }
+
+ @Test fun oversizeLineIsRejected() {
+ assertNull(Wire.decodeServer("""{"type":"pong","pad":"${"x".repeat(Protocol.MAX_LINE_BYTES)}"}"""))
+ }
+
+ @Test fun decodesSimpleMessages() {
+ assertEquals(ServerMsg.Pong, Wire.decodeServer("""{"type":"pong"}"""))
+ assertEquals(ServerMsg.ApprovalResolved(fp), Wire.decodeServer("""{"type":"approvalResolved","fingerprint":"$fp"}"""))
+ assertEquals(ServerMsg.Welcome(1, "PC", "windows"), Wire.decodeServer("""{"type":"welcome","v":1,"desktop":"PC","os":"windows"}"""))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ProtocolUsageTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolUsageTest.kt
new file mode 100644
index 00000000..327e55a9
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ProtocolUsageTest.kt
@@ -0,0 +1,44 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ProtocolUsageTest {
+ private fun usage(json: String) = (Wire.decodeServer(json) as ServerMsg.Usage).usage
+
+ @Test fun bothPlansAreRead() {
+ val u = usage("""{"type":"usage","claude":{"fiveHour":{"pct":42,"resetsAt":1900000000000},"sevenDay":{"pct":7,"resetsAt":1900500000000},"updatedAt":5},"codex":{"sevenDay":{"pct":100,"resetsAt":1900500000000},"resetCredits":2,"plan":"plus"}}""")
+ assertEquals(PlanWindow(42, 1_900_000_000_000), u.claude!!.fiveHour)
+ assertEquals(PlanWindow(7, 1_900_500_000_000), u.claude!!.sevenDay)
+ assertEquals(5L, u.claude!!.updatedAtMs)
+ assertNull(u.codex!!.fiveHour)
+ assertEquals(2, u.codex!!.resetCredits)
+ assertEquals("plus", u.codex!!.plan)
+ }
+
+ @Test fun anEmptyMessageTakesTheUsageAway() {
+ val u = usage("""{"type":"usage"}""")
+ assertNull(u.claude)
+ assertNull(u.codex)
+ }
+
+ @Test fun aPlanWithoutAUsableWindowIsLeftOut() {
+ val u = usage("""{"type":"usage","claude":{"fiveHour":{"pct":101,"resetsAt":5},"sevenDay":{"pct":-1,"resetsAt":5}},"codex":{"fiveHour":{"pct":5}}}""")
+ assertNull(u.claude)
+ assertNull(u.codex)
+ }
+
+ @Test fun nonsenseAroundAWindowIsDroppedNotTrusted() {
+ val u = usage("""{"type":"usage","claude":{"fiveHour":{"pct":10,"resetsAt":0},"sevenDay":{"pct":20,"resetsAt":9},"resetCredits":500,"plan":"<b>pro\n max</b>"}}""")
+ assertNull(u.claude!!.fiveHour)
+ assertEquals(PlanWindow(20, 9), u.claude!!.sevenDay)
+ assertNull(u.claude!!.resetCredits)
+ assertEquals("bpro maxb", u.claude!!.plan)
+ }
+
+ @Test fun theHelloAsksForUsage() {
+ assertTrue(Protocol.CAP_USAGE in Protocol.CAPABILITIES)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/ReconnectPolicyTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/ReconnectPolicyTest.kt
new file mode 100644
index 00000000..8788aa4a
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/ReconnectPolicyTest.kt
@@ -0,0 +1,36 @@
+package com.coucou.android.link
+
+import com.coucou.android.link.ReconnectPolicy.Action
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class ReconnectPolicyTest {
+ private fun d(e: Wake, paired: Boolean = true, connected: Boolean = false, wifi: Boolean = true, relay: Boolean = false) =
+ ReconnectPolicy.decide(e, paired, connected, wifi, relay)
+
+ @Test fun nothingHappensWithoutAPairing() {
+ for (e in Wake.values()) assertEquals(Action.NONE, d(e, paired = false))
+ }
+
+ @Test fun whenConnectedEveryWakeUpAsksForAPongInsteadOfTrustingTheSocket() {
+ for (e in listOf(Wake.SCREEN_ON, Wake.NEW_NETWORK, Wake.ALARM)) assertEquals("$e", Action.CHECK_NOW, d(e, connected = true))
+ }
+
+ @Test fun whenNotConnectedThoseWakeUpsReconnectAtOnce() {
+ for (e in listOf(Wake.SCREEN_ON, Wake.NEW_NETWORK, Wake.ALARM)) assertEquals("$e", Action.RETRY_NOW, d(e, connected = false))
+ }
+
+ @Test fun withoutAUsableNetworkTheNetworkAndAlarmWakeUpsDoNotBurnBatteryButTheScreenStillTries() {
+ assertEquals(Action.NONE, d(Wake.NEW_NETWORK, wifi = false))
+ assertEquals(Action.NONE, d(Wake.ALARM, wifi = false))
+ assertEquals("a relay works over mobile data", Action.RETRY_NOW, d(Wake.NEW_NETWORK, wifi = false, relay = true))
+ assertEquals("the user just woke the phone: try", Action.RETRY_NOW, d(Wake.SCREEN_ON, wifi = false))
+ }
+
+ @Test fun losingTheNetworkOrTurningTheScreenOffNeedsNothing() {
+ for (connected in listOf(true, false)) {
+ assertEquals(Action.NONE, d(Wake.NETWORK_LOST, connected = connected))
+ assertEquals(Action.NONE, d(Wake.SCREEN_OFF, connected = connected))
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayConnectorTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayConnectorTest.kt
new file mode 100644
index 00000000..79f3b100
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayConnectorTest.kt
@@ -0,0 +1,373 @@
+package com.coucou.android.link
+
+import java.io.ByteArrayOutputStream
+import java.io.EOFException
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.Socket
+import java.net.SocketTimeoutException
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+
+/**
+ * The relay connector against an in-memory stand-in for the relay + the computer: it speaks the WebSocket upgrade, plays
+ * the computer's side of the end-to-end handshake with the same key, and lets each test misbehave in one way.
+ */
+class RelayConnectorTest {
+ private val roomId = RelayCrypto.base64UrlEncode(ByteArray(16) { 5 })
+ private val keyBytes = ByteArray(32) { 6 }
+ private val accessKey = RelayCrypto.base64UrlEncode(ByteArray(32) { 7 })
+ private val hostKey = RelayCrypto.PairingKey(keyBytes)
+ private val pairing = RelayPairing("ws://127.0.0.1:8787", roomId, RelayCrypto.base64UrlEncode(keyBytes), accessKey)
+
+ /** One direction of a connection: bytes put in come out in order; reads honour a timeout; a closed pipe ends reads and breaks writes. */
+ private class Pipe {
+ private val q = LinkedBlockingQueue<ByteArray>()
+ private val end = ByteArray(0)
+ @Volatile var timeoutMs = 0
+ @Volatile private var closed = false
+ private var current = end
+ private var at = 0
+ private var finished = false
+
+ val out = object : OutputStream() {
+ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
+ override fun write(b: ByteArray, off: Int, len: Int) {
+ if (closed) throw IOException("Broken pipe")
+ q.put(b.copyOfRange(off, off + len))
+ }
+ }
+
+ val input = object : InputStream() {
+ override fun read(): Int {
+ val one = ByteArray(1)
+ return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xFF
+ }
+
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ if (len == 0) return 0
+ if (finished) return -1
+ if (at >= current.size) {
+ val next = if (timeoutMs > 0) q.poll(timeoutMs.toLong(), TimeUnit.MILLISECONDS) ?: throw SocketTimeoutException("timeout") else q.take()
+ if (next === end) { finished = true; return -1 }
+ current = next
+ at = 0
+ }
+ val n = minOf(len, current.size - at)
+ System.arraycopy(current, at, b, off, n)
+ at += n
+ return n
+ }
+ }
+
+ fun close() {
+ closed = true
+ q.put(end)
+ }
+ }
+
+ /** The phone's socket: it writes into [toRelay] and reads from [fromRelay]. */
+ private class PipeSocket(val toRelay: Pipe, val fromRelay: Pipe) : Socket() {
+ @Volatile private var closed = false
+ override fun getInputStream(): InputStream = fromRelay.input
+ override fun getOutputStream(): OutputStream = toRelay.out
+ override fun setSoTimeout(timeout: Int) { fromRelay.timeoutMs = timeout }
+ override fun setTcpNoDelay(on: Boolean) {}
+ override fun isClosed() = closed
+ override fun close() { closed = true; toRelay.close(); fromRelay.close() }
+ }
+
+ private enum class Mode { NORMAL, REFUSE_401, CLOSE_JOIN_PROOF, SILENT, WRONG_ACCEPT_FIRST, FAKE_COMPUTER }
+
+ /** The relay (upgrade, frames) and the computer (end-to-end handshake) in one thread. */
+ private inner class Fake(val mode: Mode = Mode.NORMAL) {
+ private val toClient = Pipe()
+ private val fromClient = Pipe()
+ val socket = PipeSocket(fromClient, toClient)
+ val headers = CopyOnWriteArrayList<String>()
+ val inits = CopyOnWriteArrayList<ByteArray>()
+ val lines = LinkedBlockingQueue<String>()
+ @Volatile var session: RelayCrypto.Session? = null
+ @Volatile var closedByClient = false
+ private val ready = CountDownLatch(1)
+ private val writeLock = Any()
+
+ init {
+ Thread({ run() }, "fake-relay").apply { isDaemon = true; start() }
+ }
+
+ private fun readHeaders(): String {
+ val b = ByteArrayOutputStream()
+ var last = 0
+ while (true) {
+ val x = fromClient.input.read()
+ if (x < 0) throw EOFException()
+ b.write(x)
+ last = (last shl 8) or x
+ if (last == 0x0D0A0D0A) return b.toString("ISO-8859-1")
+ }
+ }
+
+ private fun write(bytes: ByteArray) = synchronized(writeLock) { toClient.out.write(bytes) }
+
+ fun serverFrame(opcode: Int, payload: ByteArray, fin: Boolean = true): ByteArray {
+ val out = ByteArrayOutputStream()
+ out.write((if (fin) 0x80 else 0) or opcode)
+ if (payload.size < 126) out.write(payload.size) else { out.write(126); out.write(payload.size ushr 8); out.write(payload.size and 0xFF) }
+ out.write(payload)
+ return out.toByteArray()
+ }
+
+ fun sendBinary(b: ByteArray) = write(serverFrame(WsOpcode.BINARY, b))
+ fun sendText(t: String) = write(serverFrame(WsOpcode.TEXT, t.toByteArray()))
+ fun sendClose(code: Int, reason: String) = write(serverFrame(WsOpcode.CLOSE, WsFrames.closePayload(code, reason)))
+ fun sendLine(json: String) = sendBinary(session!!.seal(json.toByteArray()))
+ fun awaitSession(): RelayCrypto.Session { ready.await(5, TimeUnit.SECONDS); return session!! }
+
+ private fun readClientFrame(): Pair<Int, ByteArray> {
+ val b0 = fromClient.input.read(); val b1 = fromClient.input.read()
+ if (b0 < 0 || b1 < 0) throw EOFException()
+ assertTrue("a client frame is masked", b1 and 0x80 != 0)
+ var len = b1 and 0x7F
+ if (len == 126) len = (fromClient.input.read() shl 8) or fromClient.input.read()
+ val mask = ByteArray(4) { fromClient.input.read().toByte() }
+ val payload = ByteArray(len)
+ var got = 0
+ while (got < len) { val r = fromClient.input.read(payload, got, len - got); if (r < 0) throw EOFException(); got += r }
+ for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i and 3].toInt()).toByte()
+ return (b0 and 0x0F) to payload
+ }
+
+ private fun run() {
+ try {
+ val head = readHeaders()
+ headers += head.split("\r\n")
+ if (mode == Mode.REFUSE_401) { write("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".toByteArray()); return }
+ val key = head.lines().first { it.startsWith("Sec-WebSocket-Key:") }.substringAfter(":").trim()
+ write(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${WsHandshake.acceptFor(key)}\r\nSec-WebSocket-Protocol: coucou.v1\r\n\r\n").toByteArray())
+ if (mode == Mode.CLOSE_JOIN_PROOF) { sendClose(1008, "join proof"); return }
+ var wrongSent = false
+ while (true) {
+ val (op, payload) = readClientFrame()
+ when (op) {
+ WsOpcode.CLOSE -> { closedByClient = true; return }
+ WsOpcode.BINARY -> if (payload.size > 1 && payload[1].toInt() == RelayCrypto.T_INIT) {
+ inits += payload
+ if (mode == Mode.SILENT) continue
+ if (mode == Mode.FAKE_COMPUTER) {
+ // Someone without K: a well-formed accept frame with a made-up nonce and MAC.
+ val junk = ByteArray(48).also { java.security.SecureRandom().nextBytes(it) }
+ sendBinary(byteArrayOf(RelayCrypto.VER.toByte(), RelayCrypto.T_ACCEPT.toByte(), 0, 0, 0, 0, 0, 0, 0, 0) + junk)
+ continue
+ }
+ if (mode == Mode.WRONG_ACCEPT_FIRST && !wrongSent) {
+ wrongSent = true
+ // An accept that answers some other init (a recorded one): the phone must ignore it.
+ val other = RelayCrypto.initFrame(hostKey, roomId, RelayCrypto.freshNonce())
+ sendBinary(RelayCrypto.acceptInit(hostKey, roomId, other, RelayCrypto.freshNonce()).first)
+ }
+ val (accept, s) = RelayCrypto.acceptInit(hostKey, roomId, payload, RelayCrypto.freshNonce())
+ session = s
+ sendBinary(accept)
+ ready.countDown()
+ } else {
+ lines.put(String(session!!.open(payload)))
+ }
+ }
+ }
+ } catch (_: IOException) {
+ }
+ }
+ }
+
+ private fun connectorFor(f: Fake, answerMs: Int = 5_000, resendMs: Int = 4_000) =
+ RelayConnector(pairing, sockets = { _, _ -> f.socket }, answerTimeoutMs = answerMs, resendMs = resendMs)
+
+ private fun readLine(s: Socket): String? {
+ val b = ByteArrayOutputStream()
+ while (true) {
+ val x = s.getInputStream().read()
+ if (x < 0) return null
+ if (x == '\n'.code) return b.toString("UTF-8")
+ b.write(x)
+ }
+ }
+
+ // ── the upgrade ──
+
+ @Test fun theUpgradePresentsTheAccessKeyTheJoinProofAndTheRoom() {
+ val f = Fake()
+ connectorFor(f).connect(2_000).close()
+ val head = f.headers.joinToString("\n")
+ assertTrue(head, f.headers[0] == "GET /v1/room/$roomId?role=phone HTTP/1.1")
+ assertTrue(f.headers.contains("Authorization: Bearer $accessKey"))
+ assertTrue(f.headers.contains("Sec-WebSocket-Protocol: coucou.v1, coucou.join.${RelayCrypto.joinProof(hostKey)}"))
+ assertFalse("K itself is never sent", head.contains(pairing.key))
+ }
+
+ @Test fun theAccessKeyBeingRefusedIsReportedAsSuch() {
+ val f = Fake(Mode.REFUSE_401)
+ val c = connectorFor(f)
+ try { c.connect(2_000); fail() } catch (e: WsHandshakeException) { assertEquals(401, e.status) }
+ assertEquals(RelayIssue.ACCESS_REFUSED, c.issue)
+ }
+
+ @Test fun aRoomHeldBySomeoneElseIsReportedAsSuch() {
+ val f = Fake(Mode.CLOSE_JOIN_PROOF)
+ val c = connectorFor(f)
+ try { c.connect(2_000); fail() } catch (_: IOException) {}
+ assertEquals(RelayIssue.ROOM_TAKEN, c.issue)
+ }
+
+ @Test fun aComputerThatNeverAnswersIsAGiveUpAndInitIsAskedAgain() {
+ val f = Fake(Mode.SILENT)
+ val c = connectorFor(f, answerMs = 700, resendMs = 150)
+ try { c.connect(2_000); fail() } catch (_: IOException) {}
+ assertEquals(RelayIssue.COMPUTER_AWAY, c.issue)
+ Thread.sleep(200) // the stand-in reads the last frames on its own thread
+ val sent = f.inits.toList()
+ assertTrue("init was sent again with a fresh nonce", sent.size >= 3)
+ assertEquals("every init uses its own nonce", sent.size, sent.map { it.copyOfRange(10, 26).toList() }.toSet().size)
+ }
+
+ @Test fun aFakeComputerWithoutTheKeyIsNeverTrusted() {
+ val f = Fake(Mode.FAKE_COMPUTER)
+ val c = connectorFor(f, answerMs = 600, resendMs = 150)
+ try { c.connect(2_000); fail("a made-up accept was accepted") } catch (_: IOException) {}
+ assertEquals(RelayIssue.COMPUTER_AWAY, c.issue)
+ }
+
+ @Test fun anAcceptThatAnswersAnOtherInitIsIgnored() {
+ val f = Fake(Mode.WRONG_ACCEPT_FIRST)
+ val s = connectorFor(f).connect(2_000)
+ s.getOutputStream().write("{\"type\":\"ping\"}\n".toByteArray())
+ assertEquals("{\"type\":\"ping\"}", f.lines.poll(5, TimeUnit.SECONDS))
+ s.close()
+ }
+
+ // ── the conversation ──
+
+ @Test fun linesGoBothWaysEncryptedAndInOrder() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ val out = s.getOutputStream()
+ out.write("{\"type\":\"hello\"}\n".toByteArray())
+ out.write("{\"type\":\"ping\"}\n{\"type\":\"ping\"}\n".toByteArray())
+ assertEquals("{\"type\":\"hello\"}", f.lines.poll(5, TimeUnit.SECONDS))
+ assertEquals("{\"type\":\"ping\"}", f.lines.poll(5, TimeUnit.SECONDS))
+ assertEquals("{\"type\":\"ping\"}", f.lines.poll(5, TimeUnit.SECONDS))
+ f.awaitSession()
+ f.sendLine("{\"type\":\"welcome\"}")
+ f.sendLine("{\"type\":\"pong\"}")
+ assertEquals("{\"type\":\"welcome\"}", readLine(s))
+ assertEquals("{\"type\":\"pong\"}", readLine(s))
+ s.close()
+ assertTrue(s.isClosed)
+ }
+
+ @Test fun aLineOverTheLimitCannotBeSent() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ try { s.getOutputStream().write(ByteArray(RelayCrypto.MAX_LINE + 10) { 'a'.code.toByte() }); fail() } catch (_: IOException) {}
+ s.close()
+ }
+
+ @Test fun aSilentLinkTimesOutLikeASocketWould() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ s.soTimeout = 150
+ try { s.getInputStream().read(); fail() } catch (_: SocketTimeoutException) {}
+ s.close()
+ }
+
+ @Test fun aTamperedReplayedOrReorderedFrameEndsTheStream() {
+ for (what in listOf("flip", "replay", "gap")) {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ val host = f.awaitSession()
+ val first = host.seal("{\"n\":1}".toByteArray())
+ when (what) {
+ "flip" -> f.sendBinary(first.copyOf().also { it[it.size - 1] = (it[it.size - 1].toInt() xor 1).toByte() })
+ "replay" -> { f.sendBinary(first); f.sendBinary(first) }
+ "gap" -> { host.seal("{\"n\":2}".toByteArray()); f.sendBinary(host.seal("{\"n\":3}".toByteArray())) }
+ }
+ val got = mutableListOf<String?>()
+ var line = readLine(s)
+ while (line != null) { got += line; line = readLine(s) }
+ assertTrue("$what: the stream ended", true)
+ assertTrue("$what: at most the first line got through", got.size <= 1)
+ assertTrue(got.all { it == "{\"n\":1}" })
+ s.close()
+ }
+ }
+
+ @Test fun theComputerLeavingEndsTheStream() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ f.awaitSession()
+ f.sendText("""{"peer":"offline"}""")
+ assertEquals(null, readLine(s))
+ s.close()
+ }
+
+ @Test fun aCloseFromTheRelayEndsTheStream() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ f.sendClose(1008, "access key changed")
+ assertEquals(null, readLine(s))
+ }
+
+ @Test fun closingTellsTheRelayAndNothingMoreCanBeSent() {
+ val f = Fake()
+ val s = connectorFor(f).connect(2_000)
+ s.close()
+ val deadline = System.currentTimeMillis() + 3_000
+ while (!f.closedByClient && System.currentTimeMillis() < deadline) Thread.sleep(10)
+ assertTrue(f.closedByClient)
+ try { s.getOutputStream().write("x\n".toByteArray()); fail() } catch (_: IOException) {}
+ }
+
+ // ── the unchanged LinkClient on top ──
+
+ @Test fun theLinkClientRunsTheUsualConversationThroughTheRelay() {
+ val f = Fake()
+ val welcome = CountDownLatch(1)
+ val approval = LinkedBlockingQueue<ApprovalRequest>()
+ val listener = object : LinkListener {
+ override fun onWelcome(desktopName: String, os: String) { assertEquals("Test PC", desktopName); welcome.countDown() }
+ override fun onApproval(request: ApprovalRequest) { approval.put(request) }
+ }
+ val payload = PairingPayload("192.0.2.1", 1, "ab".repeat(32), "tok_en-1234567890abcd", "PC", pairing)
+ val client = LinkClient(payload, "Phone", listener, connector = connectorFor(f), caps = emptyList())
+ client.start()
+ try {
+ val hello = JSONObject(f.lines.poll(5, TimeUnit.SECONDS))
+ assertEquals("hello", hello.getString("type"))
+ assertEquals("tok_en-1234567890abcd", hello.getString("token"))
+ f.sendLine("""{"type":"welcome","v":1,"desktop":"Test PC","os":"linux"}""")
+ assertTrue(welcome.await(5, TimeUnit.SECONDS))
+ val fp = "cd".repeat(32)
+ f.sendLine("""{"type":"approval","pillId":"integration_claude","tool":"Bash","command":"ls","fingerprint":"$fp","createdAt":${System.currentTimeMillis()}}""")
+ val req = approval.poll(5, TimeUnit.SECONDS)
+ assertNotNull(req)
+ assertTrue(client.decide(fp, true))
+ val decision = JSONObject(f.lines.poll(5, TimeUnit.SECONDS))
+ assertEquals("decision", decision.getString("type"))
+ assertEquals(fp, decision.getString("fingerprint"))
+ assertEquals("allow", decision.getString("decision"))
+ } finally {
+ client.stop()
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayCryptoTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayCryptoTest.kt
new file mode 100644
index 00000000..3af63bd7
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayCryptoTest.kt
@@ -0,0 +1,254 @@
+package com.coucou.android.link
+
+import com.coucou.android.link.RelayCrypto.ChannelException
+import com.coucou.android.link.RelayCrypto.Dir
+import com.coucou.android.link.RelayCrypto.Failure
+import java.io.File
+import org.json.JSONObject
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The same checks as the Rust twin, against the same android/relay/test-vectors.json. */
+class RelayCryptoTest {
+ private val v = JSONObject(File("../relay/test-vectors.json").readText())
+ private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
+ private fun ByteArray.hex() = joinToString("") { "%02x".format(it) }
+ private fun text(vararg path: String): String {
+ var o = v
+ for (p in path.dropLast(1)) o = o.getJSONObject(p)
+ return o.getString(path.last())
+ }
+ private val k = RelayCrypto.PairingKey(hex(text("inputs", "key")))
+ private val room = text("inputs", "room")
+ private val nPhone = hex(text("inputs", "nPhone"))
+ private val nPc = hex(text("inputs", "nPc"))
+ private fun dir(s: String) = if (s == "p2h") Dir.PHONE_TO_HOST else Dir.HOST_TO_PHONE
+ private fun failure(block: () -> Unit): Failure? = try { block(); null } catch (e: ChannelException) { e.failure }
+
+ /** The session that RECEIVES frames sent in direction [d], built from the vectors' handshake. */
+ private fun receiverOf(d: Dir, key: RelayCrypto.PairingKey = k, roomText: String = room): RelayCrypto.Session {
+ val init = RelayCrypto.initFrame(key, roomText, nPhone)
+ val (accept, host) = RelayCrypto.acceptInit(key, roomText, init, nPc)
+ return if (d == Dir.PHONE_TO_HOST) host else RelayCrypto.finishHandshake(key, roomText, nPhone, accept)
+ }
+
+ @Test fun hkdfMatchesRfc5869A1() {
+ val r = v.getJSONObject("rfc5869_a1")
+ assertEquals(r.getString("okm"), RelayCrypto.hkdf(hex(r.getString("ikm")), hex(r.getString("salt")), hex(r.getString("info")), r.getInt("length")).hex())
+ }
+
+ @Test fun derivedKeysMatchTheVectors() {
+ assertEquals(text("derived", "kAuth"), RelayCrypto.kAuth(k).bytes.hex())
+ assertEquals(text("derived", "kJoin"), RelayCrypto.kJoin(k).bytes.hex())
+ val (p2h, h2p) = RelayCrypto.sessionKeys(k, nPhone, nPc)
+ assertEquals(text("derived", "kP2H"), p2h.bytes.hex())
+ assertEquals(text("derived", "kH2P"), h2p.bytes.hex())
+ assertEquals(43, RelayCrypto.joinProof(k).length)
+ assertEquals(RelayCrypto.base64UrlEncode(RelayCrypto.kJoin(k).bytes), RelayCrypto.joinProof(k))
+ }
+
+ @Test fun theHandshakeFramesMatchTheVectorsAndTheTwoSidesAgree() {
+ val init = RelayCrypto.initFrame(k, room, nPhone)
+ assertEquals(text("init", "frame"), init.hex())
+ val (accept, host) = RelayCrypto.acceptInit(k, room, init, nPc)
+ assertEquals(text("accept", "frame"), accept.hex())
+ val phone = RelayCrypto.finishHandshake(k, room, nPhone, accept)
+ val a = phone.seal("""{"type":"hello"}""".toByteArray())
+ assertArrayEquals("""{"type":"hello"}""".toByteArray(), host.open(a))
+ val b = host.seal("""{"type":"welcome"}""".toByteArray())
+ assertArrayEquals("""{"type":"welcome"}""".toByteArray(), phone.open(b))
+ }
+
+ @Test fun aWrongKeyRoomOrStaleAcceptIsRefused() {
+ val init = RelayCrypto.initFrame(k, room, nPhone)
+ val other = RelayCrypto.PairingKey(ByteArray(32) { 9 })
+ assertEquals(Failure.BAD_TAG, failure { RelayCrypto.acceptInit(other, room, init, nPc) })
+ assertEquals(Failure.BAD_TAG, failure { RelayCrypto.acceptInit(k, "AAAAAAAAAAAAAAAAAAAAAA", init, nPc) })
+ val (accept, _) = RelayCrypto.acceptInit(k, room, init, nPc)
+ assertEquals("a recorded accept must not answer a newer init", Failure.BAD_TAG, failure { RelayCrypto.finishHandshake(k, room, ByteArray(16) { 7 }, accept) })
+ assertEquals(Failure.BAD_HEADER, failure { RelayCrypto.finishHandshake(k, room, nPhone, init) })
+ assertEquals(Failure.BAD_HEADER, failure { RelayCrypto.acceptInit(k, room, accept, nPc) })
+ assertEquals(Failure.BAD_HEADER, failure { RelayCrypto.acceptInit(k, room, init.copyOf(40), nPc) })
+ val flipped = init.copyOf().also { it[12] = (it[12].toInt() xor 1).toByte() }
+ assertEquals(Failure.BAD_TAG, failure { RelayCrypto.acceptInit(k, room, flipped, nPc) })
+ }
+
+ @Test fun dataFramesReproduceTheVectorsByteForByteAndOpenBack() {
+ val (p2h, h2p) = RelayCrypto.sessionKeys(k, nPhone, nPc)
+ val cases = v.getJSONArray("data")
+ for (i in 0 until cases.length()) {
+ val c = cases.getJSONObject(i)
+ val d = dir(c.getString("dir"))
+ val key = if (d == Dir.PHONE_TO_HOST) p2h else h2p
+ val counter = c.getLong("counter")
+ val line = c.getString("line").toByteArray()
+ assertEquals(c.getString("nonce"), RelayCrypto.nonceFor(d, counter).hex())
+ assertEquals(c.getString("plaintext"), RelayCrypto.pad(line).hex())
+ val sealed = RelayCrypto.sealWith(key.bytes, room, d, counter, line)
+ assertEquals("$d $counter", c.getString("frame"), sealed.hex())
+ assertArrayEquals(line, RelayCrypto.openWith(key.bytes, room, d, sealed))
+ }
+ }
+
+ @Test fun framesThatMustBeRefusedAreRefusedWithTheListedReason() {
+ val list = v.getJSONArray("mustRefuse")
+ for (i in 0 until list.length()) {
+ val n = list.getJSONObject(i)
+ val d = dir(n.getString("dir"))
+ val key = if (n.has("key")) RelayCrypto.PairingKey(hex(n.getString("key"))) else k
+ val rx = receiverOf(d, key, if (n.has("room")) n.getString("room") else room)
+ val name = n.getString("name")
+ val expected = if (name == "the counter in the header changed") Failure.BAD_COUNTER // refused by the counter rule first
+ else if (n.getString("expect") == "bad_tag") Failure.BAD_TAG else Failure.BAD_HEADER
+ val frame = hex(n.getString("frame"))
+ assertEquals(name, expected, failure { rx.open(frame) })
+ assertEquals("$name: the session is dead after a fault", Failure.FAULTED, failure { rx.open(frame) })
+ }
+ }
+
+ @Test fun counterSequencesFollowTheRule() {
+ val (p2h, _) = RelayCrypto.sessionKeys(k, nPhone, nPc)
+ val list = v.getJSONArray("mustRefuseInOrder")
+ for (i in 0 until list.length()) {
+ val s = list.getJSONObject(i)
+ val rx = receiverOf(Dir.PHONE_TO_HOST)
+ val counters = s.getJSONArray("counters")
+ val want = s.getJSONArray("accepted")
+ val got = (0 until counters.length()).map {
+ val frame = RelayCrypto.sealWith(p2h.bytes, room, Dir.PHONE_TO_HOST, counters.getLong(it), """{"type":"ping"}""".toByteArray())
+ failure { rx.open(frame) } == null
+ }
+ assertEquals(s.getString("name"), (0 until want.length()).map { want.getBoolean(it) }, got)
+ }
+ }
+
+ @Test fun noKeyAndNoncePairRepeatsAcrossBothDirectionsAndTwoSessions() {
+ val seen = HashSet<String>()
+ val key = RelayCrypto.PairingKey(ByteArray(32) { 3 })
+ for ((np, nh) in listOf(ByteArray(16) { 1 } to ByteArray(16) { 2 }, ByteArray(16) { 5 } to ByteArray(16) { 6 })) {
+ val (p2h, h2p) = RelayCrypto.sessionKeys(key, np, nh)
+ assertFalse("the directions share a key", p2h.bytes.contentEquals(h2p.bytes))
+ for (c in 0L until 3000L) {
+ assertTrue("p2h $c", seen.add(p2h.bytes.hex() + ":" + RelayCrypto.nonceFor(Dir.PHONE_TO_HOST, c).hex()))
+ assertTrue("h2p $c", seen.add(h2p.bytes.hex() + ":" + RelayCrypto.nonceFor(Dir.HOST_TO_PHONE, c).hex()))
+ }
+ }
+ assertEquals(2 * 2 * 3000, seen.size)
+ assertFalse(RelayCrypto.nonceFor(Dir.PHONE_TO_HOST, 5).contentEquals(RelayCrypto.nonceFor(Dir.HOST_TO_PHONE, 5)))
+ }
+
+ @Test fun theSessionsThemselvesReproduceTheVectorFramesInEachDirection() {
+ val phone = receiverOf(Dir.HOST_TO_PHONE)
+ val host = receiverOf(Dir.PHONE_TO_HOST)
+ var checked = 0
+ val cases = v.getJSONArray("data")
+ for (i in 0 until cases.length()) {
+ val c = cases.getJSONObject(i)
+ val d = dir(c.getString("dir"))
+ if (c.getLong("counter") > 2) continue
+ val (sender, receiver) = if (d == Dir.PHONE_TO_HOST) phone to host else host to phone
+ val frame = sender.seal(c.getString("line").toByteArray())
+ assertEquals(c.getString("frame"), frame.hex())
+ assertArrayEquals(c.getString("line").toByteArray(), receiver.open(frame))
+ checked++
+ }
+ assertEquals(5, checked)
+ assertFalse("a session must not send and receive under one key", phone.sendKey.bytes.contentEquals(phone.recvKey.bytes))
+ assertFalse(host.sendKey.bytes.contentEquals(host.recvKey.bytes))
+ assertArrayEquals(phone.sendKey.bytes, host.recvKey.bytes)
+ assertArrayEquals(host.sendKey.bytes, phone.recvKey.bytes)
+ }
+
+ @Test fun aSessionSendsCountersInOrderAndNeverReusesOne() {
+ val host = receiverOf(Dir.PHONE_TO_HOST)
+ val counters = (0 until 500).map { java.nio.ByteBuffer.wrap(host.seal("{}".toByteArray()), 2, 8).long }
+ assertEquals((0L until 500L).toList(), counters)
+ }
+
+ @Test fun aSenderAtTheLastCounterSendsItOnceAndThenRefuses() {
+ val host = receiverOf(Dir.PHONE_TO_HOST)
+ host.forceSendCounterForTest(RelayCrypto.LAST_COUNTER - 1)
+ host.seal("{}".toByteArray())
+ val last = host.seal("{}".toByteArray())
+ assertEquals(RelayCrypto.LAST_COUNTER, java.nio.ByteBuffer.wrap(last, 2, 8).long)
+ assertEquals(Failure.EXHAUSTED, failure { host.seal("{}".toByteArray()) })
+ assertEquals(Failure.EXHAUSTED, failure { host.seal("{}".toByteArray()) })
+ }
+
+ @Test fun aReceiverRefusesACounterPastTheLastOne() {
+ val (p2h, _) = RelayCrypto.sessionKeys(k, nPhone, nPc)
+ val rx = receiverOf(Dir.PHONE_TO_HOST)
+ val beyond = RelayCrypto.sealWith(p2h.bytes, room, Dir.PHONE_TO_HOST, RelayCrypto.LAST_COUNTER + 1, "{}".toByteArray())
+ assertEquals(Failure.BAD_COUNTER, failure { rx.open(beyond) })
+ }
+
+ @Test fun linesPadToBlocksAndTheSizeLimitHolds() {
+ assertEquals(128, RelayCrypto.pad(ByteArray(0)).size)
+ assertEquals(128, RelayCrypto.pad(ByteArray(124)).size)
+ assertEquals(256, RelayCrypto.pad(ByteArray(125)).size)
+ val tx = receiverOf(Dir.PHONE_TO_HOST)
+ val rx = receiverOf(Dir.HOST_TO_PHONE)
+ val biggest = ByteArray(RelayCrypto.MAX_LINE) { 'x'.code.toByte() }
+ val frame = tx.seal(biggest)
+ assertTrue("${frame.size} bytes", frame.size <= RelayCrypto.MAX_FRAME)
+ assertArrayEquals(biggest, rx.open(frame))
+ assertEquals(Failure.TOO_LONG, failure { tx.seal(ByteArray(RelayCrypto.MAX_LINE + 1)) })
+ assertEquals(Failure.TOO_LONG, failure { rx.open(ByteArray(RelayCrypto.MAX_FRAME + 1)) })
+ }
+
+ @Test fun aFrameWithBadPaddingIsRefusedEvenWithAValidTag() {
+ val (p2h, _) = RelayCrypto.sessionKeys(k, nPhone, nPc)
+ val shapes = listOf(
+ ByteArray(100),
+ RelayCrypto.pad("{}".toByteArray()).also { it[100] = 1 },
+ RelayCrypto.pad("{}".toByteArray()).also { java.nio.ByteBuffer.wrap(it).putInt(200) },
+ )
+ for (plain in shapes) {
+ val h = java.nio.ByteBuffer.allocate(10).put(1).put(3).putLong(0).array()
+ val aad = (RelayCrypto.LABEL.toByteArray() + room.toByteArray() + byteArrayOf(1) + h)
+ val c = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(javax.crypto.Cipher.ENCRYPT_MODE, javax.crypto.spec.SecretKeySpec(p2h.bytes, "AES"), javax.crypto.spec.GCMParameterSpec(128, RelayCrypto.nonceFor(Dir.PHONE_TO_HOST, 0)))
+ c.updateAAD(aad)
+ val frame = h + c.doFinal(plain)
+ assertEquals(Failure.BAD_PADDING, failure { receiverOf(Dir.PHONE_TO_HOST).open(frame) })
+ }
+ }
+
+ @Test fun base64UrlRoundTripsAndIsStrict() {
+ for (len in 0 until 40) {
+ val bytes = ByteArray(len) { (it * 37).toByte() }
+ assertArrayEquals("$len", bytes, RelayCrypto.base64UrlDecode(RelayCrypto.base64UrlEncode(bytes)))
+ }
+ assertEquals(text("inputs", "room"), RelayCrypto.base64UrlEncode(hex(text("inputs", "roomBytes"))))
+ assertEquals("-_8", RelayCrypto.base64UrlEncode(byteArrayOf(0xfb.toByte(), 0xff.toByte())))
+ for (bad in listOf("A", "AAAAA", "AA=A", "A+AA", "A/AA", "AB", "AAB", "a b ")) assertNull(bad, RelayCrypto.base64UrlDecode(bad))
+ assertNotNull(RelayCrypto.PairingKey.fromBase64Url(RelayCrypto.base64UrlEncode(ByteArray(32) { 1 })))
+ assertNull(RelayCrypto.PairingKey.fromBase64Url(RelayCrypto.base64UrlEncode(ByteArray(31) { 1 })))
+ }
+
+ @Test fun secretsNeverPrintAndTheModuleNeverLogs() {
+ val key = RelayCrypto.PairingKey(ByteArray(32) { 0xab.toByte() })
+ val shown = "$key ${RelayCrypto.kAuth(key)} ${receiverOf(Dir.PHONE_TO_HOST)}"
+ assertFalse(shown, shown.contains("ab") || shown.contains("171"))
+ assertEquals("Session(..)", receiverOf(Dir.PHONE_TO_HOST).toString())
+ val src = File("src/main/kotlin/com/coucou/android/link/RelayCrypto.kt").readText()
+ for (bad in listOf("Log.", "println", "System.out", "System.err", "printStackTrace", "File(", "FileOutputStream", "SharedPreferences", "Timber")) {
+ assertFalse("RelayCrypto.kt uses $bad", src.contains(bad))
+ }
+ assertNotEquals("", src)
+ }
+
+ @Test fun wipingASessionKillsIt() {
+ val s = receiverOf(Dir.PHONE_TO_HOST)
+ val key = s.sendKey.bytes
+ s.wipe()
+ assertTrue(key.all { it == 0.toByte() })
+ assertEquals(Failure.FAULTED, failure { s.seal("{}".toByteArray()) })
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayE2ETest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayE2ETest.kt
new file mode 100644
index 00000000..96ba8ea0
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayE2ETest.kt
@@ -0,0 +1,62 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/**
+ * The phone's half of the end-to-end check. The computer's half is the Rust test `e2e_the_computer_side_for_the_phone_test`,
+ * and between them is a real relay (the Cloudflare Worker under `wrangler dev`, or the Node twin). Both halves use the same
+ * fixed credentials. Run by android/relay/tools/e2e.sh; skipped everywhere else (it needs COUCOU_E2E_RELAY_URL).
+ */
+class RelayE2ETest {
+ private val url = System.getenv("COUCOU_E2E_RELAY_URL")
+ private val room = RelayCrypto.base64UrlEncode(ByteArray(16) { 0x11 })
+ private val key = RelayCrypto.base64UrlEncode(ByteArray(32) { 0x22 })
+ private val access = RelayCrypto.base64UrlEncode(ByteArray(32) { 0x33 })
+
+ private fun pairing(accessKey: String = access) = RelayPairing(url, room, key, accessKey)
+
+ @Test fun aWrongAccessKeyIsRefusedByTheRealRelay() {
+ assumeTrue("needs COUCOU_E2E_RELAY_URL", url != null)
+ val c = RelayConnector(pairing(RelayCrypto.base64UrlEncode(ByteArray(32) { 0x44 })))
+ try { c.connect(5_000); fail() } catch (e: WsHandshakeException) { assertEquals(401, e.status) }
+ assertEquals(RelayIssue.ACCESS_REFUSED, c.issue)
+ }
+
+ @Test fun theRustComputerAndTheKotlinPhoneTalkThroughTheRealRelayAndAnApprovalIsDecided() {
+ assumeTrue("needs COUCOU_E2E_RELAY_URL", url != null)
+ val welcomed = CountDownLatch(1)
+ val approvals = LinkedBlockingQueue<ApprovalRequest>()
+ val resolved = LinkedBlockingQueue<String>()
+ val listener = object : LinkListener {
+ override fun onWelcome(desktopName: String, os: String) { assertEquals("E2E PC", desktopName); welcomed.countDown() }
+ override fun onApproval(request: ApprovalRequest) { approvals.put(request) }
+ override fun onApprovalResolved(fingerprint: String) { resolved.put(fingerprint) }
+ }
+ val payload = PairingPayload("192.0.2.1", 1, "ab".repeat(32), "e2e-token-0123456789abcdef", "E2E PC", pairing())
+ // The computer may start a little after the phone: the connector waits for it and the link retries.
+ val client = LinkClient(
+ payload, "Phone", listener, connector = RelayConnector(pairing(), answerTimeoutMs = 20_000),
+ backoffMs = longArrayOf(500, 1_000, 2_000), caps = Protocol.CAPABILITIES,
+ )
+ client.start()
+ try {
+ assertTrue("the computer's welcome arrived through the relay", welcomed.await(60, TimeUnit.SECONDS))
+ val request = approvals.poll(30, TimeUnit.SECONDS) ?: throw IOException("no approval")
+ assertEquals("Bash", request.tool)
+ assertEquals("echo end-to-end", request.command)
+ assertEquals(64, request.fingerprint.length)
+ assertTrue(client.decide(request.fingerprint, true))
+ assertEquals("the computer closed the approval after the decision", request.fingerprint, resolved.poll(30, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayGuardsTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayGuardsTest.kt
new file mode 100644
index 00000000..bc492b58
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayGuardsTest.kt
@@ -0,0 +1,43 @@
+package com.coucou.android.link
+
+import java.io.File
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Rules about the relay code that no behaviour test would notice breaking. */
+class RelayGuardsTest {
+ private fun main(path: String) = File("src/main/kotlin/com/coucou/android/$path").readText()
+
+ @Test fun theWebSocketRelayAndTransportCodeNeverLogOrPrint() {
+ for (f in listOf("link/WebSocket.kt", "link/RelayLink.kt", "link/Transport.kt", "link/RelayCrypto.kt")) {
+ val text = main(f)
+ for (bad in listOf("Log.", "println", "printStackTrace", "System.err", "System.out")) assertFalse("$f uses $bad", text.contains(bad))
+ }
+ }
+
+ @Test fun noLogLineInTheAppNamesARelaySecret() {
+ val model = main("app/AppModel.kt")
+ for (line in model.lines().filter { it.contains("Log.") }) {
+ for (secret in listOf(".access", ".key", ".room", "pairingKey", "relay.url")) assertFalse("a log line names $secret: $line", line.contains(secret))
+ }
+ }
+
+ @Test fun theWebSocketClientIsOurOwnWithNoNewLibrary() {
+ // Decision D2 of android/RELAY_PLAN.md: no WebSocket library; OkHttp stays the fallback if this client ever proves unreliable.
+ val gradle = File("build.gradle.kts").readText().lowercase()
+ for (lib in listOf("okhttp", "tyrus", "java-websocket", "scarlet", "ktor")) assertFalse("$lib was added", gradle.contains(lib))
+ }
+
+ @Test fun theRelayPairingKeepsItsSecretsOutOfToString() {
+ val r = RelayPairing("wss://relay.example.com", "R", "K", "A")
+ assertTrue(r.toString() == "RelayPairing(..)")
+ }
+
+ @Test fun theSecureStoreKeepsEverythingInsideTheEncryptedBlob() {
+ val store = main("app/SecureStore.kt")
+ // The pairing, relay fields included, goes through one encrypted preference and nothing else is written for it.
+ assertTrue(store.contains("PairingCodec.encode(p)"))
+ assertTrue(Regex("""putString\(""").findAll(store).count() == 1)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayLinkTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayLinkTest.kt
new file mode 100644
index 00000000..a2cc020c
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayLinkTest.kt
@@ -0,0 +1,142 @@
+package com.coucou.android.link
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The relay fields of a pairing link, how they are kept, and the relay's text hints. */
+class RelayLinkTest {
+ private val room = RelayCrypto.base64UrlEncode(ByteArray(16) { 1 })
+ private val key = RelayCrypto.base64UrlEncode(ByteArray(32) { 2 })
+ private val access = RelayCrypto.base64UrlEncode(ByteArray(32) { 3 })
+ private val fp = "ab".repeat(32)
+ private val lan = "coucou://pair?v=1&host=192.168.1.20&port=47821&fp=$fp&token=tok_en-1234567890abcd&name=PC"
+ private val withRelay = "$lan&relay=wss:%2F%2Frelay.example.workers.dev&room=$room&key=$key&access=$access"
+
+ @Test fun anOldLinkStillPairsOverTheLanOnly() {
+ val p = PairingPayload.parse(lan)!!
+ assertNull(p.relay)
+ assertEquals("192.168.1.20", p.host)
+ }
+
+ @Test fun aLinkWithTheRelayFieldsCarriesThemAll() {
+ val p = PairingPayload.parse(withRelay)!!
+ val r = p.relay!!
+ assertEquals("wss://relay.example.workers.dev", r.url)
+ assertEquals(room, r.room)
+ assertEquals(key, r.key)
+ assertEquals(access, r.access)
+ assertNotNull(r.pairingKey())
+ assertEquals("wss://relay.example.workers.dev", r.relayUrl()!!.display)
+ assertEquals(443, r.relayUrl()!!.port)
+ }
+
+ @Test fun thePortInTheAddressIsKept() {
+ val p = PairingPayload.parse(withRelay.replace("workers.dev", "workers.dev:8443"))!!
+ assertEquals(8443, p.relay!!.relayUrl()!!.port)
+ }
+
+ @Test fun someOfTheFieldsButNotAllIsADamagedLink() {
+ for (missing in listOf("relay", "room", "key", "access")) {
+ val link = withRelay.split("&").filterNot { it.startsWith("$missing=") }.joinToString("&")
+ assertNull("without $missing", PairingPayload.parse(link))
+ }
+ }
+
+ @Test fun aMalformedFieldMakesTheWholeLinkInvalid() {
+ val bad = mapOf(
+ "room too short" to withRelay.replace(room, room.dropLast(1)),
+ "room not base64url" to withRelay.replace(room, "!".repeat(22)),
+ "key too short" to withRelay.replace(key, key.dropLast(1)),
+ "key too long" to withRelay.replace(key, key + "A"),
+ "access too short" to withRelay.replace(access, access.dropLast(2)),
+ "access with padding" to withRelay.replace(access, access.dropLast(1) + "="),
+ "plain http" to withRelay.replace("wss:%2F%2F", "https:%2F%2F"),
+ "ws to another host" to withRelay.replace("wss:%2F%2Frelay.example.workers.dev", "ws:%2F%2Frelay.example.workers.dev"),
+ "credentials in the address" to withRelay.replace("wss:%2F%2F", "wss:%2F%2Fuser:pw%40"),
+ "a path in the address" to withRelay.replace("workers.dev", "workers.dev%2Fx"),
+ )
+ for ((name, link) in bad) assertNull(name, PairingPayload.parse(link))
+ }
+
+ @Test fun theLanPartIsUnchangedByTheRelayFields() {
+ val a = PairingPayload.parse(lan)!!
+ val b = PairingPayload.parse(withRelay)!!
+ assertEquals(a.copy(relay = null), b.copy(relay = null))
+ }
+
+ @Test fun aPairingNeverPrintsItsRelaySecrets() {
+ val p = PairingPayload.parse(withRelay)!!
+ val shown = p.relay.toString() + p.relay!!.pairingKey().toString()
+ for (secret in listOf(key, access, room)) assertFalse(shown.contains(secret))
+ assertFalse(p.toString().contains(key) || p.toString().contains(access) || p.toString().contains(room))
+ }
+
+ @Test fun theLongestRealisticLinkIsStillAccepted() {
+ val name = java.net.URLEncoder.encode("é".repeat(48), "UTF-8").replace("+", "%20")
+ val host = "${"a".repeat(63)}.${"b".repeat(63)}.workers.dev"
+ val link = "coucou://pair?v=1&host=2001:db8:aaaa:bbbb:cccc:dddd:eeee:ffff&port=47821&fp=$fp&token=${"t".repeat(128)}&name=$name" +
+ "&relay=wss:%2F%2F$host:8443&room=$room&key=$key&access=$access"
+ assertTrue("${link.length} characters", link.length < com.coucou.android.core.PairingScan.MAX_LINK)
+ assertTrue(com.coucou.android.core.PairingScan.decide(link) is com.coucou.android.core.ScanDecision.Pairing)
+ assertEquals(host, PairingPayload.parse(link)!!.relay!!.relayUrl()!!.host)
+ }
+
+ @Test fun theConfirmationShowsTheRelayHostBeforeAnythingIsStored() {
+ val dialog = java.io.File("src/main/kotlin/com/coucou/android/ui/PairConfirm.kt").readText()
+ assertTrue(dialog.contains("p.relay?.relayUrl()?.host"))
+ assertTrue(dialog.contains("R.string.pair_confirm_relay"))
+ }
+
+ @Test fun theHintsAreTheTwoExactMessages() {
+ assertEquals(RelayHints.Hint.ONLINE, RelayHints.parse("""{"peer":"online"}"""))
+ assertEquals(RelayHints.Hint.OFFLINE, RelayHints.parse("""{"peer":"offline"}"""))
+ for (other in listOf("pong", "", """{"peer":"online","x":1}""", """{"peer":"gone"}""", "ONLINE")) {
+ assertEquals(RelayHints.Hint.OTHER, RelayHints.parse(other))
+ }
+ }
+
+ @Test fun aRelayAccessMessageIsAcceptedOnlyWithAWellFormedKey() {
+ val ok = Wire.decodeServer("""{"type":"relayAccess","access":"$access"}""")
+ assertTrue(ok is ServerMsg.RelayAccess && ok.access == access)
+ assertNull(Wire.decodeServer("""{"type":"relayAccess","access":"short"}"""))
+ assertNull(Wire.decodeServer("""{"type":"relayAccess"}"""))
+ }
+}
+
+class PairingCodecTest {
+ private val room = RelayCrypto.base64UrlEncode(ByteArray(16) { 1 })
+ private val key = RelayCrypto.base64UrlEncode(ByteArray(32) { 2 })
+ private val access = RelayCrypto.base64UrlEncode(ByteArray(32) { 3 })
+ private val lanOnly = PairingPayload("192.168.1.20", 47821, "ab".repeat(32), "tok_en-1234567890abcd", "PC")
+
+ @Test fun aLanPairingRoundTrips() {
+ val text = PairingCodec.encode(lanOnly)
+ assertEquals(5, text.split("\n").size)
+ assertEquals(lanOnly, PairingCodec.decode(text))
+ }
+
+ @Test fun aPairingWithARelayRoundTripsWithAllFourFields() {
+ val p = lanOnly.copy(relay = RelayPairing("wss://relay.example.workers.dev", room, key, access))
+ val back = PairingCodec.decode(PairingCodec.encode(p))!!
+ assertEquals(p, back)
+ assertEquals(key, back.relay!!.key)
+ assertEquals(access, back.relay!!.access)
+ }
+
+ @Test fun aPairingSavedByAnOlderAppStillLoadsAsLanOnly() {
+ val old = listOf("192.168.1.20", "47821", "ab".repeat(32), "tok_en-1234567890abcd", "PC").joinToString("\n")
+ val p = PairingCodec.decode(old)!!
+ assertNull(p.relay)
+ assertEquals("192.168.1.20", p.host)
+ }
+
+ @Test fun anUnreadablePairingIsNotAPairing() {
+ assertNull(PairingCodec.decode(""))
+ assertNull(PairingCodec.decode("a\nb"))
+ assertNull(PairingCodec.decode("h\nnotaport\nfp\ntoken"))
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RelayNodeTwinTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RelayNodeTwinTest.kt
new file mode 100644
index 00000000..2084f51d
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RelayNodeTwinTest.kt
@@ -0,0 +1,191 @@
+package com.coucou.android.link
+
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.IOException
+import java.net.Socket
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+
+/**
+ * The WebSocket client and the connector against a real server: the relay's Node twin (android/relay/tools/dev-relay.ts,
+ * the same rules as the Cloudflare Worker, from the same code). It is a separate implementation of WebSocket (the `ws`
+ * package), so it checks this client's framing, masking and upgrade against someone else's reading of RFC 6455.
+ *
+ * Runs only when COUCOU_NODE_RELAY=1 and `npm ci` was done in android/relay (CI does both).
+ */
+class RelayNodeTwinTest {
+ private var process: Process? = null
+ private var port = 0
+ private val access = RelayCrypto.base64UrlEncode(ByteArray(32) { 9 })
+ private val room = RelayCrypto.base64UrlEncode(ByteArray(16) { 4 })
+ private val key = RelayCrypto.PairingKey(ByteArray(32) { 8 })
+
+ @Before fun start() {
+ assumeTrue("set COUCOU_NODE_RELAY=1 to run against the relay's Node twin", System.getenv("COUCOU_NODE_RELAY") == "1")
+ val script = listOf(File("../relay/tools/dev-relay.ts"), File("android/relay/tools/dev-relay.ts")).first { it.exists() }
+ val node = ProcessBuilder("node", "--experimental-strip-types", "--no-warnings", script.path)
+ .also { it.environment().putAll(mapOf("ACCESS_KEY" to access, "PORT" to "0", "HOST" to "127.0.0.1")) }
+ .redirectErrorStream(true)
+ .start()
+ process = node
+ val first = node.inputStream.bufferedReader().readLine() ?: error("the relay printed nothing")
+ port = Regex("port (\\d+)").find(first)!!.groupValues[1].toInt()
+ }
+
+ @After fun stop() { process?.destroy() }
+
+ private fun pairing(accessKey: String = access, k: RelayCrypto.PairingKey = key) =
+ RelayPairing("ws://127.0.0.1:$port", room, k.toBase64Url(), accessKey)
+
+ /** The computer's side: joins as `pc`, answers `init`, and exchanges lines. */
+ private inner class Host(k: RelayCrypto.PairingKey = key) : AutoCloseable {
+ val ws: WsConnection = WsClient.open(
+ RelayUrl.parse("ws://127.0.0.1:$port")!!, "/v1/room/$room?role=pc",
+ listOf("Authorization" to "Bearer $access"), listOf("coucou.v1", "coucou.join.${RelayCrypto.joinProof(k)}"),
+ 3_000, RelayCrypto.MAX_FRAME + 1024,
+ )
+ val lines = LinkedBlockingQueue<String>()
+ @Volatile var session: RelayCrypto.Session? = null
+ @Volatile var peerOffline = false
+
+ init {
+ Thread({
+ try {
+ while (true) when (val m = ws.receive()) {
+ is WsMessage.Binary -> {
+ val f = m.data
+ if (f.size > 1 && f[1].toInt() == RelayCrypto.T_INIT) {
+ val (accept, s) = RelayCrypto.acceptInit(k, room, f, RelayCrypto.freshNonce())
+ session = s
+ ws.sendBinary(accept)
+ } else lines.put(String(session!!.open(f)))
+ }
+ is WsMessage.Text -> if (RelayHints.parse(m.text) == RelayHints.Hint.OFFLINE) peerOffline = true
+ is WsMessage.Closed -> return@Thread
+ }
+ } catch (_: Exception) {
+ }
+ }, "node-host").apply { isDaemon = true; start() }
+ }
+
+ fun send(line: String) = ws.sendBinary(session!!.seal(line.toByteArray()))
+ override fun close() = ws.close()
+ }
+
+ private fun readLine(s: Socket): String? {
+ val b = ByteArrayOutputStream()
+ while (true) {
+ val x = s.getInputStream().read()
+ if (x < 0) return null
+ if (x == '\n'.code) return b.toString("UTF-8")
+ b.write(x)
+ }
+ }
+
+ private fun awaitSession(h: Host) {
+ val end = System.currentTimeMillis() + 5_000
+ while (h.session == null && System.currentTimeMillis() < end) Thread.sleep(10)
+ }
+
+ @Test fun aPhoneAndAComputerTalkBothWaysThroughTheRealRelay() {
+ Host().use { host ->
+ val phone = RelayConnector(pairing()).connect(3_000)
+ try {
+ phone.getOutputStream().write("{\"type\":\"hello\"}\n".toByteArray())
+ assertEquals("{\"type\":\"hello\"}", host.lines.poll(5, TimeUnit.SECONDS))
+ host.send("{\"type\":\"welcome\"}")
+ assertEquals("{\"type\":\"welcome\"}", readLine(phone))
+ // A larger line, several frames in a row, and both directions interleaved.
+ val big = "{\"x\":\"" + "a".repeat(40_000) + "\"}"
+ repeat(5) { phone.getOutputStream().write((big + "\n").toByteArray()) }
+ repeat(5) { assertEquals(big, host.lines.poll(5, TimeUnit.SECONDS)) }
+ repeat(5) { host.send(big) }
+ repeat(5) { assertEquals(big, readLine(phone)) }
+ } finally {
+ phone.close()
+ }
+ }
+ }
+
+ @Test fun theLinkClientRunsThroughTheRealRelay() {
+ Host().use { host ->
+ val welcomed = java.util.concurrent.CountDownLatch(1)
+ val listener = object : LinkListener { override fun onWelcome(desktopName: String, os: String) { welcomed.countDown() } }
+ val payload = PairingPayload("192.0.2.1", 1, "ab".repeat(32), "tok_en-1234567890abcd", "PC", pairing())
+ val client = LinkClient(payload, "Phone", listener, connector = RelayConnector(pairing()), caps = emptyList())
+ client.start()
+ try {
+ assertTrue(host.lines.poll(10, TimeUnit.SECONDS)!!.contains("\"hello\""))
+ host.send("""{"type":"welcome","v":1,"desktop":"Test PC","os":"linux"}""")
+ assertTrue(welcomed.await(5, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+ }
+
+ @Test fun aWrongAccessKeyIsRefusedByTheRelay() {
+ val c = RelayConnector(pairing(accessKey = RelayCrypto.base64UrlEncode(ByteArray(32) { 1 })))
+ try { c.connect(3_000); fail() } catch (e: WsHandshakeException) { assertEquals(401, e.status) }
+ assertEquals(RelayIssue.ACCESS_REFUSED, c.issue)
+ }
+
+ @Test fun aWrongPairingKeyCannotJoinARoomThatIsInUse() {
+ Host().use {
+ val other = RelayCrypto.PairingKey(ByteArray(32) { 77 })
+ val c = RelayConnector(pairing(k = other), answerTimeoutMs = 3_000)
+ try { c.connect(3_000); fail() } catch (_: IOException) {}
+ assertEquals(RelayIssue.ROOM_TAKEN, c.issue)
+ }
+ }
+
+ @Test fun aComputerThatIsNotThereIsReportedAfterTheWait() {
+ val c = RelayConnector(pairing(), answerTimeoutMs = 600, resendMs = 200)
+ try { c.connect(3_000); fail() } catch (_: IOException) {}
+ assertEquals(RelayIssue.COMPUTER_AWAY, c.issue)
+ }
+
+ @Test fun aComputerThatJoinsLaterIsFoundWithoutRetrying() {
+ // The phone is already waiting when the computer arrives: the relay's "online" hint (or the resent init) completes it.
+ val result = LinkedBlockingQueue<Any>()
+ Thread({ result.put(runCatching { RelayConnector(pairing(), answerTimeoutMs = 8_000, resendMs = 300).connect(3_000) }) }).apply { isDaemon = true; start() }
+ Thread.sleep(500)
+ Host().use { host ->
+ val r = result.poll(8, TimeUnit.SECONDS) as Result<*>
+ val socket = r.getOrThrow() as Socket
+ socket.getOutputStream().write("{\"type\":\"ping\"}\n".toByteArray())
+ assertEquals("{\"type\":\"ping\"}", host.lines.poll(5, TimeUnit.SECONDS))
+ socket.close()
+ }
+ }
+
+ @Test fun whenTheComputerGoesAwayTheStreamEnds() {
+ val host = Host()
+ val phone = RelayConnector(pairing()).connect(3_000)
+ awaitSession(host)
+ host.close()
+ phone.soTimeout = 5_000
+ assertEquals(null, readLine(phone))
+ phone.close()
+ }
+
+ @Test fun aSecondPhoneReplacesTheFirstOne() {
+ Host().use { host ->
+ val first = RelayConnector(pairing()).connect(3_000)
+ val second = RelayConnector(pairing()).connect(3_000)
+ first.soTimeout = 5_000
+ assertEquals("the first phone was replaced", null, readLine(first))
+ second.getOutputStream().write("{\"type\":\"ping\"}\n".toByteArray())
+ assertEquals("{\"type\":\"ping\"}", host.lines.poll(5, TimeUnit.SECONDS))
+ second.close()
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/RustDesktopInteropTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/RustDesktopInteropTest.kt
new file mode 100644
index 00000000..8679ccf3
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/RustDesktopInteropTest.kt
@@ -0,0 +1,525 @@
+package com.coucou.android.link
+
+import com.coucou.android.ReferenceFiles
+import java.io.BufferedReader
+import java.io.InputStreamReader
+import java.io.PrintWriter
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.TimeUnit
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/**
+ * The real [LinkClient] against the real desktop server of the Windows/Linux app
+ * (windows/src-tauri/src/phone_link), a separate implementation of docs/ANDROID_LINK.md in Rust
+ * with its own TLS stack (rustls) and its own certificate.
+ *
+ * The server is the ignored cargo test `phone_link::interop::interop_server`, started here and
+ * driven over stdin. Compiling it takes minutes, so this only runs when COUCOU_RUST_INTEROP=1
+ * (the `interop` job in .github/workflows/android.yml sets it) and cargo is installed.
+ */
+class RustDesktopInteropTest {
+ private var proc: Process? = null
+ private var stdin: PrintWriter? = null
+ private val lines = LinkedBlockingQueue<String>()
+
+ @After fun cleanup() {
+ stdin?.println("quit")
+ stdin?.flush()
+ proc?.waitFor(5, TimeUnit.SECONDS)
+ proc?.destroyForcibly()
+ }
+
+ private fun startDesktop(): JSONObject {
+ assumeTrue("set COUCOU_RUST_INTEROP=1 to run against the Rust desktop", System.getenv("COUCOU_RUST_INTEROP") == "1")
+ val manifest = ReferenceFiles.file("windows/Cargo.toml").absolutePath
+ proc = try {
+ ProcessBuilder(
+ "cargo", "test", "--manifest-path", manifest, "-p", "coucou", "--lib", "--locked", "--",
+ "--ignored", "--nocapture", "phone_link::interop::interop_server",
+ ).redirectErrorStream(true).start()
+ } catch (_: Exception) {
+ assumeTrue("cargo not available", false)
+ return JSONObject()
+ }
+ stdin = PrintWriter(proc!!.outputStream, true)
+ Thread {
+ BufferedReader(InputStreamReader(proc!!.inputStream)).forEachLine { lines.add(it) }
+ }.apply { isDaemon = true; start() }
+ // The first start compiles the whole app: allow for it.
+ val deadline = System.currentTimeMillis() + 20 * 60_000
+ while (System.currentTimeMillis() < deadline) {
+ val l = lines.poll(5, TimeUnit.SECONDS) ?: continue
+ if (l.startsWith("{\"listening\"")) return JSONObject(l)
+ }
+ error("the Rust desktop did not start")
+ }
+
+ /** Sends one command and waits until the desktop has done it. */
+ private fun command(text: String) {
+ stdin!!.println(text)
+ val deadline = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < deadline) {
+ val l = lines.poll(1, TimeUnit.SECONDS) ?: continue
+ if (l == "OK $text") return
+ }
+ error("no answer to '$text'")
+ }
+
+ /** True if the desktop printed [expected] within [seconds]. */
+ private fun sawLine(expected: String, seconds: Long): Boolean {
+ val deadline = System.currentTimeMillis() + seconds * 1000
+ while (System.currentTimeMillis() < deadline) {
+ val l = lines.poll(200, TimeUnit.MILLISECONDS) ?: continue
+ if (l == expected) return true
+ }
+ return false
+ }
+
+ private class Rec : LinkListener {
+ val welcome = LinkedBlockingQueue<String>()
+ val sessions = LinkedBlockingQueue<List<SessionInfo>>()
+ val approvals = LinkedBlockingQueue<ApprovalRequest>()
+ val resolved = LinkedBlockingQueue<String>()
+ val errors = LinkedBlockingQueue<String>()
+ override fun onWelcome(desktopName: String, os: String) { welcome.add(desktopName) }
+ override fun onSessions(sessions: List<SessionInfo>) { this.sessions.add(sessions) }
+ override fun onApproval(request: ApprovalRequest) { approvals.add(request) }
+ override fun onApprovalResolved(fingerprint: String) { resolved.add(fingerprint) }
+ override fun onError(code: String, message: String) { errors.add(code) }
+ val caps = LinkedBlockingQueue<Set<String>>()
+ val chat = LinkedBlockingQueue<String>()
+ // "prefs" (the outfit) is offered to every app that asks, so the other tests leave it out; it has its own test.
+ override fun onCaps(caps: Set<String>) { this.caps.add(caps - Protocol.CAP_PREFS); allCaps.add(caps) }
+ val allCaps = LinkedBlockingQueue<Set<String>>()
+ val prefs = LinkedBlockingQueue<String>()
+ val serviceCards = LinkedBlockingQueue<List<ServiceCard>>()
+ override fun onServices(cards: List<ServiceCard>) { serviceCards.add(cards) }
+ val usages = LinkedBlockingQueue<UsageSnapshot>()
+ override fun onUsage(usage: UsageSnapshot) { usages.add(usage) }
+ val diffParts = LinkedBlockingQueue<ServerMsg.Diff>()
+ override fun onDiff(part: ServerMsg.Diff) { diffParts.add(part) }
+ override fun onPrefs(outfit: String) { prefs.add(outfit) }
+ override fun onChatModels(models: List<ChatModel>) { chat.add("models:" + models.joinToString(",") { it.id }) }
+ override fun onChatDelta(id: String, text: String) { chat.add("delta:$id:$text") }
+ override fun onChatDone(id: String, text: String?) { chat.add("done:$id:${text ?: "-"}") }
+ override fun onChatError(id: String, reason: String, message: String) { chat.add("error:$id:$reason") }
+
+ fun answer(id: String, seconds: Long = 15): Pair<String, String> {
+ val text = StringBuilder()
+ val deadline = System.currentTimeMillis() + seconds * 1000
+ while (System.currentTimeMillis() < deadline) {
+ val e = chat.poll(200, TimeUnit.MILLISECONDS) ?: continue
+ when {
+ e.startsWith("delta:$id:") -> text.append(e.removePrefix("delta:$id:"))
+ e.startsWith("done:$id:") -> return text.toString() to ("done:" + e.removePrefix("done:$id:"))
+ e.startsWith("error:$id:") -> return text.toString() to e
+ }
+ }
+ error("no end of answer for $id")
+ }
+ }
+
+ private fun chatClient(info: JSONObject, rec: Rec, caps: List<String> = Protocol.CAPABILITIES): LinkClient {
+ val client = LinkClient(PairingPayload.parse(info.getString("link"))!!, "Interop Pixel", rec, readTimeoutMs = 5_000, caps = caps)
+ client.start()
+ return client
+ }
+
+ private fun connect(info: JSONObject, rec: Rec, token: String? = null): LinkClient {
+ val pairing = PairingPayload.parse(info.getString("link"))
+ assertNotNull("the Rust desktop's pairing link was not accepted: ${info.getString("link")}", pairing)
+ val client = LinkClient(if (token == null) pairing!! else pairing!!.copy(token = token), "Interop Pixel", rec, readTimeoutMs = 5_000)
+ client.start()
+ return client
+ }
+
+ @Test fun pairsReceivesSessionsAndApprovalAndAllows() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec)
+ try {
+ assertEquals("Rust desktop", rec.welcome.poll(15, TimeUnit.SECONDS))
+ command("sessions")
+ var sessions = rec.sessions.poll(10, TimeUnit.SECONDS)
+ while (sessions != null && sessions.isEmpty()) sessions = rec.sessions.poll(10, TimeUnit.SECONDS)
+ assertNotNull("no sessions arrived", sessions)
+ assertEquals(listOf("integration_claude", "agent_gemini"), sessions!!.map { it.pillId })
+ assertEquals("Claude Code", sessions[0].agent)
+ assertEquals(2, sessions[0].stepIndex)
+ assertEquals(6, sessions[0].stepCount)
+
+ command("approval req-1 npm run build")
+ val req = rec.approvals.poll(10, TimeUnit.SECONDS)
+ assertNotNull("no approval request arrived", req)
+ assertEquals("npm run build", req!!.command)
+ assertEquals("Bash", req.tool)
+ // The Rust fingerprint must be the one the Mac-compatible Kotlin derivation yields.
+ assertEquals(Fingerprint.of("integration_claude", "interop", "Bash", "npm run build", "req-1"), req.fingerprint)
+
+ assertTrue(client.decide(req.fingerprint, allow = true))
+ assertEquals(req.fingerprint, rec.resolved.poll(10, TimeUnit.SECONDS))
+ assertTrue("the desktop never applied the decision", sawLine("DECISION allow req-1", 10))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun aCommandOf10000CharactersIsFlaggedAndCannotBeAllowedFromThePhone() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec)
+ try {
+ assertNotNull(rec.welcome.poll(15, TimeUnit.SECONDS))
+ command("approval req-long " + "x".repeat(10_000))
+ val req = rec.approvals.poll(10, TimeUnit.SECONDS)!!
+ assertTrue(req.truncated)
+ assertEquals(500, req.command.length)
+ assertFalse(com.coucou.android.core.ApprovalSheetPlan.canAllowHere(req))
+ // Even a phone that asks anyway is not obeyed.
+ client.decide(req.fingerprint, allow = true)
+ assertFalse("the desktop must not apply Allow for a cut command", sawLine("DECISION allow req-long", 2))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun denyReachesTheDesktop() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec)
+ try {
+ assertNotNull(rec.welcome.poll(15, TimeUnit.SECONDS))
+ command("approval req-9 rm -rf build")
+ val req = rec.approvals.poll(10, TimeUnit.SECONDS)!!
+ assertTrue(client.decide(req.fingerprint, allow = false))
+ assertTrue(sawLine("DECISION deny req-9", 10))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun aRequestAnsweredAtTheDeskCannotBeAnsweredFromThePhone() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec)
+ try {
+ assertNotNull(rec.welcome.poll(15, TimeUnit.SECONDS))
+ command("approval req-2 ls")
+ val req = rec.approvals.poll(10, TimeUnit.SECONDS)!!
+ command("clear") // allowed on the desktop
+ assertEquals(req.fingerprint, rec.resolved.poll(10, TimeUnit.SECONDS))
+ assertFalse("the phone no longer offers it", client.decide(req.fingerprint, allow = true))
+ assertFalse(sawLine("DECISION allow req-2", 1))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun aWrongTokenIsRefused() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec, token = "x".repeat(30))
+ try {
+ assertEquals("auth", rec.errors.poll(15, TimeUnit.SECONDS))
+ assertNull(rec.welcome.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun pairingAgainDisconnectsThePhoneThatHadTheOldCode() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = connect(info, rec)
+ try {
+ assertNotNull(rec.welcome.poll(15, TimeUnit.SECONDS))
+ command("repair brand-new-token-0123456789")
+ assertEquals("auth", rec.errors.poll(10, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── Service cards (cap services) ────────────────────────────────────────────────
+
+ @Test fun theRealServerSendsOnlyTheServicesTheUserTicked() {
+ val info = startDesktop()
+ command("services stripe")
+ command("servicecards")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(setOf("services"), rec.caps.poll(15, TimeUnit.SECONDS))
+ val cards = rec.serviceCards.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(listOf("integration_stripe"), cards.map { it.id })
+ assertTrue("the Notion card was not ticked: its text must not arrive", cards.none { c -> c.items.any { it.label == "Private page" } })
+ assertNull(rec.serviceCards.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withNothingTickedTheRealServerOffersNoServices() {
+ val info = startDesktop()
+ command("servicecards")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ assertNull(rec.serviceCards.poll(2, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── Plan usage (cap usage) ──────────────────────────────────────────────────────
+
+ @Test fun theRealServerSendsTheUsageToAnAppThatAsksWhileTheSwitchIsOn() {
+ val info = startDesktop()
+ command("usage on")
+ command("usagepct 62.6")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ val old = Rec()
+ val oldClient = chatClient(info, old, caps = emptyList())
+ try {
+ assertEquals(setOf("prefs", "usage"), rec.allCaps.poll(15, TimeUnit.SECONDS))
+ val first = rec.usages.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(PlanWindow(63, 1_900_000_000_000), first.claude!!.fiveHour)
+ assertEquals("max", first.claude!!.plan)
+ command("usagepct 80")
+ assertEquals(80, rec.usages.poll(10, TimeUnit.SECONDS)!!.claude!!.fiveHour!!.pct)
+ assertNull("an app that did not ask hears nothing", old.usages.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ oldClient.stop()
+ }
+ }
+
+ @Test fun withTheSwitchOffTheRealServerOffersNoUsage() {
+ val info = startDesktop()
+ command("usagepct 50")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ assertNull(rec.usages.poll(2, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── File changes (cap diffs) ────────────────────────────────────────────────────
+
+ /** The connection number the desktop printed for a request, or null. */
+ private fun connOfRequest(seconds: Long): String? {
+ val deadline = System.currentTimeMillis() + seconds * 1000
+ while (System.currentTimeMillis() < deadline) {
+ val l = lines.poll(200, TimeUnit.MILLISECONDS) ?: continue
+ if (l.startsWith("GETDIFF ")) return l.split(" ")[1]
+ }
+ return null
+ }
+
+ @Test fun theRealServerListsFilesByNameAndSendsAFileOnRequestOnly() {
+ val info = startDesktop()
+ command("diffs on")
+ command("sessions")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(setOf("diffs"), rec.caps.poll(15, TimeUnit.SECONDS))
+ val s = generateSequence { rec.sessions.poll(10, TimeUnit.SECONDS) }.take(5).first { l -> l.any { it.files.isNotEmpty() } }
+ val file = s.first { it.files.isNotEmpty() }.files[0]
+ assertEquals("a full path went in; only the name comes out", "app.ts", file.name)
+ assertEquals(7L, file.id)
+ assertNull("nothing is sent before it is asked for", rec.diffParts.poll(1, TimeUnit.SECONDS))
+
+ assertTrue(client.getDiff("integration_claude", 7))
+ val conn = connOfRequest(10)
+ assertNotNull("the island was never asked", conn)
+ command("diff $conn 250")
+ val a = rec.diffParts.poll(10, TimeUnit.SECONDS)!!
+ val b = rec.diffParts.poll(10, TimeUnit.SECONDS)!!
+ assertEquals(200, a.lines.size + b.lines.size)
+ assertTrue(a.truncated)
+ assertEquals("app.ts", a.name)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withTheSwitchOffTheRealServerOffersNoFilesAndIgnoresTheRequest() {
+ val info = startDesktop()
+ command("sessions")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ assertTrue(!client.getDiff("integration_claude", 7))
+ assertTrue(generateSequence { rec.sessions.poll(2, TimeUnit.SECONDS) }.take(3).all { l -> l.all { it.files.isEmpty() } })
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── Mochi's outfit (cap prefs) ─────────────────────────────────────────────────
+
+ @Test fun theOutfitReachesAnAppThatAsksAndNobodyElse() {
+ val info = startDesktop()
+ command("outfit beanie")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ val old = Rec()
+ val oldClient = chatClient(info, old, caps = emptyList())
+ try {
+ assertEquals(setOf("prefs"), rec.allCaps.poll(15, TimeUnit.SECONDS))
+ assertEquals("beanie", rec.prefs.poll(10, TimeUnit.SECONDS))
+ command("outfit crown")
+ assertEquals("crown", rec.prefs.poll(10, TimeUnit.SECONDS))
+ command("outfit topHat") // not a wardrobe value: never sent
+ command("outfit auto")
+ assertEquals("auto", rec.prefs.poll(10, TimeUnit.SECONDS))
+ assertEquals(emptySet<String>(), old.allCaps.poll(15, TimeUnit.SECONDS))
+ assertNull("an app that did not ask hears nothing", old.prefs.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ oldClient.stop()
+ }
+ }
+
+ // ── chat, against the real server with a fake provider ───────────────────────────
+
+ @Test fun chatWorksAgainstTheRealServerWhenItsSwitchIsOn() {
+ val info = startDesktop()
+ command("chat on")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(setOf("chat"), rec.caps.poll(15, TimeUnit.SECONDS))
+ assertEquals("models:anthropic/fake-claude,openai/fake-gpt", rec.chat.poll(10, TimeUnit.SECONDS))
+ assertTrue(client.chatSend("c1", "openai/fake-gpt", "hello"))
+ val (text, end) = rec.answer("c1")
+ assertEquals("echo from openai/fake-gpt: hello", text)
+ assertEquals("done:-", end)
+
+ client.chatSend("c2", "openai/fake-gpt", "/error")
+ assertEquals("error:c2:provider", rec.answer("c2").second)
+ client.chatSend("c3", "openai/fake-gpt", "/auth")
+ assertEquals("error:c3:auth", rec.answer("c3").second)
+ client.chatSend("c4", "ollama/not-allowed", "hi")
+ assertEquals("error:c4:not_allowed", rec.answer("c4").second)
+ client.chatSend("c5", "openai/fake-gpt", "x".repeat(Protocol.CHAT_MAX_TEXT + 1))
+ assertEquals("error:c5:too_long", rec.answer("c5").second)
+
+ client.chatSend("s1", "openai/fake-gpt", "/slow")
+ assertTrue("never started", generateSequence { rec.chat.poll(5, TimeUnit.SECONDS) }.take(20).any { it.startsWith("delta:s1:") })
+ client.chatSend("s2", "openai/fake-gpt", "second")
+ assertEquals("error:s2:busy", rec.answer("s2").second)
+ client.chatCancel("s1")
+ assertEquals("error:s1:canceled", rec.answer("s1").second)
+
+ // New chat: the computer forgets its side
+ client.chatReset()
+ assertTrue(sawLine("CHAT reset", 10))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withTheSwitchOffTheServerOffersNoChat() {
+ val info = startDesktop()
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ client.chatSend("o1", "openai/fake-gpt", "hi")
+ assertNull(rec.chat.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun anOlderAppIsNeverOfferedChatEvenWhenItIsOn() {
+ val info = startDesktop()
+ command("chat on")
+ val rec = Rec()
+ val client = chatClient(info, rec, caps = emptyList())
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ client.chatSend("o1", "openai/fake-gpt", "hi")
+ assertNull(rec.chat.poll(1, TimeUnit.SECONDS))
+ } finally {
+ client.stop()
+ }
+ }
+
+ // ── session details, against the real server ──────────────────────────────────────────
+
+ private fun claude(rec: Rec): SessionInfo {
+ val deadline = System.currentTimeMillis() + 15_000
+ while (System.currentTimeMillis() < deadline) {
+ val list = rec.sessions.poll(1, TimeUnit.SECONDS) ?: continue
+ list.firstOrNull { it.pillId == "integration_claude" }?.let { return it }
+ }
+ error("no Claude Code session arrived")
+ }
+
+ @Test fun detailsArriveFromTheRealServerWhenItsSwitchIsOn_andNeverAPath() {
+ val info = startDesktop()
+ command("details on")
+ command("sessions")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(setOf("details"), rec.caps.poll(15, TimeUnit.SECONDS))
+ val s = claude(rec)
+ assertEquals(listOf("Read · README.md", "Edit · src/app.ts"), s.steps)
+ assertEquals("Fixed the bug", s.finalLine)
+ assertEquals("proj", s.project)
+ assertEquals("#2DD4BF", s.color)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun withTheSwitchOffTheRealServerSendsNoDetailsToAnAppThatAsks() {
+ val info = startDesktop()
+ command("sessions")
+ val rec = Rec()
+ val client = chatClient(info, rec)
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ val s = claude(rec)
+ assertEquals(emptyList<String>(), s.steps)
+ assertNull(s.project); assertNull(s.finalLine); assertNull(s.color)
+ } finally {
+ client.stop()
+ }
+ }
+
+ @Test fun anOlderAppGetsTheV1SessionsFromTheRealServerEvenWithDetailsOn() {
+ val info = startDesktop()
+ command("details on")
+ command("sessions")
+ val rec = Rec()
+ val client = chatClient(info, rec, caps = emptyList())
+ try {
+ assertEquals(emptySet<String>(), rec.caps.poll(15, TimeUnit.SECONDS))
+ val s = claude(rec)
+ assertEquals("Editing files", s.statusText)
+ assertEquals(emptyList<String>(), s.steps)
+ assertNull(s.project)
+ } finally {
+ client.stop()
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/TransportTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/TransportTest.kt
new file mode 100644
index 00000000..b85230e9
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/TransportTest.kt
@@ -0,0 +1,148 @@
+package com.coucou.android.link
+
+import java.io.IOException
+import java.net.Socket
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+
+/** LAN first, relay when the LAN does not answer, and back to the LAN when it does again. */
+class TransportTest {
+ private var now = 1_000_000L
+ private var relayOn = true
+ private val policy = TransportPolicy({ relayOn }, { now })
+
+ @Test fun withoutARelayOnlyTheLanIsEverTried() {
+ relayOn = false
+ assertEquals(listOf(Route.LAN), policy.order())
+ policy.lanFailed()
+ assertEquals(listOf(Route.LAN), policy.order())
+ assertEquals(5_000, policy.lanTimeoutMs(5_000))
+ }
+
+ @Test fun withARelayTheLanComesFirstWithAShortTimeout() {
+ assertEquals(listOf(Route.LAN, Route.RELAY), policy.order())
+ assertEquals(TransportPolicy.LAN_FAST_MS, policy.lanTimeoutMs(10_000))
+ assertEquals(1_000, policy.lanTimeoutMs(1_000))
+ }
+
+ @Test fun afterALanFailureTheRelayIsTriedFirstForAWhileThenTheLanAgain() {
+ policy.lanFailed()
+ assertEquals(listOf(Route.RELAY, Route.LAN), policy.order())
+ now += TransportPolicy.LAN_SKIP_MS - 1
+ assertEquals(listOf(Route.RELAY, Route.LAN), policy.order())
+ now += 1
+ assertEquals(listOf(Route.LAN, Route.RELAY), policy.order())
+ }
+
+ @Test fun aLanSuccessForgetsTheFailure() {
+ policy.lanFailed()
+ policy.lanWorked()
+ assertEquals(listOf(Route.LAN, Route.RELAY), policy.order())
+ }
+
+ // ── the connector on top of the policy ──
+
+ private class FakeSocket : Socket()
+
+ private class Fake(private val works: () -> Boolean) : Connector {
+ val calls = AtomicInteger()
+ val timeouts = mutableListOf<Int>()
+ val made = mutableListOf<Socket>()
+ override fun connect(timeoutMs: Int): Socket {
+ calls.incrementAndGet()
+ timeouts += timeoutMs
+ if (!works()) throw IOException("down")
+ return FakeSocket().also { made += it }
+ }
+ }
+
+ private fun connector(lan: Fake, relay: Fake, routes: MutableList<Route> = mutableListOf(), every: Long = 3_600_000) =
+ FallbackConnector(lan, relay, policy, { routes += it }, probeEveryMs = every, probeTimeoutMs = 200)
+
+ @Test fun theLanIsUsedWhenItAnswers() {
+ val lan = Fake { true }
+ val relay = Fake { true }
+ val routes = mutableListOf<Route>()
+ val c = connector(lan, relay, routes)
+ val s = c.connect(10_000)
+ assertSame(lan.made.single(), s)
+ assertEquals(0, relay.calls.get())
+ assertEquals(listOf(Route.LAN), routes)
+ assertEquals(TransportPolicy.LAN_FAST_MS, lan.timeouts.single())
+ }
+
+ @Test fun theRelayIsUsedWhenTheLanDoesNotAnswer() {
+ val lan = Fake { false }
+ val relay = Fake { true }
+ val routes = mutableListOf<Route>()
+ val c = connector(lan, relay, routes)
+ val s = c.connect(10_000)
+ assertSame(relay.made.single(), s)
+ assertEquals(listOf(Route.RELAY), routes)
+ assertEquals(Route.RELAY, c.route)
+ c.stop()
+ // The next attempt goes to the relay first, without waiting for a LAN timeout.
+ c.connect(10_000)
+ assertEquals("the LAN was not tried again within the window", 1, lan.calls.get())
+ }
+
+ @Test fun whenBothFailTheFirstFailureIsReported() {
+ val c = connector(Fake { false }, Fake { false })
+ try { c.connect(1_000); fail() } catch (e: IOException) { assertEquals("down", e.message) }
+ }
+
+ @Test fun ifTheRelayFailsInsideTheSkipWindowTheLanGetsAnotherChance() {
+ val lanUp = AtomicBoolean(false)
+ val lan = Fake { lanUp.get() }
+ val relay = Fake { false }
+ val c = connector(lan, relay)
+ try { c.connect(1_000); fail() } catch (_: IOException) {}
+ lanUp.set(true) // back home, inside the 60 s window
+ val s = c.connect(1_000)
+ assertSame(lan.made.last(), s)
+ assertEquals(Route.LAN, c.route)
+ }
+
+ @Test fun whileOnTheRelayAFoundLanEndsTheRelayConnectionSoTheLinkMovesBack() {
+ val lanUp = AtomicBoolean(false)
+ val lan = Fake { lanUp.get() }
+ val relay = Fake { true }
+ val c = connector(lan, relay, every = 40)
+ val relaySocket = c.connect(1_000)
+ assertFalse(relaySocket.isClosed)
+ lanUp.set(true)
+ val deadline = System.currentTimeMillis() + 3_000
+ while (!relaySocket.isClosed && System.currentTimeMillis() < deadline) Thread.sleep(10)
+ assertTrue("the relay socket was closed once the LAN answered", relaySocket.isClosed)
+ c.stop()
+ }
+
+ @Test fun aNetworkChangeLooksForTheLanAtOnce() {
+ val lanUp = AtomicBoolean(false)
+ val lan = Fake { lanUp.get() }
+ val c = connector(lan, Fake { true })
+ val relaySocket = c.connect(1_000)
+ c.networkChanged()
+ Thread.sleep(150)
+ assertFalse("the LAN is still down: stay", relaySocket.isClosed)
+ lanUp.set(true)
+ c.networkChanged()
+ val deadline = System.currentTimeMillis() + 3_000
+ while (!relaySocket.isClosed && System.currentTimeMillis() < deadline) Thread.sleep(10)
+ assertTrue(relaySocket.isClosed)
+ c.stop()
+ }
+
+ @Test fun theProbeConnectionItselfIsClosedAgain() {
+ val lan = Fake { true }
+ val c = connector(lan, Fake { true })
+ assertTrue(c.lanAnswers())
+ assertTrue(lan.made.single().isClosed)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/link/WebSocketTest.kt b/android/app/src/test/kotlin/com/coucou/android/link/WebSocketTest.kt
new file mode 100644
index 00000000..dcd2cc5e
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/link/WebSocketTest.kt
@@ -0,0 +1,255 @@
+package com.coucou.android.link
+
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.EOFException
+import java.util.Random
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Test
+
+/** The in-house WebSocket client (decision D2): framing, masking, fragmentation, size limits and a fuzz run. */
+class WebSocketTest {
+ private fun hex(s: String) = s.replace(" ", "").chunked(2).map { it.toInt(16).toByte() }.toByteArray()
+
+ private fun decoder(bytes: ByteArray, max: Int = 1024) = WsDecoder(ByteArrayInputStream(bytes), max)
+
+ /** What a server sends: not masked. */
+ private fun serverFrame(opcode: Int, payload: ByteArray, fin: Boolean = true): ByteArray {
+ val out = ByteArrayOutputStream()
+ out.write((if (fin) 0x80 else 0) or opcode)
+ when {
+ payload.size < 126 -> out.write(payload.size)
+ payload.size <= 0xFFFF -> { out.write(126); out.write(payload.size ushr 8); out.write(payload.size and 0xFF) }
+ else -> { out.write(127); for (s in 56 downTo 0 step 8) out.write(((payload.size.toLong() ushr s) and 0xFF).toInt()) }
+ }
+ out.write(payload)
+ return out.toByteArray()
+ }
+
+ private fun message(e: WsEvent) = (e as WsEvent.Message).message
+
+ // ── masking and encoding (RFC 6455 section 5.7 examples) ──
+
+ @Test fun aMaskedClientFrameMatchesTheRfcExample() {
+ val frame = WsFrames.encode(WsOpcode.TEXT, "Hello".toByteArray(), hex("37fa213d"))
+ assertArrayEquals(hex("81 85 37fa213d 7f9f4d5158"), frame)
+ }
+
+ @Test fun everyClientFrameIsMaskedAndTheMaskIsFresh() {
+ val a = WsFrames.encode(WsOpcode.BINARY, ByteArray(10), hex("01020304"))
+ assertTrue("the mask bit is set", a[1].toInt() and 0x80 != 0)
+ assertFalse("the payload is not sent in clear", a.copyOfRange(6, 16).all { it == 0.toByte() })
+ val link = WsConnectionProbe.maskedFramesDiffer()
+ assertTrue("two frames of the same data use different masks", link)
+ }
+
+ @Test fun lengthsAroundTheBoundariesRoundTrip() {
+ for (n in listOf(0, 1, 124, 125, 126, 127, 65535, 65536, 70000)) {
+ val payload = ByteArray(n) { (it * 7).toByte() }
+ val enc = WsFrames.encode(WsOpcode.BINARY, payload, hex("a1b2c3d4"))
+ // Unmask what we encoded, by the rules a server follows, and read it back.
+ val headerLen = 2 + (if (n < 126) 0 else if (n <= 0xFFFF) 2 else 8)
+ val unmasked = ByteArray(n) { (enc[headerLen + 4 + it].toInt() xor "a1b2c3d4".chunked(2).map { h -> h.toInt(16) }[it and 3]).toByte() }
+ assertArrayEquals(payload, unmasked)
+ val e = decoder(serverFrame(WsOpcode.BINARY, payload), max = 100_000).next()
+ assertArrayEquals(payload, (message(e) as WsMessage.Binary).data)
+ }
+ }
+
+ @Test fun aControlFrameOver125BytesCannotBeEncoded() {
+ try { WsFrames.encode(WsOpcode.PING, ByteArray(126), ByteArray(4)); fail() } catch (_: IllegalArgumentException) {}
+ }
+
+ // ── decoding ──
+
+ @Test fun textAndBinaryMessagesAreDecoded() {
+ assertEquals("Hello", (message(decoder(hex("81 05 48656c6c6f")).next()) as WsMessage.Text).text)
+ assertArrayEquals(byteArrayOf(1, 2, 3), (message(decoder(serverFrame(WsOpcode.BINARY, byteArrayOf(1, 2, 3))).next()) as WsMessage.Binary).data)
+ }
+
+ @Test fun fragmentedMessagesAreReassembledEvenWithAPingBetween() {
+ val bytes = serverFrame(WsOpcode.TEXT, "Hel".toByteArray(), fin = false) +
+ serverFrame(WsOpcode.PING, byteArrayOf(9)) +
+ serverFrame(WsOpcode.CONTINUATION, "lo".toByteArray(), fin = true)
+ val d = decoder(bytes)
+ val ping = d.next()
+ assertTrue(ping is WsEvent.Ping && ping.payload.contentEquals(byteArrayOf(9)))
+ assertEquals("Hello", (message(d.next()) as WsMessage.Text).text)
+ }
+
+ @Test fun aMultiByteCharacterSplitAcrossFragmentsIsNotCorrupted() {
+ val euro = "€".toByteArray() // 3 bytes
+ val bytes = serverFrame(WsOpcode.TEXT, euro.copyOfRange(0, 1), fin = false) + serverFrame(WsOpcode.CONTINUATION, euro.copyOfRange(1, 3))
+ assertEquals("€", (message(decoder(bytes).next()) as WsMessage.Text).text)
+ }
+
+ @Test fun theRulesTheServerMustKeepAreEnforced() {
+ val bad = mapOf(
+ "masked server frame" to hex("81 85 37fa213d 7f9f4d5158"),
+ "reserved bit" to hex("c1 05 48656c6c6f"),
+ "fragmented control frame" to hex("09 00"),
+ "control frame over 125" to (byteArrayOf(0x89.toByte(), 126, 0, 126) + ByteArray(126)),
+ "unknown data opcode" to hex("83 00"),
+ "unknown control opcode" to hex("8b 00"),
+ "continuation without a start" to hex("80 01 41"),
+ "a message inside a message" to (serverFrame(WsOpcode.TEXT, byteArrayOf(65), fin = false) + serverFrame(WsOpcode.TEXT, byteArrayOf(66))),
+ "text that is not UTF-8" to serverFrame(WsOpcode.TEXT, byteArrayOf(0xC3.toByte(), 0x28)),
+ "close with one byte" to serverFrame(WsOpcode.CLOSE, byteArrayOf(3)),
+ "close code 1005" to serverFrame(WsOpcode.CLOSE, byteArrayOf(0x03, 0xED.toByte())),
+ "close code 999" to serverFrame(WsOpcode.CLOSE, byteArrayOf(0x03, 0xE7.toByte())),
+ "64-bit length with the top bit" to hex("82 7f 8000000000000000"),
+ )
+ for ((name, bytes) in bad) {
+ try { decoder(bytes).next(); fail("$name was accepted") } catch (_: WsProtocolException) {}
+ }
+ }
+
+ @Test fun aHugeLengthIsRefusedBeforeAnythingIsAllocatedOrRead() {
+ // The header claims 1 GiB; the stream holds nothing more. A protocol error, not an out-of-memory or a long wait.
+ try { decoder(hex("82 7f 0000000040000000")).next(); fail() } catch (_: WsProtocolException) {}
+ try { decoder(hex("82 7f 00000000ffffffff"), max = 66_000).next(); fail() } catch (_: WsProtocolException) {}
+ // A message over the limit, even in small fragments.
+ val parts = ByteArrayOutputStream()
+ parts.write(serverFrame(WsOpcode.BINARY, ByteArray(600), fin = false))
+ parts.write(serverFrame(WsOpcode.CONTINUATION, ByteArray(600), fin = true))
+ try { decoder(parts.toByteArray(), max = 1000).next(); fail() } catch (_: WsProtocolException) {}
+ }
+
+ @Test fun aMessageExactlyAtTheLimitIsAccepted() {
+ val e = decoder(serverFrame(WsOpcode.BINARY, ByteArray(1000)), max = 1000).next()
+ assertEquals(1000, (message(e) as WsMessage.Binary).data.size)
+ }
+
+ @Test fun aTruncatedStreamIsAnEndOfStreamNotAHang() {
+ for (cut in 1 until 10) {
+ val full = serverFrame(WsOpcode.TEXT, "Hello".toByteArray())
+ try { decoder(full.copyOf(minOf(cut, full.size - 1))).next(); fail("cut $cut") } catch (_: EOFException) {}
+ }
+ }
+
+ @Test fun closeFramesCarryTheirCodeAndReason() {
+ val m = message(decoder(serverFrame(WsOpcode.CLOSE, WsFrames.closePayload(1008, "join proof"))).next()) as WsMessage.Closed
+ assertEquals(1008, m.code)
+ assertEquals("join proof", m.reason)
+ val none = message(decoder(serverFrame(WsOpcode.CLOSE, ByteArray(0))).next()) as WsMessage.Closed
+ assertNull(none.code)
+ }
+
+ // ── a malformed-input fuzz run ──
+
+ @Test fun randomBytesNeverCrashTheDecoderAndNeverBufferMoreThanTheLimit() {
+ val rnd = Random(20260101)
+ val limit = 2048
+ var accepted = 0
+ repeat(30_000) {
+ val bytes = ByteArray(rnd.nextInt(80)).also(rnd::nextBytes)
+ val d = WsDecoder(ByteArrayInputStream(bytes), limit)
+ try {
+ while (true) {
+ when (val e = d.next()) {
+ is WsEvent.Message -> {
+ accepted++
+ val m = e.message
+ if (m is WsMessage.Binary) assertTrue(m.data.size <= limit)
+ if (m is WsMessage.Text) assertTrue(m.text.length <= limit)
+ }
+ else -> {}
+ }
+ }
+ } catch (_: WsProtocolException) {
+ } catch (_: EOFException) {
+ }
+ }
+ assertTrue("the fuzz inputs reached some valid frames too", accepted > 0)
+ }
+
+ @Test fun flippedBitsInValidFramesNeverEscapeAsAnythingButAProtocolError() {
+ val rnd = Random(7)
+ val valid = serverFrame(WsOpcode.TEXT, "Hel".toByteArray(), fin = false) + serverFrame(WsOpcode.PING, byteArrayOf(1, 2)) +
+ serverFrame(WsOpcode.CONTINUATION, "lo".toByteArray()) + serverFrame(WsOpcode.BINARY, ByteArray(200) { it.toByte() }) +
+ serverFrame(WsOpcode.CLOSE, WsFrames.closePayload(1000, "bye"))
+ repeat(20_000) {
+ val bytes = valid.copyOf()
+ repeat(1 + rnd.nextInt(4)) { bytes[rnd.nextInt(bytes.size)] = (bytes[rnd.nextInt(bytes.size)].toInt() xor (1 shl rnd.nextInt(8))).toByte() }
+ val d = WsDecoder(ByteArrayInputStream(bytes), 4096)
+ try { while (true) d.next() } catch (_: WsProtocolException) {} catch (_: EOFException) {}
+ }
+ }
+
+ // ── the upgrade ──
+
+ @Test fun theAcceptValueMatchesTheRfcExample() {
+ assertEquals("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", WsHandshake.acceptFor("dGhlIHNhbXBsZSBub25jZQ=="))
+ }
+
+ @Test fun theRequestCarriesTheHeadersAndRefusesLineBreaks() {
+ val req = String(WsHandshake.request("relay.example.com", "/v1/room/AAAAAAAAAAAAAAAAAAAAAA?role=phone", "KEY", listOf("Authorization" to "Bearer abc", "Sec-WebSocket-Protocol" to "coucou.v1, coucou.join.x")))
+ assertTrue(req.startsWith("GET /v1/room/AAAAAAAAAAAAAAAAAAAAAA?role=phone HTTP/1.1\r\nHost: relay.example.com\r\n"))
+ assertTrue(req.contains("Upgrade: websocket\r\n") && req.contains("Sec-WebSocket-Version: 13\r\n") && req.contains("Authorization: Bearer abc\r\n"))
+ assertTrue(req.endsWith("\r\n\r\n"))
+ for (bad in listOf("a\r\nX: y", "a\nb", "a\u0000b")) {
+ try { WsHandshake.request("h", "/", "k", listOf("X" to bad)); fail() } catch (_: IllegalArgumentException) {}
+ }
+ try { WsHandshake.request("h", "/a b", "k", emptyList()); fail() } catch (_: IllegalArgumentException) {}
+ }
+
+ private fun response(status: String = "101 Switching Protocols", key: String = "KEY", extra: String = "", accept: String = WsHandshake.acceptFor("KEY"), protocol: String? = "coucou.v1"): ByteArray =
+ ("HTTP/1.1 $status\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $accept\r\n" +
+ (protocol?.let { "Sec-WebSocket-Protocol: $it\r\n" } ?: "") + extra + "\r\n").toByteArray()
+
+ @Test fun aCorrectResponseIsAcceptedAndNoFrameDataIsSwallowed() {
+ val after = byteArrayOf(0x81.toByte(), 2, 'o'.code.toByte(), 'k'.code.toByte())
+ val input = ByteArrayInputStream(response() + after)
+ assertEquals("coucou.v1", WsHandshake.readResponse(input, "KEY", setOf("coucou.v1")))
+ assertEquals("ok", (message(WsDecoder(input, 100).next()) as WsMessage.Text).text)
+ }
+
+ @Test fun everyWrongResponseIsRefusedWithItsStatus() {
+ fun status(bytes: ByteArray) = try { WsHandshake.readResponse(ByteArrayInputStream(bytes), "KEY", setOf("coucou.v1")); -1 } catch (e: WsHandshakeException) { e.status }
+ assertEquals(401, status("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".toByteArray()))
+ assertEquals(429, status("HTTP/1.1 429 Too Many Requests\r\n\r\n".toByteArray()))
+ assertEquals(404, status("HTTP/1.1 404 Not Found\r\n\r\n".toByteArray()))
+ assertEquals(101, status(response(accept = "wrong")))
+ assertEquals(101, status(response(protocol = "other")))
+ assertEquals(101, status(response(protocol = null)))
+ assertEquals(101, status(response(extra = "Sec-WebSocket-Extensions: permessage-deflate\r\n")))
+ assertEquals(101, status("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${WsHandshake.acceptFor("KEY")}\r\nSec-WebSocket-Protocol: coucou.v1\r\n\r\n".toByteArray()))
+ assertEquals(0, status("garbage\r\n\r\n".toByteArray()))
+ assertEquals(0, status("HTTP/1.1 101".toByteArray()))
+ assertEquals(0, status(ByteArray(WsHandshake.MAX_HEADER_BYTES + 100) { 'a'.code.toByte() }))
+ }
+
+ // ── relay addresses ──
+
+ @Test fun onlyAWssAddressWithNothingElseIsAccepted() {
+ assertEquals(RelayUrl(true, "relay.example.workers.dev", 443), RelayUrl.parse("wss://relay.example.workers.dev"))
+ assertEquals(RelayUrl(true, "relay.example.com", 8443), RelayUrl.parse(" wss://relay.example.com:8443/ "))
+ assertEquals("wss://relay.example.com:8443", RelayUrl.parse("wss://relay.example.com:8443")!!.display)
+ assertEquals("wss://relay.example.com", RelayUrl.parse("wss://relay.example.com")!!.display)
+ assertEquals(RelayUrl(false, "127.0.0.1", 8787), RelayUrl.parse("ws://127.0.0.1:8787"))
+ assertEquals(RelayUrl(false, "localhost", 8787), RelayUrl.parse("ws://localhost:8787"))
+ for (bad in listOf(
+ "", "relay.example.com", "https://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#f",
+ "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",
+ )) assertNull("$bad must be refused", RelayUrl.parse(bad))
+ }
+}
+
+/** Two frames of the same payload must not carry the same mask (the client draws a new one for each). */
+private object WsConnectionProbe {
+ fun maskedFramesDiffer(): Boolean {
+ val written = ByteArrayOutputStream()
+ val conn = WsConnection(java.net.Socket(), ByteArrayInputStream(ByteArray(0)), written, 1024, java.security.SecureRandom())
+ repeat(8) { conn.sendBinary(ByteArray(4)) }
+ val bytes = written.toByteArray()
+ val masks = (0 until 8).map { bytes.copyOfRange(it * 10 + 2, it * 10 + 6).toList() }
+ return masks.toSet().size > 1
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/mochi/OutfitEngineTest.kt b/android/app/src/test/kotlin/com/coucou/android/mochi/OutfitEngineTest.kt
new file mode 100644
index 00000000..105769ea
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/mochi/OutfitEngineTest.kt
@@ -0,0 +1,95 @@
+package com.coucou.android.mochi
+
+import com.coucou.android.mochi.outfit.Outfit
+import kotlin.random.Random
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** setOutfit and the soft-part physics, as in windows/src/mochi/engine.ts. */
+class OutfitEngineTest {
+ private class Clock { var ms = 10_000.0 }
+
+ private fun engine(clock: Clock) = MochiEngine({ clock.ms }, Random(1), SoundSink { })
+
+ private fun MochiEngine.run(clock: Clock, ms: Int) {
+ repeat(ms / 16) { clock.ms += 16; update(0.016) }
+ }
+
+ @Test fun mochiStartsUndressed() {
+ val e = engine(Clock())
+ assertEquals(Outfit.NONE, e.outfit)
+ assertEquals(0.0, e.outfitPresence, 0.0)
+ assertFalse(e.rigidRoll)
+ }
+
+ @Test fun anOutfitDropsInOver350msAndThenMochiSquashes() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.CROWN)
+ assertEquals("the outfit is chosen at once", Outfit.CROWN, e.outfit)
+ assertEquals(0.0, e.outfitPresence, 0.0)
+ e.run(clock, 160)
+ assertTrue(e.outfitPresence in 0.05..0.95)
+ e.run(clock, 240)
+ assertEquals(1.0, e.outfitPresence, 1e-9)
+ assertTrue("squash runs when it has landed", e.sy != 1.0 || e.sx != 1.0)
+ }
+
+ @Test fun anOutfitLeavesOver180msAndThenIsGone() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.BEANIE, animated = false)
+ assertEquals(1.0, e.outfitPresence, 0.0)
+ e.setOutfit(Outfit.NONE)
+ e.run(clock, 96)
+ assertTrue(e.outfitPresence in 0.01..0.99)
+ assertEquals("still drawn while it leaves", Outfit.BEANIE, e.outfit)
+ e.run(clock, 160)
+ assertEquals(Outfit.NONE, e.outfit)
+ assertEquals(0.0, e.outfitPresence, 1e-9)
+ }
+
+ @Test fun changingOutfitTakesTheOldOneOffFirst() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.BEANIE, animated = false)
+ e.setOutfit(Outfit.BOW)
+ assertEquals("the old one is still shown", Outfit.BEANIE, e.outfit)
+ e.run(clock, 208)
+ assertEquals(Outfit.BOW, e.outfit)
+ e.run(clock, 400)
+ assertEquals(1.0, e.outfitPresence, 1e-9)
+ }
+
+ @Test fun theSameOutfitTwiceChangesNothing() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.SCARF, animated = false)
+ e.setOutfit(Outfit.SCARF)
+ assertEquals(1.0, e.outfitPresence, 0.0)
+ }
+
+ @Test fun aVisibleOutfitMakesTheBodyRollAsOnePieceButAMiniNeverWearsOne() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.CROWN, animated = false)
+ assertTrue(e.rigidRoll)
+ val mini = engine(clock).also { it.isMini = true }
+ mini.setOutfit(Outfit.CROWN, animated = false)
+ assertFalse(mini.rigidRoll)
+ }
+
+ @Test fun aSlapSetsTheSoftPartsSwingingAndTheyCalmDown() {
+ val clock = Clock()
+ val e = engine(clock)
+ e.setOutfit(Outfit.SANTA_HAT, animated = false)
+ e.slap()
+ e.run(clock, 80)
+ assertTrue(e.busy)
+ assertTrue(Math.abs(e.physDy) > 0.001 || Math.abs(e.physDx) > 0.001)
+ e.run(clock, 6000)
+ assertTrue(Math.abs(e.physDx) < 0.05)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/Ctx2DTest.kt b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/Ctx2DTest.kt
new file mode 100644
index 00000000..4d361cda
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/Ctx2DTest.kt
@@ -0,0 +1,71 @@
+package com.coucou.android.mochi.outfit
+
+import kotlin.math.PI
+import kotlin.math.abs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class Ctx2DTest {
+ @Test fun cssColoursAreReadLikeTheBrowserDoes() {
+ assertEquals(Rgba(255.0, 255.0, 255.0, 1.0), Css.parse("#FFFFFF"))
+ assertEquals(Rgba(17.0, 34.0, 51.0, 1.0), Css.parse("#123"))
+ assertEquals(Rgba(26.0, 20.0, 18.0, 1.0), Css.parse("rgb(26,20,18)"))
+ assertEquals(Rgba(17.0, 19.0, 23.0, 0.82), Css.parse("rgba(17,19,23,0.82)"))
+ assertEquals(Rgba(150.0, 50.0, 0.0, 1.0E-7), Css.parse("rgba(150,50,0,1e-7)"))
+ assertEquals(Rgba(0.0, 0.0, 0.0, 0.0), Css.parse(" rgba( 0 , 0 , 0 , 0 ) "))
+ }
+
+ @Test fun arcToRoundsACornerTheWayTheBrowserDoes() {
+ // A square corner at (10, 0), coming from (0, 0), going down to (10, 10), radius 2.
+ val a = ArcToMath.compute(0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 2.0)
+ assertNotNull(a)
+ assertEquals(8.0, a!!.startX, 1e-9); assertEquals(0.0, a.startY, 1e-9)
+ assertEquals(10.0, a.endX, 1e-9); assertEquals(2.0, a.endY, 1e-9)
+ assertEquals(8.0, a.cx, 1e-9); assertEquals(2.0, a.cy, 1e-9)
+ assertEquals(PI / 2, a.sweep, 1e-9) // clockwise on screen (y down)
+ }
+
+ @Test fun arcToTurnsTheOtherWayForTheOtherCorner() {
+ val a = ArcToMath.compute(10.0, 0.0, 0.0, 0.0, 0.0, 10.0, 3.0)!!
+ assertEquals(-PI / 2, a.sweep, 1e-9)
+ assertEquals(3.0, a.cx, 1e-9); assertEquals(3.0, a.cy, 1e-9)
+ }
+
+ @Test fun arcToWithNoCornerIsALine() {
+ assertNull(ArcToMath.compute(0.0, 0.0, 5.0, 0.0, 10.0, 0.0, 2.0))
+ assertNull(ArcToMath.compute(0.0, 0.0, 5.0, 0.0, 10.0, 5.0, 0.0))
+ assertNull(ArcToMath.compute(0.0, 0.0, 0.0, 0.0, 10.0, 5.0, 1.0))
+ }
+
+ @Test fun anAcuteCornerKeepsTheTangentPointsAtEqualDistance() {
+ val a = ArcToMath.compute(0.0, 0.0, 10.0, 0.0, 0.0, 4.0, 1.5)!!
+ val d1 = Math.hypot(a.startX - 10.0, a.startY - 0.0)
+ val d2 = Math.hypot(a.endX - 10.0, a.endY - 0.0)
+ assertTrue(abs(d1 - d2) < 1e-9)
+ assertEquals(1.5, Math.hypot(a.startX - a.cx, a.startY - a.cy), 1e-9)
+ assertEquals(1.5, Math.hypot(a.endX - a.cx, a.endY - a.cy), 1e-9)
+ }
+
+ @Test fun styleStateComesBackAfterRestore() {
+ val ctx = Ctx2D(RecGfx())
+ ctx.fillStyle("#FF0000"); ctx.lineWidth = 3.0; ctx.lineCap = Cap.ROUND
+ ctx.save()
+ ctx.fillStyle("#00FF00"); ctx.lineWidth = 9.0; ctx.lineCap = Cap.BUTT
+ ctx.restore()
+ assertEquals(Solid(Rgba(255.0, 0.0, 0.0, 1.0)), ctx.fillStyle)
+ assertEquals(3.0, ctx.lineWidth, 0.0)
+ assertEquals(Cap.ROUND, ctx.lineCap)
+ }
+
+ @Test fun anAlmostOpaqueLayerIsAPlainSave() {
+ val rec = RecGfx()
+ Ctx2D(rec).withLayer(0.9995) { it.translate(1.0, 2.0) }
+ assertEquals("""[["save"],["translate",1,2],["restore"]]""", rec.result().toString())
+ val rec2 = RecGfx()
+ Ctx2D(rec2).withLayer(0.5) { it.translate(1.0, 2.0) }
+ assertEquals("""[["layer",0.5,[["save"],["translate",1,2],["restore"]]]]""", rec2.result().toString())
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/OutfitParityTest.kt b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/OutfitParityTest.kt
new file mode 100644
index 00000000..1822e731
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/OutfitParityTest.kt
@@ -0,0 +1,145 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.ReferenceFiles
+import java.io.File
+import java.util.concurrent.TimeUnit
+import kotlin.math.abs
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/** A [Gfx] that writes down what it was asked to draw, in the same JSON shape as android/tools/outfit-trace.mjs. */
+class RecGfx : Gfx {
+ private var ops = JSONArray()
+
+ fun result(): JSONArray = ops
+
+ private fun segs(p: Path2D) = JSONArray().also { a ->
+ for (s in p.segs) a.put(
+ when (s) {
+ is Seg.MoveTo -> arr("M", s.x, s.y)
+ is Seg.LineTo -> arr("L", s.x, s.y)
+ is Seg.QuadTo -> arr("Q", s.cx, s.cy, s.x, s.y)
+ is Seg.CubicTo -> arr("C", s.c1x, s.c1y, s.c2x, s.c2y, s.x, s.y)
+ is Seg.ArcTo -> arr("AT", s.x1, s.y1, s.x2, s.y2, s.r)
+ is Seg.Arc -> arr("A", s.x, s.y, s.r, s.a0, s.a1)
+ is Seg.Ellipse -> arr("E", s.x, s.y, s.rx, s.ry, s.rot, s.a0, s.a1)
+ is Seg.Rect -> arr("R", s.x, s.y, s.w, s.h)
+ Seg.Close -> arr("Z")
+ },
+ )
+ }
+
+ private fun rgba(c: Rgba) = listOf(c.r, c.g, c.b, c.a)
+ private fun stops(l: List<Stop>) = JSONArray().also { a -> l.forEach { a.put(JSONArray(listOf(it.offset) + rgba(it.c))) } }
+ private fun style(s: Style): JSONArray = when (s) {
+ is Solid -> JSONArray(listOf<Any>("solid") + rgba(s.c))
+ is LinearGradient -> JSONArray(listOf<Any>("lin", s.x0, s.y0, s.x1, s.y1, stops(s.stops)))
+ is RadialGradient -> JSONArray(listOf<Any>("rad", s.x, s.y, s.r0, s.r1, stops(s.stops)))
+ }
+
+ private fun arr(vararg v: Any) = JSONArray(v.toList())
+
+ override fun save() { ops.put(arr("save")) }
+ override fun restore() { ops.put(arr("restore")) }
+ override fun translate(x: Double, y: Double) { ops.put(arr("translate", x, y)) }
+ override fun scale(x: Double, y: Double) { ops.put(arr("scale", x, y)) }
+ override fun rotate(angle: Double) { ops.put(arr("rotate", angle)) }
+ override fun clip(path: Path2D, evenOdd: Boolean) { ops.put(arr("clip", segs(path), evenOdd)) }
+ override fun fill(path: Path2D, style: Style) { ops.put(arr("fill", segs(path), style(style))) }
+ override fun stroke(path: Path2D, style: Style, width: Double, cap: Cap, join: Join) {
+ ops.put(arr("stroke", segs(path), style(style), width, cap.name.lowercase(), join.name.lowercase()))
+ }
+ override fun layer(alpha: Double, block: () -> Unit) {
+ val outer = ops
+ ops = JSONArray()
+ block()
+ val inner = ops
+ ops = outer
+ ops.put(arr("layer", alpha, inner))
+ }
+}
+
+/**
+ * The Kotlin outfits against the TypeScript ones: android/tools/outfit-trace.mjs runs windows/src/mochi/outfits.ts
+ * on 297 cases (every outfit, five head poses, the fade and drop-in states, the wardrobe icons) and this test
+ * replays the same cases with the port and compares every drawing call, number by number. Skipped without node.
+ */
+class OutfitParityTest {
+ private fun node(): Boolean = try {
+ ProcessBuilder("node", "--version").redirectErrorStream(true).start().also { it.inputStream.readBytes() }.waitFor() == 0
+ } catch (_: Exception) { false }
+
+ private fun trace(): JSONArray {
+ assumeTrue("node not available", node())
+ val setup = ReferenceFiles.file("windows/tests/setup.mjs").absolutePath
+ val script = ReferenceFiles.file("android/tools/outfit-trace.mjs").absolutePath
+ val out = File.createTempFile("outfit-trace", ".json")
+ try {
+ val p = ProcessBuilder("node", "--import", setup, script).redirectOutput(out).redirectError(ProcessBuilder.Redirect.INHERIT)
+ .directory(ReferenceFiles.file("windows")).start()
+ assertTrue("trace timed out", p.waitFor(120, TimeUnit.SECONDS))
+ assertEquals("trace failed", 0, p.exitValue())
+ return JSONArray(out.readText())
+ } finally { out.delete() }
+ }
+
+ private fun replay(c: JSONObject): JSONArray {
+ val rec = RecGfx()
+ val ctx = Ctx2D(rec)
+ val outfit = Outfit.entries.first { it.id == c.getString("outfit") }
+ when (c.getString("kind")) {
+ "icon" -> drawIconMochi(ctx, c.getDouble("size"), outfit)
+ else -> {
+ val hd = c.getJSONObject("head")
+ val st = c.getJSONObject("state")
+ val h = makeHead(hd.getDouble("R"), hd.getDouble("yaw"), hd.getDouble("pitch"), hd.getDouble("physDx"), hd.getDouble("physDy"))
+ val s = OutfitState(st.getDouble("presence"), st.getDouble("morph"))
+ if (c.getString("kind") == "behind") drawOutfitBehind(ctx, outfit, h, s) else drawOutfitFront(ctx, outfit, h, s)
+ }
+ }
+ return rec.result()
+ }
+
+ private fun same(path: String, a: Any?, b: Any?) {
+ when {
+ a is JSONArray && b is JSONArray -> {
+ assertEquals("$path length", a.length(), b.length())
+ for (i in 0 until a.length()) same("$path[$i]", a.get(i), b.get(i))
+ }
+ a is Number && b is Number -> {
+ val x = a.toDouble()
+ val y = b.toDouble()
+ assertTrue("$path: $x vs $y", abs(x - y) <= 1e-7 * maxOf(1.0, abs(x), abs(y)))
+ }
+ else -> assertEquals(path, a, b)
+ }
+ }
+
+ @Test fun everyDrawingCallMatchesTheTypeScriptOriginal() {
+ val cases = trace()
+ assertTrue(cases.length() > 250)
+ var compared = 0
+ for (i in 0 until cases.length()) {
+ val c = cases.getJSONObject(i)
+ val label = "${c.getString("kind")} ${c.getString("outfit")} " + (c.optJSONObject("head")?.toString() ?: "") + (c.optJSONObject("state")?.toString() ?: "")
+ same(label, c.getJSONArray("ops"), replay(c))
+ compared += c.getJSONArray("ops").length()
+ }
+ assertTrue("only $compared calls compared", compared > 3_000)
+ }
+
+ @Test fun theTraceReallyDrawsSomething() {
+ val cases = trace()
+ val byOutfit = HashMap<String, Int>()
+ for (i in 0 until cases.length()) {
+ val c = cases.getJSONObject(i)
+ if (c.getString("kind") == "front" && c.getJSONArray("ops").length() > 0) byOutfit.merge(c.getString("outfit"), 1, Int::plus)
+ }
+ // Every outfit but the bunny ears (all of them behind the head) has a front.
+ assertEquals(10, byOutfit.size)
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeChoiceTest.kt b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeChoiceTest.kt
new file mode 100644
index 00000000..5d5880dc
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeChoiceTest.kt
@@ -0,0 +1,66 @@
+package com.coucou.android.mochi.outfit
+
+import java.io.File
+import java.time.LocalDate
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class WardrobeChoiceTest {
+ private val day = LocalDate.of(2026, 10, 10) // witch hat season
+
+ @Test fun followingTheComputerWearsWhatItSays() {
+ assertEquals("beanie", Wardrobe.choose(Wardrobe.FOLLOW, "beanie"))
+ assertEquals(Outfit.BEANIE, Wardrobe.resolve(Wardrobe.choose(Wardrobe.FOLLOW, "beanie"), day))
+ assertEquals(Outfit.WITCH_HAT, Wardrobe.resolve(Wardrobe.choose(Wardrobe.FOLLOW, "auto"), day))
+ }
+
+ @Test fun aChoiceOfTheUserBeatsTheComputer() {
+ assertEquals("crown", Wardrobe.choose("crown", "beanie"))
+ assertEquals(Outfit.NONE, Wardrobe.resolve(Wardrobe.choose("none", "beanie"), day))
+ assertEquals(Outfit.WITCH_HAT, Wardrobe.resolve(Wardrobe.choose("auto", "none"), day))
+ }
+
+ @Test fun garbageFromEitherSideIsHarmless() {
+ assertEquals("auto", Wardrobe.choose(Wardrobe.FOLLOW, "topHat"))
+ assertEquals("computer", Wardrobe.parseLocal("x"))
+ assertEquals(Outfit.NONE, Wardrobe.outfitOf("x"))
+ }
+
+ // The screens cannot be drawn in a JVM test, so these read the sources.
+ private fun src(name: String) = File("src/main/kotlin/com/coucou/android/$name").readText()
+
+ @Test fun theWardrobeIsOneTapFromSettingsAndGoesBackToSettings() {
+ assertTrue(src("ui/SettingsScreens.kt").contains("onWardrobe"))
+ assertTrue(src("MainActivity.kt").contains("Screen.WARDROBE -> WardrobeScreen"))
+ assertTrue(src("core/Navigation.kt").contains("Screen.HISTORY, Screen.GALLERY, Screen.WARDROBE, Screen.DIAGNOSTICS, Screen.LICENCES -> Screen.SETTINGS"))
+ }
+
+ @Test fun everyWardrobeValueHasAnEnglishName() {
+ val xml = File("src/main/res/values/strings.xml").readText()
+ for (id in Wardrobe.SELECTIONS) assertTrue("outfit_$id", xml.contains("name=\"outfit_$id\""))
+ val screen = src("ui/WardrobeScreen.kt")
+ for (id in Wardrobe.SELECTIONS.filter { it != "bunnyEars" }) assertTrue(id, screen.contains("\"$id\" -> R.string.outfit_$id"))
+ }
+
+ @Test fun theIconsAreDrawnByTheSameCodeAsTheBigMochi() {
+ val screen = src("ui/WardrobeScreen.kt")
+ assertTrue(screen.contains("drawIconMochi("))
+ assertTrue(src("mochi/MochiPainter.kt").contains("drawOutfitFront(") && src("mochi/MochiPainter.kt").contains("drawOutfitBehind("))
+ }
+
+ @Test fun homeDressesTheHeroAndOnlyTheHero() {
+ val main = src("MainActivity.kt")
+ assertTrue(main.contains("engine.setOutfit("))
+ assertEquals("only the hero's engine is dressed", 2, Regex("""setOutfit\(""").findAll(main).count())
+ assertFalse(src("mochi/MochiEngine.kt").contains("isMini) outfit"))
+ }
+
+ @Test fun nothingAboutTheOutfitLeavesThePhone() {
+ for (f in listOf("ui/WardrobeScreen.kt", "mochi/outfit/Wardrobe.kt")) {
+ val s = src(f)
+ assertFalse(f, s.contains("Log.") || s.contains("Socket") || s.contains("http"))
+ }
+ }
+}
diff --git a/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeTest.kt b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeTest.kt
new file mode 100644
index 00000000..b5f1d8d3
--- /dev/null
+++ b/android/app/src/test/kotlin/com/coucou/android/mochi/outfit/WardrobeTest.kt
@@ -0,0 +1,83 @@
+package com.coucou.android.mochi.outfit
+
+import com.coucou.android.ReferenceFiles
+import java.time.LocalDate
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Mirrors windows/tests/wardrobe.test.mjs so the phone and the PC dress Mochi alike. */
+class WardrobeTest {
+ private fun season(y: Int, m: Int, d: Int) = Wardrobe.seasonal(LocalDate.of(y, m, d))
+
+ @Test fun witchHatFromOctoberFirstToNovemberFirst() {
+ assertEquals(Outfit.NONE, season(2026, 9, 30))
+ assertEquals(Outfit.WITCH_HAT, season(2026, 10, 1))
+ assertEquals(Outfit.WITCH_HAT, season(2026, 10, 31))
+ assertEquals(Outfit.WITCH_HAT, season(2026, 11, 1))
+ assertEquals(Outfit.NONE, season(2026, 11, 2))
+ }
+
+ @Test fun santaHatFromDecemberFirstToTwentySixth() {
+ assertEquals(Outfit.NONE, season(2026, 11, 30))
+ assertEquals(Outfit.SANTA_HAT, season(2026, 12, 1))
+ assertEquals(Outfit.SANTA_HAT, season(2026, 12, 26))
+ assertEquals(Outfit.NONE, season(2026, 12, 27))
+ }
+
+ @Test fun partyHatAroundNewYear() {
+ assertEquals(Outfit.NONE, season(2026, 12, 30))
+ assertEquals(Outfit.PARTY_HAT, season(2026, 12, 31))
+ assertEquals(Outfit.PARTY_HAT, season(2027, 1, 1))
+ assertEquals(Outfit.PARTY_HAT, season(2027, 1, 2))
+ assertEquals(Outfit.NONE, season(2027, 1, 3))
+ }
+
+ @Test fun sunglassesFromJuneTwentyFirstToAugustThirtyFirst() {
+ assertEquals(Outfit.NONE, season(2026, 6, 20))
+ assertEquals(Outfit.SUNGLASSES, season(2026, 6, 21))
+ assertEquals(Outfit.SUNGLASSES, season(2026, 8, 31))
+ assertEquals(Outfit.NONE, season(2026, 9, 1))
+ }
+
+ @Test fun easterDatesAreRight() {
+ assertEquals(4 to 5, Wardrobe.easterDate(2026))
+ assertEquals(3 to 31, Wardrobe.easterDate(2024))
+ assertEquals(4 to 20, Wardrobe.easterDate(2025))
+ assertEquals(4 to 9, Wardrobe.easterDate(2023))
+ }
+
+ @Test fun bunnyEarsTwoDaysBeforeEasterToTheDayAfter() {
+ // Easter 2026 is April 5.
+ assertEquals(Outfit.NONE, season(2026, 4, 2))
+ assertEquals(Outfit.BUNNY_EARS, season(2026, 4, 3))
+ assertEquals(Outfit.BUNNY_EARS, season(2026, 4, 5))
+ assertEquals(Outfit.BUNNY_EARS, season(2026, 4, 6))
+ assertEquals(Outfit.NONE, season(2026, 4, 7))
+ }
+
+ @Test fun unknownStoredValuesMeanAuto() {
+ assertEquals("auto", Wardrobe.parse(null))
+ assertEquals("auto", Wardrobe.parse("topHat"))
+ assertEquals("auto", Wardrobe.parse(""))
+ for (s in Wardrobe.SELECTIONS) assertEquals(s, Wardrobe.parse(s))
+ }
+
+ @Test fun autoFollowsTheSeasonAndAnythingElseIsWornAsChosen() {
+ assertEquals(Outfit.WITCH_HAT, Wardrobe.resolve("auto", LocalDate.of(2026, 10, 10)))
+ assertEquals(Outfit.CROWN, Wardrobe.resolve("crown", LocalDate.of(2026, 10, 10)))
+ assertEquals(Outfit.NONE, Wardrobe.resolve("none", LocalDate.of(2026, 10, 10)))
+ }
+
+ @Test fun theListsAreTheSameAsOnTheComputer() {
+ val ts = ReferenceFiles.read("windows/src/mochi/wardrobe.ts")
+ val body = ts.substringAfter("export const OUTFIT_SELECTIONS = [").substringBefore("] as const")
+ val ids = Regex("\"(\\w+)\"").findAll(body).map { it.groupValues[1] }.toList()
+ assertEquals(ids, Wardrobe.SELECTIONS)
+ assertEquals(Wardrobe.SELECTIONS.toSet(), Wardrobe.LABELS.keys)
+ // Every outfit of the drawing code has a stored id, and every stored id but "auto" is an outfit.
+ assertEquals(Wardrobe.SELECTIONS.filter { it != "auto" }.toSet(), Outfit.entries.map { it.id }.toSet())
+ for (id in ids) if (id != "auto") assertTrue(Wardrobe.outfitOf(id).id == id)
+ for ((id, label) in Wardrobe.LABELS) assertTrue("$id: $label", ts.contains("N_(\"$label\")"))
+ }
+}
diff --git a/android/app/src/test/resources/test-desktop.p12 b/android/app/src/test/resources/test-desktop.p12
new file mode 100644
index 00000000..8aa60417
Binary files /dev/null and b/android/app/src/test/resources/test-desktop.p12 differ
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
new file mode 100644
index 00000000..1b4481ac
--- /dev/null
+++ b/android/build.gradle.kts
@@ -0,0 +1,5 @@
+plugins {
+ id("com.android.application") version "8.7.3" apply false
+ id("org.jetbrains.kotlin.android") version "2.0.21" apply false
+ id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
+}
diff --git a/android/gradle.properties b/android/gradle.properties
new file mode 100644
index 00000000..1a8c9bcd
--- /dev/null
+++ b/android/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g
+android.useAndroidX=true
+kotlin.code.style=official
diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 00000000..a4b76b95
Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..df97d72b
--- /dev/null
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/android/gradlew b/android/gradlew
new file mode 100755
index 00000000..f5feea6d
--- /dev/null
+++ b/android/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/android/gradlew.bat b/android/gradlew.bat
new file mode 100644
index 00000000..9d21a218
--- /dev/null
+++ b/android/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/android/i18n/app-strings.json b/android/i18n/app-strings.json
new file mode 100644
index 00000000..d28c0f48
--- /dev/null
+++ b/android/i18n/app-strings.json
@@ -0,0 +1,257 @@
+{
+ "_about": "English source for the Android app (English only). Edit this file, then run: node android/scripts/gen-strings.mjs . Placeholders are %1$s style.",
+ "strings": {
+ "app_name": "Coucou for Android",
+ "about_unofficial": "Coucou for Android, by Rhytam Biswas. Part of Coucou by Louis Raillé.",
+ "about_repo": "github.com/Louis-CFM/coucou",
+ "licences_title": "Licences",
+ "licences_intro": "The code of Coucou is MIT-licensed. The name, the character, the icon and the sounds are Louis Raillé's and are not. The libraries are listed with their licence.",
+ "about_assets": "The name Coucou, the Mochi character, the icon and the sounds are © Louis Raillé and used with permission. The Android code is © Rhytam Biswas, released under the MIT License.",
+ "action_allow": "Allow",
+ "action_deny": "Deny",
+ "action_close": "Close",
+ "widget_description": "Shows whether your agents are working, without opening Coucou.",
+ "status_connected": "Connected",
+ "status_connecting": "Connecting…",
+ "status_not_connected": "Not connected",
+ "demo_mode": "Demo mode",
+ "demo_try": "Try demo mode",
+ "pair_button": "Pair",
+ "approval_title": "Approval needed",
+ "action_unpair": "Disconnect this computer",
+ "demo_leave": "Leave demo mode",
+ "gallery": "Mochi gallery",
+ "pair_paste_short": "Paste the link",
+ "pairing_headline": "Connect to your computer",
+ "pairing_help": "On your computer open Coucou, then Settings, Android phone, and scan the code it shows.",
+ "pairing_footer": "Coucou for Android, by Rhytam Biswas.",
+ "pairing_about": "About",
+ "paste_title": "Paste the pairing link",
+ "paste_hint": "Copy it from Coucou on your computer (Settings, Android phone).",
+ "approval_later": "Not now",
+ "approval_wants": "Wants to %1$s",
+ "approval_too_long": "Command is longer than shown",
+ "approval_on_computer": "Answer this request on your computer. Allow is not offered here, because the whole command cannot be shown on the phone.",
+ "approval_caution": "Allow only if you asked for this.",
+ "approval_show_cmd": "Show exact command",
+ "approval_hide_cmd": "Hide exact command",
+ "question_title": "%1$s has a question",
+ "question_body": "Answer it on your computer. To answer here, turn on \"Let the phone answer Claude Code's questions\" in Coucou on your computer (Settings > Android phone).",
+ "question_see_answer": "Answer the question",
+ "question_position": "Question %1$d of %2$d",
+ "question_pick_many": "Pick one or more",
+ "question_next": "Next",
+ "question_back": "Back",
+ "question_send": "Send answer",
+ "question_confirm_title": "Send your answer",
+ "question_sent": "Answer sent",
+ "question_not_sent": "The answer could not be sent. Your computer may have answered already.",
+ "question_see": "See the question",
+ "question_ok": "OK",
+ "home_running": "%1$d running",
+ "home_empty_title": "Nothing is running",
+ "home_empty_hint": "Start an agent on your computer and it shows up here.",
+ "recent_title": "Recent",
+ "recent_all": "See all",
+ "status_looking": "Looking for your computer…",
+ "discovery_title": "Can't find your computer",
+ "discovery_body": "Is the phone on the same Wi-Fi as the computer? Is the computer awake, with Coucou running and the phone link on, and does Windows allow Coucou on private networks? Some hotspots and guest networks block devices from finding each other (client isolation).",
+ "discovery_pair_again": "Pair again",
+ "discovery_enter_address": "Enter address manually",
+ "address_title": "Computer address",
+ "address_hint": "For example 192.168.1.20 or 192.168.1.20:47821. Your pairing stays as it is: only the address changes.",
+ "address_save": "Use this address",
+ "address_bad": "That is not a valid address.",
+ "chat_off_not_paired_title": "Not connected",
+ "chat_off_not_paired_body": "Pair your computer first, then you can chat through it.",
+ "chat_off_offline_title": "Not connected",
+ "chat_off_offline_body": "Your computer cannot be reached right now. Check that it is on, with Coucou running, on the same Wi-Fi.",
+ "chat_off_title": "Chat is off on your computer",
+ "chat_nomodel_title": "Your computer has no model allowed for the phone yet",
+ "chat_off_hint": "On your computer open Coucou > Settings > Android phone, turn on \"Let the phone chat with my AI providers\" and tick a model.",
+ "chat_go_pair": "Connect to your computer",
+ "chat_go_settings": "Open Settings",
+ "tab_home": "Home",
+ "tab_chat": "Chat",
+ "tab_settings": "Settings",
+ "design_note": "The building blocks of the new look. No other screen uses them yet.",
+ "pair_clipboard": "Paste from clipboard",
+ "notif_unlock": "Unlock to see the request",
+ "msg_not_pending": "That request is no longer pending.",
+ "msg_bad_link": "That is not a Coucou pairing link.",
+ "msg_rejected": "The desktop rejected this phone. Pair again.",
+ "msg_link_error": "Link error",
+ "msg_need_lock": "Set a screen lock to approve from your phone.",
+ "approval_hint": "Allow on the phone asks for the fingerprint or the screen lock. Deny does not.",
+ "overlay_title": "Show Mochi over other apps",
+ "overlay_hint": "An island drops from the top of the screen while an agent works, then goes back up.",
+ "msg_overlay_permission": "Allow “display over other apps” for Coucou, then come back.",
+ "settings_title": "Settings",
+ "settings_sound": "Mochi's sounds",
+ "settings_volume": "Volume",
+ "notify_done": "When an agent finishes or fails",
+ "notify_done_hint": "A quiet notice in the notification shade, and the pill if it is on. Permission requests and questions always notify you.",
+ "quiet_hours": "Quiet hours",
+ "quiet_hint": "No sound and no pill for finished or failed agents. Requests and questions still come through.",
+ "quiet_from": "From",
+ "quiet_to": "To",
+ "history_title": "Activity",
+ "history_empty": "Your decisions will appear here. They stay on this phone.",
+ "history_today": "Today",
+ "history_yesterday": "Yesterday",
+ "history_clear": "Clear history",
+ "history_note": "Kept only on this phone, never sent anywhere.",
+ "action_back": "Back",
+ "notif_finished": "Finished",
+ "notif_error": "Stopped on an error",
+ "notif_question": "Has a question",
+ "notif_ratelimit": "Hit a usage limit",
+ "island_answer_on_pc": "Tap to open Coucou, or answer on your computer",
+ "state_ready": "Ready",
+ "state_working": "Working",
+ "state_thinking": "Thinking",
+ "state_searching": "Searching",
+ "state_approval": "Waiting for your OK",
+ "state_question": "Has a question",
+ "state_error": "Error",
+ "state_finished": "Finished",
+ "state_ratelimit": "Limit reached",
+ "state_sleeping": "Sleeping",
+ "state_dizzy": "Dizzy",
+ "agent_kind": "Agent",
+ "link_pair": "Pair with your computer",
+ "link_approval": "Review request",
+ "overlay_missing": "Allow “display over other apps” so the island can show.",
+ "overlay_allow": "Allow",
+ "settings_section_computer": "Computer",
+ "settings_section_away": "Away from home Wi-Fi",
+ "relay_use": "Use the relay when I'm away",
+ "relay_use_hint": "Reaches your computer from mobile data or another network, through the relay you set up. Everything stays end-to-end encrypted. The direct link is always tried first.",
+ "relay_line_none": "This pairing has no relay. On your computer, turn on Away from home Wi-Fi in Settings, then scan the new code.",
+ "relay_line_off": "The relay is off. Coucou only connects when your computer is on this network.",
+ "relay_line_direct": "Connected directly on this network.",
+ "relay_line_via": "Connected through your relay (%1$s).",
+ "relay_line_waiting": "Looking for your computer. It will use the relay if it is not on this network.",
+ "relay_line_access": "The relay refused the access key. Check it in Settings on your computer.",
+ "relay_line_taken": "This pairing is in use somewhere else. Pair again from your computer.",
+ "relay_line_rate": "The relay is limiting connections for now. Trying again soon.",
+ "relay_line_unreachable": "Cannot reach the relay. Check your internet connection.",
+ "relay_line_away": "Your computer is not answering through the relay. It may be asleep or have the relay off.",
+ "settings_section_sound": "Sound",
+ "settings_section_notices": "Notices",
+ "settings_section_display": "Display",
+ "settings_section_more": "More",
+ "settings_section_about": "About",
+ "settings_computer_none": "No computer connected yet. You can pair one from the Home screen.",
+ "action_cancel": "Cancel",
+ "chat_title": "Chat",
+ "chat_note": "Uses your computer's API key. Your computer sends your messages to the provider you pick; the key never reaches this phone.",
+ "chat_empty": "Ask anything. Your message goes to the model you pick above the box.",
+ "chat_placeholder": "Ask me anything…",
+ "chat_send": "Send",
+ "chat_stop": "Stop",
+ "chat_clear": "Clear",
+ "chat_clear_title": "Clear this chat?",
+ "chat_clear_body": "This removes the conversation from this phone and tells your computer to forget it.",
+ "chat_model": "Model: %1$s",
+ "chat_count": "%1$d / %2$d",
+ "chat_ref_too_long": "That message is too long.",
+ "chat_ref_no_model": "Pick a model first.",
+ "chat_ref_busy": "Wait for the answer to finish, or stop it.",
+ "chat_ref_offline": "Not connected to your computer.",
+ "chat_err_off": "Chat is turned off on your computer.",
+ "chat_err_not_allowed": "That model is not allowed for the phone.",
+ "chat_err_busy": "Another answer is still being written.",
+ "chat_err_rate": "Too many messages. Try again in a few minutes.",
+ "chat_err_too_long": "The message is too long.",
+ "chat_err_empty": "Nothing to send.",
+ "chat_err_no_key": "Your computer has no key for that provider.",
+ "chat_err_unreachable": "Your computer could not reach the provider.",
+ "chat_err_auth": "The provider refused your computer's key.",
+ "chat_err_provider": "The provider returned an error.",
+ "chat_err_canceled": "Stopped.",
+ "chat_err_internal": "Something went wrong.",
+ "chat_err_connection": "The connection to your computer was lost.",
+ "chat_err_interrupted": "Stopped when the app closed.",
+ "session_details": "Details",
+ "session_last": "Last message",
+ "session_steps": "Steps",
+ "session_step_working": "Working",
+ "session_step_done": "Step done",
+ "session_no_steps": "No steps yet.",
+ "session_hint": "Turn on “Show session details on the phone” in your computer's Settings to see the steps and the last message here.",
+ "session_ended": "This session is no longer running.",
+ "session_project": "Project: %1$s",
+ "scan_button": "Scan QR code",
+ "scan_title": "Scan QR code",
+ "scan_hint": "Point the camera at the code in your computer's Settings → Android phone.",
+ "scan_not_pairing": "That is not a Coucou pairing code",
+ "scan_why": "Coucou uses the camera only on this screen, to read the pairing code. Nothing is saved or sent.",
+ "scan_allow": "Allow camera",
+ "scan_blocked": "The camera is off for Coucou. Turn it on in Android's settings, or paste the link instead.",
+ "scan_open_settings": "Open settings",
+ "scan_paste_instead": "Paste the link instead",
+ "scan_camera_error": "The camera could not start. Paste the link instead.",
+ "pair_confirm_title": "Pair with %1$s?",
+ "pair_confirm_body": "%1$s:%2$d on your network. Only pair with a computer you own.",
+ "pair_confirm_relay": "It can also reach your computer from other networks through the relay at %1$s. Only pair if you set up that relay yourself.",
+ "pair_confirm_replace": "This replaces the computer you are connected to now.",
+ "pair_confirm_ok": "Pair",
+ "wardrobe_title": "Mochi's wardrobe",
+ "wardrobe_note": "Choose what Mochi wears on this phone.",
+ "wardrobe_follow": "Same as my computer",
+ "wardrobe_follow_hint": "Mochi wears what you chose in Coucou on your computer.",
+ "wardrobe_auto_tag": "AUTO",
+ "wardrobe_selected": "Selected",
+ "outfit_auto": "Auto (seasons)",
+ "outfit_none": "None",
+ "outfit_partyHat": "Party hat",
+ "outfit_beanie": "Beanie",
+ "outfit_crown": "Crown",
+ "outfit_sunglasses": "Sunglasses",
+ "outfit_roundGlasses": "Round glasses",
+ "outfit_bow": "Bow",
+ "outfit_scarf": "Scarf",
+ "outfit_witchHat": "Witch hat",
+ "outfit_pumpkin": "Pumpkin",
+ "outfit_santaHat": "Santa hat",
+ "outfit_bunnyEars": "Bunny ears",
+ "files_heading": "Files changed",
+ "files_counts": "+%1$d −%2$d",
+ "files_new": "New file",
+ "file_loading": "Loading the changes…",
+ "file_failed": "Could not load this change. Check the connection and try again.",
+ "file_gone": "This change is no longer available on your computer.",
+ "file_too_large": "This change is too large to show line by line.",
+ "file_truncated": "Only the first 200 lines are shown.",
+ "file_empty": "Nothing to show.",
+ "file_close": "Close",
+ "file_summary": "+%1$d added, −%2$d removed",
+ "usage_title": "Plan usage",
+ "usage_claude": "Claude",
+ "usage_codex": "Codex",
+ "usage_five_hours": "5 hours",
+ "usage_week": "Week",
+ "usage_pct": "%1$d%%",
+ "usage_resets_now": "Resetting…",
+ "usage_resets_hm": "Resets in %1$d h %2$d",
+ "usage_resets_m": "Resets in %1$d min",
+ "usage_resets_week": "Resets %1$s",
+ "usage_credits": "%1$d free resets available",
+ "usage_desc": "%1$s, %2$s: %3$d percent used",
+ "services_title": "Services",
+ "diag_title": "Can't connect?",
+ "diag_intro": "These checks find where the connection breaks. Nothing secret is shown or copied: the report hides the pairing code, the fingerprint, the computer's name and its full address.",
+ "diag_run": "Check again",
+ "diag_running": "Checking…",
+ "diag_copy": "Copy report",
+ "diag_copied": "Report copied",
+ "diag_ok": "OK",
+ "diag_problem": "Problem",
+ "diag_skipped": "Not checked",
+ "battery_title": "Keep the connection while the screen is off",
+ "battery_body": "Android pauses background apps to save battery. If requests stop reaching you when the phone is locked, let Coucou run without restrictions. This is only a suggestion.",
+ "battery_open": "Open settings",
+ "battery_not_now": "Not now"
+ }
+}
diff --git a/android/relay/.gitignore b/android/relay/.gitignore
new file mode 100644
index 00000000..c4d2db01
--- /dev/null
+++ b/android/relay/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+.wrangler/
+.dev.vars
+.env
diff --git a/android/relay/.npmrc b/android/relay/.npmrc
new file mode 100644
index 00000000..521a9f7c
--- /dev/null
+++ b/android/relay/.npmrc
@@ -0,0 +1 @@
+legacy-peer-deps=true
diff --git a/android/relay/README.md b/android/relay/README.md
new file mode 100644
index 00000000..d781f049
--- /dev/null
+++ b/android/relay/README.md
@@ -0,0 +1,81 @@
+# Coucou link relay
+
+A tiny, key-less Cloudflare Worker that lets *Coucou for Android* and a desktop Coucou sync over the internet, from
+different networks, with no VPN and no shared Wi-Fi. **It is separate from Louis's `relay/`** (which holds an APNs key and
+only does iPhone Live Activities) and is deployed by you, on your own Cloudflare account.
+
+The wire is specified in `docs/RELAY_LINK.md`; the reasoning is in `android/RELAY_PLAN.md`; the step-by-step deploy and the phone-on-mobile-data test are in `docs/RELAY_DEPLOY.md`.
+
+## What it does, and what it cannot do
+
+- Both the computer and the phone open **outbound** WebSockets to it. It forwards each binary frame to the other peer of the
+ room, as it is. Everything inside is end-to-end encrypted by the two apps; **the relay never sees a content key**.
+- It stores nothing (no KV, no R2, no database, no storage call), logs nothing (observability is off), has no accounts, and
+ never buffers a frame: a frame for an absent peer is dropped.
+- It holds exactly **one secret**, the access key, which only lets a request create or join a room. Without it the relay
+ refuses everything (fail closed).
+- Operator and Cloudflare can see IP addresses, that a pairing exists, when each side is online, and padded frame sizes and
+ timing. They cannot read sessions, commands, paths, approvals or chat.
+
+## Deploy (once)
+
+You need a free Cloudflare account and Node 22 or newer.
+
+```
+cd android/relay
+npm install
+npx wrangler login
+# 1. Make a random access key (43 characters) and keep it for the next step and for the computer's setting:
+openssl rand -base64 32 | tr '+/' '-_' | tr -d '='
+# 2. Store it as a secret (it prompts for the value; it is never written to a file or to git):
+npx wrangler secret put ACCESS_KEY
+# 3. Deploy:
+npx wrangler deploy
+```
+
+`deploy` prints the URL, like `https://coucou-link.<you>.workers.dev`. Check it: `curl https://coucou-link.<you>.workers.dev/`
+answers `Coucou link relay`. Use the `wss://` form of that URL and the access key in the computer's settings (a later stage).
+
+Wrangler itself (Cloudflare's tool, not this relay or the apps) may send anonymous usage statistics; turn that off with
+`export WRANGLER_SEND_METRICS=false` if you prefer.
+
+Nothing in `wrangler.toml` is secret. Do not add `ACCESS_KEY` to it, to `.dev.vars` in git, or to any file you commit.
+
+## Rotating the access key
+
+1. Make a new key (command above) and run `npx wrangler secret put ACCESS_KEY` with it.
+2. Paste the same value in the computer's setting. New connections with the old key are refused at once; sockets that are
+ already open are closed at their next frame. The computer then sends the new key to your paired phones inside the
+ encrypted channel, so they do not have to scan again.
+3. If a key leaked, rotate. It protects your free quota, not your data (that is protected by the pairing key).
+
+## Free-tier limits and what happens when they run out
+
+Written from memory of Cloudflare's published limits; check their pages: Workers and Durable Objects each allow about 100,000
+requests a day on the free plan, incoming WebSocket messages count at roughly 1/20 of a request, and an idle room costs almost
+nothing because it hibernates. A setup of one computer and one phone uses a few hundred "requests" a day. If the quota is
+exhausted, Cloudflare refuses requests until the daily reset: the app says "Relay unavailable" and keeps working over the home
+network; nothing is lost because nothing is stored. The paid Workers plan (about $5 a month) removes the cap.
+
+## Self-hosting
+
+`tools/dev-relay.ts` is the same relay in plain Node (it shares `src/protocol.ts` with the Worker and is checked by the same
+behaviour tests). It speaks `ws://`, so put a TLS terminator in front of it on the internet.
+
+```
+npm install
+ACCESS_KEY=<your key> PORT=8787 node tools/dev-relay.ts
+```
+
+Without `ACCESS_KEY` it refuses every room request.
+
+## Develop and test
+
+```
+npm install # .npmrc sets legacy-peer-deps (the Workers test plugin's peer range)
+npm run typecheck
+npm test # the behaviour suite in workerd (Miniflare) and against the Node twin, the guards, the vectors
+npm run vectors # test-vectors.json is up to date (shared with the Rust and Kotlin code)
+```
+
+`wrangler dev` runs the Worker locally; set `ACCESS_KEY` for it with a `.dev.vars` file (git-ignored).
diff --git a/android/relay/package-lock.json b/android/relay/package-lock.json
new file mode 100644
index 00000000..bd8d96a9
--- /dev/null
+++ b/android/relay/package-lock.json
@@ -0,0 +1,2789 @@
+{
+ "name": "coucou-link-relay",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "coucou-link-relay",
+ "devDependencies": {
+ "@cloudflare/vitest-plugin": "1.4.0",
+ "@cloudflare/workers-types": "5.20261010.1",
+ "@types/node": "^22.0.0",
+ "@types/ws": "^8.5.0",
+ "typescript": "^5.6.0",
+ "vitest": "4.1.11",
+ "wrangler": "4.149.0",
+ "ws": "^8.18.0"
+ }
+ },
+ "node_modules/@cloudflare/kv-asset-handler": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",
+ "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/@cloudflare/unenv-preset": {
+ "version": "2.16.2",
+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz",
+ "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "peerDependencies": {
+ "unenv": "2.0.0-rc.24",
+ "workerd": ">1.20260305.0 <2.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "workerd": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@cloudflare/vitest-plugin": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@cloudflare/vitest-plugin/-/vitest-plugin-1.4.0.tgz",
+ "integrity": "sha512-SgIhyhpVH+2MVSJxidG8gosqrpzF25IwKevQhPykwulTgAFe4s0Nkj71pNzqCkwV2+A4NKkHJP2ReyyRsoIxsg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cjs-module-lexer": "1.2.3",
+ "esbuild": "0.28.2",
+ "miniflare": "5.20261006.1-alpha",
+ "wrangler": "4.149.0",
+ "zod": "4.6.5"
+ },
+ "peerDependencies": {
+ "vitest": "^4.1.0 || ^5.0.0"
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-64": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261006.1.tgz",
+ "integrity": "sha512-lCX6avJO2It9AyDEYitjmOtJRVp/xmaW0TziyoLAnfxlzozyyRbSFfIIMMCiDx/sTP1++E4VLbV+7BHSD33f0Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-darwin-arm64": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261006.1.tgz",
+ "integrity": "sha512-PyFGjOaldtppnLuKsdkoYWXfLVpDjuf8u+uoykX+1Xvxo2EPmCVViq0iDKm+U7c7PRno85ehS3/MPVXyk2HwHw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-64": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261006.1.tgz",
+ "integrity": "sha512-Ntf9S8eesmVufdjaT2kzWlz6Ng9XGYTc6cHQVRKAg59lFufwsIabGeMT6U4KkrpEeSIxgHq8aPtuLbZXE19tCA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-linux-arm64": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261006.1.tgz",
+ "integrity": "sha512-JyeDBymVWw5tVRebSsVE8ojDYxd6UlZrAseHU8G+NpIyd5wF61tXlF/axLeCUqu0pOhBFHb8I5QKi0jwrCK41Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workerd-windows-64": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261006.1.tgz",
+ "integrity": "sha512-nWP0URNqOBN9fa/gZ7eh/w051DwjOXN8j4lDZDYVXyQPsux6sV3DfyYZT+CjR/rt9nKBSmJT9QE9/bWT18+84w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@cloudflare/workers-types": {
+ "version": "5.20261010.1",
+ "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20261010.1.tgz",
+ "integrity": "sha512-Csvu2Wsd8JWnP8HNg/uAAEYzoGw+eKEvoftoHrbMWuFDoC0g6e5XSP8XO9vJsdjjVpPaURdFoL3g/xpZSdQr3Q==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0"
+ },
+ "node_modules/@cspotcode/source-map-support": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.9"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.3"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.0.3",
+ "@jridgewell/sourcemap-codec": "^1.4.10"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.153.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz",
+ "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@poppinss/colors": {
+ "version": "4.1.6",
+ "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "kleur": "^4.1.5"
+ }
+ },
+ "node_modules/@poppinss/dumper": {
+ "version": "0.6.5",
+ "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",
+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/colors": "^4.1.5",
+ "@sindresorhus/is": "^7.0.2",
+ "supports-color": "^10.0.0"
+ }
+ },
+ "node_modules/@poppinss/exception": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",
+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz",
+ "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz",
+ "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz",
+ "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz",
+ "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz",
+ "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz",
+ "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz",
+ "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz",
+ "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz",
+ "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz",
+ "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz",
+ "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz",
+ "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz",
+ "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz",
+ "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz",
+ "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@sindresorhus/is": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sindresorhus/is?sponsor=1"
+ }
+ },
+ "node_modules/@speed-highlight/core": {
+ "version": "1.2.24",
+ "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",
+ "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "22.20.5",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
+ "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.2",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
+ "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
+ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
+ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.11",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
+ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
+ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.11",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
+ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
+ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
+ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.11",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/blake3-wasm": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
+ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/chai": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/cjs-module-lexer": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz",
+ "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cookie": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/error-stack-parser-es": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/kleur": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/miniflare": {
+ "version": "5.20261006.1-alpha",
+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261006.1-alpha.tgz",
+ "integrity": "sha512-6ylv8tamkrspDI2R/cAYfv+YWmfGNdXe76Pi9TauEUWsFVXn3LNF9Yk8oduzf1a+TYsSRYTqlOE7+nGGRsMHdw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "0.8.1",
+ "sharp": "0.35.5",
+ "undici": "7.29.1",
+ "workerd": "1.20261006.1",
+ "ws": "8.21.0",
+ "youch": "4.1.0-beta.10"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
+ },
+ "node_modules/miniflare/node_modules/ws": {
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.29",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.19",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz",
+ "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.153.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.13",
+ "@rolldown/binding-android-arm64": "1.2.13",
+ "@rolldown/binding-darwin-arm64": "1.2.13",
+ "@rolldown/binding-darwin-x64": "1.2.13",
+ "@rolldown/binding-freebsd-x64": "1.2.13",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.13",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.13",
+ "@rolldown/binding-linux-arm64-musl": "1.2.13",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.13",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.13",
+ "@rolldown/binding-linux-x64-gnu": "1.2.13",
+ "@rolldown/binding-linux-x64-musl": "1.2.13",
+ "@rolldown/binding-openharmony-arm64": "1.2.13",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.13",
+ "@rolldown/binding-win32-x64-msvc": "1.2.13"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.5",
+ "@img/sharp-darwin-x64": "0.35.5",
+ "@img/sharp-freebsd-wasm32": "0.35.5",
+ "@img/sharp-libvips-darwin-arm64": "1.3.4",
+ "@img/sharp-libvips-darwin-x64": "1.3.4",
+ "@img/sharp-libvips-linux-arm": "1.3.4",
+ "@img/sharp-libvips-linux-arm64": "1.3.4",
+ "@img/sharp-libvips-linux-ppc64": "1.3.4",
+ "@img/sharp-libvips-linux-riscv64": "1.3.4",
+ "@img/sharp-libvips-linux-s390x": "1.3.4",
+ "@img/sharp-libvips-linux-x64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
+ "@img/sharp-linux-arm": "0.35.5",
+ "@img/sharp-linux-arm64": "0.35.5",
+ "@img/sharp-linux-ppc64": "0.35.5",
+ "@img/sharp-linux-riscv64": "0.35.5",
+ "@img/sharp-linux-s390x": "0.35.5",
+ "@img/sharp-linux-x64": "0.35.5",
+ "@img/sharp-linuxmusl-arm64": "0.35.5",
+ "@img/sharp-linuxmusl-x64": "0.35.5",
+ "@img/sharp-webcontainers-wasm32": "0.35.5",
+ "@img/sharp-win32-arm64": "0.35.5",
+ "@img/sharp-win32-ia32": "0.35.5",
+ "@img/sharp-win32-x64": "0.35.5"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/supports-color": {
+ "version": "10.2.2",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/supports-color?sponsor=1"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz",
+ "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici": {
+ "version": "7.29.1",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",
+ "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unenv": {
+ "version": "2.0.0-rc.24",
+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",
+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pathe": "^2.0.3"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.4",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz",
+ "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.29",
+ "rolldown": "~1.2.12",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
+ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.11",
+ "@vitest/mocker": "4.1.11",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/runner": "4.1.11",
+ "@vitest/snapshot": "4.1.11",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.11",
+ "@vitest/browser-preview": "4.1.11",
+ "@vitest/browser-webdriverio": "4.1.11",
+ "@vitest/coverage-istanbul": "4.1.11",
+ "@vitest/coverage-v8": "4.1.11",
+ "@vitest/ui": "4.1.11",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/workerd": {
+ "version": "1.20261006.1",
+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261006.1.tgz",
+ "integrity": "sha512-8MadBuffZ5NdpLwZjUmsqT5QlaKXq4gjgT6wzcKeynZTICNXyePhc+5QVoKiK7+MMhFTLNrRO2KXLlpk8Q6BkA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "workerd": "bin/workerd"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "@cloudflare/workerd-darwin-64": "1.20261006.1",
+ "@cloudflare/workerd-darwin-arm64": "1.20261006.1",
+ "@cloudflare/workerd-linux-64": "1.20261006.1",
+ "@cloudflare/workerd-linux-arm64": "1.20261006.1",
+ "@cloudflare/workerd-windows-64": "1.20261006.1"
+ }
+ },
+ "node_modules/wrangler": {
+ "version": "4.149.0",
+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.149.0.tgz",
+ "integrity": "sha512-OzK7xmB5r5iLKb3cIT3783g13fe6T7xyeKu9LEdUyl+DKAM2KP/jkjnE0OUhyw+mB/XJM9ycjgF3MWm8PR9amg==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@cloudflare/kv-asset-handler": "0.5.0",
+ "@cloudflare/unenv-preset": "2.16.2",
+ "blake3-wasm": "2.1.5",
+ "esbuild": "0.28.2",
+ "miniflare": "5.20261006.1-alpha",
+ "path-to-regexp": "6.3.0",
+ "unenv": "2.0.0-rc.24",
+ "workerd": "1.20261006.1"
+ },
+ "bin": {
+ "cf-wrangler": "bin/cf-wrangler.js",
+ "wrangler": "bin/wrangler.js",
+ "wrangler2": "bin/wrangler.js"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.3"
+ },
+ "peerDependencies": {
+ "@cloudflare/workers-types": "^5.20261006.1"
+ },
+ "peerDependenciesMeta": {
+ "@cloudflare/workers-types": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.22.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/youch": {
+ "version": "4.1.0-beta.10",
+ "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",
+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/colors": "^4.1.5",
+ "@poppinss/dumper": "^0.6.4",
+ "@speed-highlight/core": "^1.2.7",
+ "cookie": "^1.0.2",
+ "youch-core": "^0.3.3"
+ }
+ },
+ "node_modules/youch-core": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",
+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@poppinss/exception": "^1.2.2",
+ "error-stack-parser-es": "^1.0.5"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/android/relay/package.json b/android/relay/package.json
new file mode 100644
index 00000000..8519f0c1
--- /dev/null
+++ b/android/relay/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "coucou-link-relay",
+ "private": true,
+ "description": "Key-less WebSocket relay for the Coucou Android link (docs/RELAY_LINK.md). Deployed by the user on their own Cloudflare account.",
+ "type": "module",
+ "scripts": {
+ "dev": "wrangler dev",
+ "deploy": "wrangler deploy",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run -c vitest.config.ts && vitest run -c vitest.node.config.ts",
+ "vectors": "node tools/gen-vectors.mjs --check"
+ },
+ "devDependencies": {
+ "@cloudflare/workers-types": "5.20261010.1",
+ "@types/node": "^22.0.0",
+ "@types/ws": "^8.5.0",
+ "typescript": "^5.6.0",
+ "vitest": "4.1.11",
+ "wrangler": "4.149.0",
+ "ws": "^8.18.0",
+ "@cloudflare/vitest-plugin": "1.4.0"
+ }
+}
diff --git a/android/relay/src/index.ts b/android/relay/src/index.ts
new file mode 100644
index 00000000..4516fef3
--- /dev/null
+++ b/android/relay/src/index.ts
@@ -0,0 +1,40 @@
+// Coucou link relay: a stateless Cloudflare Worker (docs/RELAY_LINK.md).
+//
+// It forwards opaque, end-to-end encrypted frames between the two peers of a room, a computer and a phone. It never sees a
+// content key, stores nothing (no KV, no R2, no database, no storage API call), logs nothing (observability off) and has
+// no accounts. The one secret it holds is the deploy-time ACCESS_KEY, which only lets a request create or join a room.
+//
+// This file answers the HTTP side and refuses everything that is not a well-formed, authorised room request BEFORE a room
+// (a Durable Object) is created or contacted.
+
+import { accessKeyOk, parseJoinProof, parseRoomRequest } from "./protocol";
+export { Room } from "./room";
+
+export interface Env {
+ ROOM: DurableObjectNamespace;
+ /** Set with `wrangler secret put ACCESS_KEY`. Never in git. Unset: every room request is refused (fail closed). */
+ ACCESS_KEY?: string;
+ /** Optional Workers Rate Limiting binding: new connections per source address. */
+ CONNECT_LIMIT?: { limit(options: { key: string }): Promise<{ success: boolean }> };
+}
+
+const empty = (status: number) => new Response(null, { status });
+
+export default {
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url);
+ if (url.pathname === "/") {
+ return request.method === "GET" ? new Response("Coucou link relay", { status: 200, headers: { "content-type": "text/plain" } }) : empty(405);
+ }
+ const target = request.method === "GET" ? parseRoomRequest(url) : null;
+ if (!target) return empty(404); // bad path, bad room id, bad role, wrong method: nothing is created
+ if (env.CONNECT_LIMIT) {
+ const ip = request.headers.get("CF-Connecting-IP") ?? "unknown";
+ if (!(await env.CONNECT_LIMIT.limit({ key: ip })).success) return empty(429);
+ }
+ if (!(await accessKeyOk(env.ACCESS_KEY, request.headers.get("Authorization")))) return empty(401);
+ if (!parseJoinProof(request.headers.get("Sec-WebSocket-Protocol"))) return empty(400);
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return empty(426);
+ return env.ROOM.get(env.ROOM.idFromName(target.room)).fetch(request);
+ },
+};
diff --git a/android/relay/src/protocol.ts b/android/relay/src/protocol.ts
new file mode 100644
index 00000000..9ea1f968
--- /dev/null
+++ b/android/relay/src/protocol.ts
@@ -0,0 +1,108 @@
+// The relay's rules that do not depend on Cloudflare: shared by the Worker (index.ts, room.ts) and by the Node twin
+// (tools/dev-relay.ts), so both enforce exactly the same things. Erasable TypeScript only (Node runs it as it is).
+// The wire is specified in docs/RELAY_LINK.md.
+
+export const MAX_FRAME = 66_000; // bytes; a v1 line is at most 65,536 plus a header, a tag and padding
+export const RATE_PER_SECOND = 30;
+export const RATE_BURST = 60;
+export const ROOM_ID = /^[A-Za-z0-9_-]{22}$/;
+export const B64URL_32 = /^[A-Za-z0-9_-]{43}$/;
+export const SUBPROTOCOL = "coucou.v1";
+const JOIN_PREFIX = "coucou.join.";
+
+export type Role = "pc" | "phone";
+export const otherRole = (r: Role): Role => (r === "pc" ? "phone" : "pc");
+
+/** `/v1/room/<22 chars>` with `?role=pc|phone`, or null (the caller answers 404 and touches nothing). */
+export function parseRoomRequest(url: URL): { room: string; role: Role } | null {
+ const m = /^\/v1\/room\/([^/]+)$/.exec(url.pathname);
+ if (!m || !ROOM_ID.test(m[1])) return null;
+ const role = url.searchParams.get("role");
+ if (role !== "pc" && role !== "phone") return null;
+ return { room: m[1], role };
+}
+
+/** The access key from `Authorization: Bearer …`, or null. */
+export function bearer(header: string | null): string | null {
+ const m = /^Bearer ([A-Za-z0-9_-]{16,128})$/.exec(header ?? "");
+ return m ? m[1] : null;
+}
+
+/** The join proof from the offered sub-protocols (`coucou.v1, coucou.join.<43 chars>`), or null. */
+export function parseJoinProof(header: string | null): string | null {
+ if (!header) return null;
+ const offered = header.split(",").map((s) => s.trim());
+ if (!offered.includes(SUBPROTOCOL)) return null;
+ const join = offered.filter((s) => s.startsWith(JOIN_PREFIX));
+ if (join.length !== 1) return null;
+ const proof = join[0].slice(JOIN_PREFIX.length);
+ return B64URL_32.test(proof) ? proof : null;
+}
+
+export function fromBase64Url(s: string): Uint8Array {
+ const b = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
+ return Uint8Array.from(b, (c) => c.charCodeAt(0));
+}
+
+export const toHex = (b: ArrayBuffer | Uint8Array) =>
+ [...new Uint8Array(b instanceof Uint8Array ? b : b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+async function sha256(data: Uint8Array | string): Promise<Uint8Array> {
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes as BufferSource));
+}
+
+/** Constant-time equality of the SHA-256 digests of two strings (their lengths are not revealed). */
+export async function sameSecret(a: string, b: string): Promise<boolean> {
+ const [x, y] = await Promise.all([sha256(a), sha256(b)]);
+ let diff = 0;
+ for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
+ return diff === 0;
+}
+
+/** Is this request's access key the configured one? Fails closed when none is configured (or it is too short to be a key). */
+export async function accessKeyOk(configured: string | undefined, header: string | null): Promise<boolean> {
+ const sent = bearer(header);
+ if (!configured || configured.length < 16 || !sent) return false;
+ return sameSecret(sent, configured);
+}
+
+/** Tags a socket with the access key it was admitted under (first 8 bytes of its SHA-256, hex). */
+export async function accessGeneration(configured: string | undefined): Promise<string> {
+ if (!configured) return "";
+ return toHex((await sha256(configured)).subarray(0, 8));
+}
+
+/** SHA-256 of the 32 raw bytes behind a join proof, as hex: what a room remembers in memory while it has a live socket. */
+export async function joinVerifier(proof: string): Promise<string> {
+ return toHex(await sha256(fromBase64Url(proof)));
+}
+
+/** A token bucket with an injectable clock. */
+export class Bucket {
+ private tokens: number;
+ private last: number;
+ private readonly perSecond: number;
+ private readonly burst: number;
+ private readonly now: () => number;
+ // Plain fields, not constructor parameter properties: the Node twin runs this file with Node's type stripping,
+ // which only accepts erasable syntax.
+ constructor(perSecond: number, burst: number, now: () => number = Date.now) {
+ this.perSecond = perSecond;
+ this.burst = burst;
+ this.now = now;
+ this.tokens = burst;
+ this.last = now();
+ }
+ take(): boolean {
+ const t = this.now();
+ this.tokens = Math.min(this.burst, this.tokens + ((t - this.last) / 1000) * this.perSecond);
+ this.last = t;
+ if (this.tokens < 1) return false;
+ this.tokens -= 1;
+ return true;
+ }
+}
+
+export const PEER_ONLINE = '{"peer":"online"}';
+export const PEER_OFFLINE = '{"peer":"offline"}';
diff --git a/android/relay/src/room.ts b/android/relay/src/room.ts
new file mode 100644
index 00000000..eff6c765
--- /dev/null
+++ b/android/relay/src/room.ts
@@ -0,0 +1,137 @@
+// One room = one Durable Object, named by the room id. At most one live socket per role (pc, phone); frames from one go to
+// the other as they are. It never parses, buffers or stores a frame. Hibernation API: an idle room costs nothing.
+//
+// Everything it remembers lives in the sockets' attachments (hibernation state, not storage): the role, the join verifier
+// and the access-key generation the socket was admitted under. When the last socket is gone, nothing is left.
+
+import { DurableObject } from "cloudflare:workers";
+import type { Env } from "./index";
+import {
+ Bucket, MAX_FRAME, PEER_OFFLINE, PEER_ONLINE, RATE_BURST, RATE_PER_SECOND, SUBPROTOCOL,
+ accessGeneration, joinVerifier, otherRole, parseJoinProof, parseRoomRequest,
+ type Role,
+} from "./protocol";
+
+interface Attachment {
+ role: Role;
+ verifier: string;
+ gen: string;
+ replaced?: boolean;
+}
+
+const OPEN = 1;
+
+export class Room extends DurableObject<Env> {
+ /** Token buckets live in memory only: a room that hibernated has no flood in progress. */
+ private readonly buckets = new Map<WebSocket, Bucket>();
+
+ constructor(ctx: DurableObjectState, env: Env) {
+ super(ctx, env);
+ // The platform answers this itself, without waking the room: the clients' heartbeat.
+ ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));
+ }
+
+ async fetch(request: Request): Promise<Response> {
+ const target = parseRoomRequest(new URL(request.url));
+ const proof = parseJoinProof(request.headers.get("Sec-WebSocket-Protocol"));
+ if (!target || !proof || request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response(null, { status: 400 });
+
+ const verifier = await joinVerifier(proof);
+ const gen = await accessGeneration(this.env.ACCESS_KEY);
+ const live = this.live();
+ const wrongProof = live.length > 0 && attachmentOf(live[0]).verifier !== verifier;
+
+ const pair = new WebSocketPair();
+ const [client, server] = [pair[0], pair[1]];
+ if (wrongProof) {
+ // The room is held by someone else's key. Accept, then say why, so the client can show "room is taken".
+ server.accept();
+ server.close(1008, "join proof");
+ return new Response(null, { status: 101, webSocket: client, headers: { "Sec-WebSocket-Protocol": SUBPROTOCOL } });
+ }
+
+ // A new socket for a role replaces the old one of that role.
+ for (const old of live) {
+ const att = attachmentOf(old);
+ if (att.role === target.role) {
+ old.serializeAttachment({ ...att, replaced: true });
+ old.close(1000, "replaced");
+ }
+ }
+
+ this.ctx.acceptWebSocket(server, [target.role]);
+ server.serializeAttachment({ role: target.role, verifier, gen } satisfies Attachment);
+ if (this.peerOf(target.role, server)) {
+ server.send(PEER_ONLINE);
+ this.peerOf(target.role, server)?.send(PEER_ONLINE);
+ }
+ return new Response(null, { status: 101, webSocket: client, headers: { "Sec-WebSocket-Protocol": SUBPROTOCOL } });
+ }
+
+ async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
+ const att = attachmentOf(ws);
+ // The key the socket was admitted under must still be the configured one (rotation closes live sockets here).
+ if (!att.gen || att.gen !== (await accessGeneration(this.env.ACCESS_KEY))) {
+ ws.close(1008, "access key changed");
+ return;
+ }
+ // "ping" never gets here (the platform answers it). Nothing else may be text.
+ if (typeof message === "string") {
+ ws.close(1003, "binary only");
+ return;
+ }
+ if (message.byteLength > MAX_FRAME) {
+ ws.close(1009, "too big");
+ return;
+ }
+ let bucket = this.buckets.get(ws);
+ if (!bucket) this.buckets.set(ws, (bucket = new Bucket(RATE_PER_SECOND, RATE_BURST)));
+ if (!bucket.take()) {
+ ws.close(1008, "rate");
+ return;
+ }
+ const peer = this.peerOf(att.role, ws);
+ if (!peer) {
+ ws.send(PEER_OFFLINE); // nothing is buffered: the frame is dropped
+ return;
+ }
+ peer.send(message);
+ }
+
+ async webSocketClose(ws: WebSocket, code: number, _reason: string, _wasClean: boolean): Promise<void> {
+ this.gone(ws);
+ try {
+ ws.close(code >= 1000 && code <= 1011 && code !== 1005 && code !== 1006 ? code : 1000, "");
+ } catch {
+ /* already closed */
+ }
+ }
+
+ async webSocketError(ws: WebSocket): Promise<void> {
+ this.gone(ws);
+ }
+
+ // ── helpers ────────────────────────────────────────────────────────────────────
+
+ private live(): WebSocket[] {
+ return this.ctx.getWebSockets().filter((w) => w.readyState === OPEN && !attachmentOf(w).replaced);
+ }
+
+ private peerOf(role: Role, except: WebSocket): WebSocket | undefined {
+ return this.ctx.getWebSockets(otherRole(role)).find((w) => w !== except && w.readyState === OPEN && !attachmentOf(w).replaced);
+ }
+
+ /** A socket left: forget its bucket, and tell the other side unless the same role is still here (a replacement). */
+ private gone(ws: WebSocket): void {
+ this.buckets.delete(ws);
+ const att = attachmentOf(ws);
+ if (att.replaced) return;
+ const sameRoleStillHere = this.ctx.getWebSockets(att.role).some((w) => w !== ws && w.readyState === OPEN && !attachmentOf(w).replaced);
+ if (sameRoleStillHere) return;
+ this.peerOf(att.role, ws)?.send(PEER_OFFLINE);
+ }
+}
+
+function attachmentOf(ws: WebSocket): Attachment {
+ return (ws.deserializeAttachment() ?? { role: "pc", verifier: "", gen: "" }) as Attachment;
+}
diff --git a/android/relay/test-vectors.json b/android/relay/test-vectors.json
new file mode 100644
index 00000000..34ae4135
--- /dev/null
+++ b/android/relay/test-vectors.json
@@ -0,0 +1,215 @@
+{
+ "_about": "Generated by android/relay/tools/gen-vectors.mjs. Do not edit by hand: change the script and regenerate. All byte strings are lowercase hex unless noted.",
+ "version": 1,
+ "label": "coucou-relay/v1",
+ "frameTypes": {
+ "init": 1,
+ "accept": 2,
+ "data": 3
+ },
+ "directions": {
+ "p2h": 1,
+ "h2p": 2
+ },
+ "rfc5869_a1": {
+ "ikm": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
+ "salt": "000102030405060708090a0b0c",
+ "info": "f0f1f2f3f4f5f6f7f8f9",
+ "length": 42,
+ "okm": "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
+ },
+ "inputs": {
+ "key": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "roomBytes": "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
+ "room": "oKGio6SlpqeoqaqrrK2urw",
+ "nPhone": "404142434445464748494a4b4c4d4e4f",
+ "nPc": "606162636465666768696a6b6c6d6e6f"
+ },
+ "derived": {
+ "kAuth": "b90415a0b01277ef3c2a977ab590c7742a20e417594852389803878fd3a209cb",
+ "kJoin": "546f9013ca6f8a7c824bd86aba705f9a56daa753a1307a6970ad1e0ceca671f2",
+ "joinVerifier": "b7eb4bc0a777b749e1203a08081f45860917461f8a8f19f9b00190cda9027b42",
+ "kP2H": "1797305ab1e68474f1162257ff692f3f4aa3782297ae6286b5fdd18c4fe7f3cb",
+ "kH2P": "97e12f747a35627cf356fee6d64a41beb512036792cc1f7f7143e4db4c9a2a89"
+ },
+ "init": {
+ "macInput": "696e69746f4b47696f36536c7071656f71617172724b32757277404142434445464748494a4b4c4d4e4f",
+ "mac": "8808bd267ebcbf32b8ca67234c5d73aa71b9467f0120bcdd0f9184920b27907a",
+ "frame": "01010000000000000000404142434445464748494a4b4c4d4e4f8808bd267ebcbf32b8ca67234c5d73aa71b9467f0120bcdd0f9184920b27907a"
+ },
+ "accept": {
+ "macInput": "6163636570746f4b47696f36536c7071656f71617172724b32757277404142434445464748494a4b4c4d4e4f606162636465666768696a6b6c6d6e6f",
+ "mac": "c8f9d3fd8fd232ca557ac4323a9721e1f5ed2b9c96e9fc0039e03a66739e6b69",
+ "frame": "01020000000000000000606162636465666768696a6b6c6d6e6fc8f9d3fd8fd232ca557ac4323a9721e1f5ed2b9c96e9fc0039e03a66739e6b69"
+ },
+ "data": [
+ {
+ "dir": "p2h",
+ "counter": 0,
+ "line": "{\"type\":\"hello\",\"v\":1,\"token\":\"TOKEN-for-tests-only\",\"device\":\"Test phone\"}",
+ "nonce": "010000000000000000000000",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b327572770101030000000000000000",
+ "plaintext": "0000004b7b2274797065223a2268656c6c6f222c2276223a312c22746f6b656e223a22544f4b454e2d666f722d74657374732d6f6e6c79222c22646576696365223a22546573742070686f6e65227d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5"
+ },
+ {
+ "dir": "h2p",
+ "counter": 0,
+ "line": "{\"type\":\"welcome\",\"v\":1,\"desktop\":\"Test PC\",\"os\":\"linux\"}",
+ "nonce": "020000000000000000000000",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b327572770201030000000000000000",
+ "plaintext": "000000397b2274797065223a2277656c636f6d65222c2276223a312c226465736b746f70223a2254657374205043222c226f73223a226c696e7578227d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "01030000000000000000edc43a5c4ddebb6993394c806ca5ee8520259a26e931e2f4dc5e77c6beecddae8d13b9d5ee149e465bfa7c3fc51d0ba017e63e76e69554f11f685a3aae8728dfc3d569a433ad66134805e42e7a5cd641b66d111d87fcb3eada83cc52c38b3bf31fd17a4a6188e5fe9dd6c0b24706aeb9c4be7e50ee7159659a146301dba406e9cd9a704c14c75c662b101b51a1ec916e"
+ },
+ {
+ "dir": "p2h",
+ "counter": 1,
+ "line": "{\"type\":\"ping\"}",
+ "nonce": "010000000000000000000001",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b327572770101030000000000000001",
+ "plaintext": "0000000f7b2274797065223a2270696e67227d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "010300000000000000016c6706e98fa99d94ebb73eff2ef34c7d4b8c85aa774cf5e13850f4a81a3aed47bf90762bd8281860d7437c44fca8796108e941db5f4e2550ea8cbbe240d9870ab4a6fabbdcbe71d62d4c044c705fd385669315d4cfa3d988fb9bff80f1dd33604691a9e3d120cfd13d7ddf68f5a389a3480de4cec99d1933bcc25e7dedd6bb2d333cbded0d16707cc384dcdd8d8d1c34"
+ },
+ {
+ "dir": "h2p",
+ "counter": 1,
+ "line": "{\"type\":\"sessions\",\"sessions\":[{\"pillId\":\"integration_claude\",\"agent\":\"Claude Code\",\"state\":\"working\",\"statusText\":\"step 0\",\"stepIndex\":0,\"stepCount\":9,\"updatedAt\":1760000000000},{\"pillId\":\"integration_claude\",\"agent\":\"Claude Code\",\"state\":\"working\",\"statusText\":\"step 1\",\"stepIndex\":1,\"stepCount\":9,\"updatedAt\":1760000000001},{\"pillId\":\"integration_claude\",\"agent\":\"Claude Code\",\"state\":\"working\",\"statusText\":\"step 2\",\"stepIndex\":2,\"stepCount\":9,\"updatedAt\":1760000000002}]}",
+ "nonce": "020000000000000000000001",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b327572770201030000000000000001",
+ "plaintext": "000001dc7b2274797065223a2273657373696f6e73222c2273657373696f6e73223a5b7b2270696c6c4964223a22696e746567726174696f6e5f636c61756465222c226167656e74223a22436c6175646520436f6465222c227374617465223a22776f726b696e67222c2273746174757354657874223a22737465702030222c2273746570496e646578223a302c2273746570436f756e74223a392c22757064617465644174223a313736303030303030303030307d2c7b2270696c6c4964223a22696e746567726174696f6e5f636c61756465222c226167656e74223a22436c6175646520436f6465222c227374617465223a22776f726b696e67222c2273746174757354657874223a22737465702031222c2273746570496e646578223a312c2273746570436f756e74223a392c22757064617465644174223a313736303030303030303030317d2c7b2270696c6c4964223a22696e746567726174696f6e5f636c61756465222c226167656e74223a22436c6175646520436f6465222c227374617465223a22776f726b696e67222c2273746174757354657874223a22737465702032222c2273746570496e646578223a322c2273746570436f756e74223a392c22757064617465644174223a313736303030303030303030327d5d7d0000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "01030000000000000001d0a7e6664d97d4623d424c2bde6e0d2b49785d4125e72d05b8f8ab3be8e96cabe0c11371574c779f2767c6614d55fc1f9f9c854a1026eb38c0200623db0fa998a9afbb05b8a9fb169573521cdcd61d7aa15152aed44b9b10e3d58cfe9c5dcf36544bf96b89647dc388e2c8a4741cd2d4786944d91e362d5c6ca21e3313f39a6f8119493a8da20c1c65e4caeb15a35b111eef913a5b16abe91c3f762d31deb51db500f861757a9bc45108d0f9699df06be54fe81d67ea7d1dfa0b89c85e0a25ef6646248f2fe2ba83cf3be0af0403a76ac340af957bdcecf5a66746427447d643b3830c2799451c612c165fc220d9175651ec39b6094bf9d715a0955b1cb7526b18203cdd1ca7e12770076af384f1f855ff8a20a68fdd482d992023c07ff2adcacf5ff65069f617bf6740dd367c52c52c15af4eb5da4446079c3fb94756d5d956dc63004b37e6e2c7ef603d339fb5be019372ca60395d94979af9b328abc3ae6cbd0acb1cbda89c5c2cbcdea8c172708e2d495304850913ebf37d723dd58e9c8822d1874a15a0e0784bf8f6c5fbc228333094bf351bc20bbfb96510224a104b2a20dbbe56a556680355fdace125900a10161317e5371db7d3c31f91927f11878644030aae0809c50aa5dad8387ada91da7a6feb14be985eb63a06600335498f7df33f310b34e84f5da47e696389dfa48381fcb141e6f85546087fee59875d4864563d2e1af35732ae315692c1d3f90774"
+ },
+ {
+ "dir": "h2p",
+ "counter": 2,
+ "line": "{\"type\":\"pong\"}",
+ "nonce": "020000000000000000000002",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b327572770201030000000000000002",
+ "plaintext": "0000000f7b2274797065223a22706f6e67227d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "01030000000000000002b64eb5905c1d0614d08ce87dd53ba18394f49f3582376df507b2e429bd1d7f4ce9ffde555b5b0c196bb89bff82e33e44232733711cc65355b06684e7ffd770eb447038aa8fbaa7c7538d4a7b265fa9b956599b1cc36aadb5f931727702dd7aa4382a04ba0782b11fed4da52b05ee5601feb51d7f439760ffb2137edb05be17cb3ab05379df1254bdb02115c0fec93f76"
+ },
+ {
+ "dir": "p2h",
+ "counter": 4294967295,
+ "line": "{\"type\":\"ping\"}",
+ "nonce": "0100000000000000ffffffff",
+ "aad": "636f75636f752d72656c61792f76316f4b47696f36536c7071656f71617172724b3275727701010300000000ffffffff",
+ "plaintext": "0000000f7b2274797065223a2270696e67227d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "frame": "010300000000ffffffff3d3b9c0b23c6b2efa7303bd2fce959b6e8a520d95c32cfb00659563aeeb9174ed217c53f294d09f22f914d8abdebbb21a106f8661f44cb9f7b4a4c4ce90b52b818ea87e3c44c435a3f292acc6a5d56989bba3f1923e7f5841e49524a8c15c0f0ffe2af3b046d992c060b0a6326b723fcf65582088d15d225509bce425206b744337f80c6869fbcc19d0ce1cb3b7eb2a7"
+ }
+ ],
+ "mustRefuse": [
+ {
+ "name": "a bit flipped in the ciphertext",
+ "dir": "p2h",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad3f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "a bit flipped in the tag",
+ "dir": "p2h",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e4",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "the counter in the header changed",
+ "dir": "p2h",
+ "frame": "01030000000000000001a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "the frame type changed",
+ "dir": "p2h",
+ "frame": "01020000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_header"
+ },
+ {
+ "name": "an unknown version",
+ "dir": "p2h",
+ "frame": "00030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_header"
+ },
+ {
+ "name": "a phone frame presented as a computer frame (reflection)",
+ "dir": "h2p",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "truncated",
+ "dir": "p2h",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "shorter than a header and a tag",
+ "dir": "p2h",
+ "frame": "01030000000000000000a58157b665dc562ae9cb",
+ "expect": "bad_header"
+ },
+ {
+ "name": "another room",
+ "dir": "p2h",
+ "room": "sLGys7S1tre4ubq7vL2-vw",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_tag"
+ },
+ {
+ "name": "another key",
+ "dir": "p2h",
+ "key": "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
+ "frame": "01030000000000000000a58157b665dc562ae9cb08417780d937a468a3fe8bf15dca77c85a66294c918281fd57f4dcd93782e91270587fa86980ee7798dcf8ec6a825772bcd2716ccf4fc7c5f8d2dfe316f7d8e6a05b2542255c3dd3682fb122e32e9995a2393a813fa91d8cd50d8ebd9db4f4e1fda75f4abccf638e34c1c470f23d8a62392ad2f9d165304786d0b72cab85213c03e1cc6867e5",
+ "expect": "bad_tag"
+ }
+ ],
+ "mustRefuseInOrder": [
+ {
+ "name": "the same frame twice (replay)",
+ "dir": "p2h",
+ "counters": [
+ 0,
+ 0
+ ],
+ "accepted": [
+ true,
+ false
+ ]
+ },
+ {
+ "name": "a frame going back",
+ "dir": "p2h",
+ "counters": [
+ 0,
+ 1,
+ 0
+ ],
+ "accepted": [
+ true,
+ true,
+ false
+ ]
+ },
+ {
+ "name": "a gap (a frame was dropped)",
+ "dir": "p2h",
+ "counters": [
+ 0,
+ 2
+ ],
+ "accepted": [
+ true,
+ false
+ ]
+ },
+ {
+ "name": "the first frame is not counter 0",
+ "dir": "p2h",
+ "counters": [
+ 1
+ ],
+ "accepted": [
+ false
+ ]
+ }
+ ]
+}
diff --git a/android/relay/tests/behaviour.ts b/android/relay/tests/behaviour.ts
new file mode 100644
index 00000000..bdcea37e
--- /dev/null
+++ b/android/relay/tests/behaviour.ts
@@ -0,0 +1,226 @@
+// One behaviour suite, run against the Worker (inside workerd, tests/worker.relay.test.ts) and against the Node twin
+// (tests/node.relay.test.ts). The same expectations hold for both, so the twin that the Rust and Kotlin clients are tested
+// against really behaves like the relay that is deployed.
+
+import { describe, expect, it, afterAll, beforeAll } from "vitest";
+
+export const ACCESS = "test-access-key-test-access-key-0123456789";
+export const OTHER_ACCESS = "another-access-key-another-access-key-9876543210";
+
+export type Msg =
+ | { kind: "binary"; data: Uint8Array }
+ | { kind: "text"; data: string }
+ | { kind: "close"; code: number; reason: string };
+
+export interface Conn {
+ next(timeoutMs?: number): Promise<Msg>;
+ /** Resolves true if nothing arrives within `ms`. */
+ quiet(ms?: number): Promise<boolean>;
+ send(data: Uint8Array | string): void;
+ close(code?: number, reason?: string): void;
+}
+
+export interface Options {
+ key?: string | null; // null: no Authorization header
+ protocols?: string; // the whole Sec-WebSocket-Protocol offer
+ proof?: string; // join proof only (builds the offer)
+}
+
+export interface Harness {
+ http(path: string, method?: string): Promise<{ status: number; text: string }>;
+ connect(room: string, role: string, options?: Options): Promise<Conn | { refused: number }>;
+ setAccessKey(key: string | undefined): Promise<void>;
+ /** Rooms that exist (Node: with a live socket; Worker: objects ever created in this test file). */
+ roomsCreated(): Promise<number>;
+ stop(): Promise<void>;
+}
+
+export const randomRoom = () => Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url");
+export const proofOf = (seed: number) => Buffer.from(new Uint8Array(32).fill(seed)).toString("base64url");
+export const offer = (proof: string) => `coucou.v1, coucou.join.${proof}`;
+const isConn = (c: Conn | { refused: number }): c is Conn => !("refused" in c);
+
+export async function open(h: Harness, room: string, role: string, o: Options = {}): Promise<Conn> {
+ const c = await h.connect(room, role, o);
+ if (!isConn(c)) throw new Error(`refused with ${c.refused}`);
+ return c;
+}
+
+export function behaviour(name: string, make: () => Promise<Harness>) {
+ describe(`${name}: the relay`, () => {
+ let h: Harness;
+ beforeAll(async () => {
+ h = await make();
+ });
+ afterAll(async () => {
+ await h.stop();
+ });
+
+ const P1 = proofOf(1);
+ const pair = async (room = randomRoom(), proof = P1) => {
+ const pc = await open(h, room, "pc", { proof });
+ const phone = await open(h, room, "phone", { proof });
+ expect(await pc.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ expect(await phone.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ return { room, pc, phone };
+ };
+
+ it("answers the health check and nothing else on /", async () => {
+ expect(await h.http("/")).toEqual({ status: 200, text: "Coucou link relay" });
+ expect((await h.http("/", "POST")).status).toBe(405);
+ expect((await h.http("/elsewhere")).status).toBe(404);
+ });
+
+ it("refuses a bad path, room id or role with 404 and creates no room", async () => {
+ const before = await h.roomsCreated();
+ const good = randomRoom();
+ const bad = [
+ ["short", "phone"], [good + "x", "phone"], [good.slice(0, 21) + "!", "phone"], [good, "tablet"], [good, ""],
+ ] as const;
+ for (const [room, role] of bad) expect(await h.connect(room, role, { proof: P1 })).toEqual({ refused: 404 });
+ expect(await h.roomsCreated()).toBe(before);
+ });
+
+ it("refuses a missing, wrong or malformed access key with 401, before any room exists", async () => {
+ const before = await h.roomsCreated();
+ const room = randomRoom();
+ for (const key of [null, "", "short", OTHER_ACCESS, ACCESS + "x", ACCESS.slice(1), ACCESS.toUpperCase()]) {
+ expect(await h.connect(room, "pc", { key, proof: P1 }), String(key)).toEqual({ refused: 401 });
+ }
+ expect(await h.roomsCreated()).toBe(before);
+ });
+
+ it("refuses a missing or malformed join proof with 400", async () => {
+ const room = randomRoom();
+ for (const protocols of ["", "coucou.v1", "coucou.join." + proofOf(1), "coucou.v1, coucou.join.short", "coucou.v1, coucou.join." + proofOf(1) + "A",
+ "coucou.v1, coucou.join." + proofOf(1) + ", coucou.join." + proofOf(2), "other, coucou.join." + proofOf(1)]) {
+ expect(await h.connect(room, "pc", { protocols }), protocols).toEqual({ refused: 400 });
+ }
+ });
+
+ it("fails closed: with no access key configured every room request is refused", async () => {
+ await h.setAccessKey(undefined);
+ try {
+ expect(await h.connect(randomRoom(), "pc", { proof: P1 })).toEqual({ refused: 401 });
+ expect(await h.connect(randomRoom(), "pc", { key: "", proof: P1 })).toEqual({ refused: 401 });
+ expect((await h.http("/")).status).toBe(200); // the health check needs no key
+ } finally {
+ await h.setAccessKey(ACCESS);
+ }
+ });
+
+ it("forwards binary frames both ways, byte for byte, and tells each side the other arrived", async () => {
+ const { pc, phone } = await pair();
+ const all = Uint8Array.from({ length: 256 }, (_, i) => i);
+ phone.send(all);
+ expect(await pc.next()).toEqual({ kind: "binary", data: all });
+ pc.send(new Uint8Array([9, 8, 7]));
+ expect(await phone.next()).toEqual({ kind: "binary", data: new Uint8Array([9, 8, 7]) });
+ pc.send(new Uint8Array(0));
+ expect(await phone.next()).toEqual({ kind: "binary", data: new Uint8Array(0) });
+ const biggest = new Uint8Array(66_000).fill(0xab);
+ phone.send(biggest);
+ const got = await pc.next(5000);
+ expect(got.kind === "binary" && got.data.length).toBe(66_000);
+ });
+
+ it("closes a socket that sends a frame over 66,000 bytes (1009)", async () => {
+ const { pc, phone } = await pair();
+ phone.send(new Uint8Array(66_001));
+ const m = await phone.next(5000);
+ expect(m.kind === "close" && m.code).toBe(1009);
+ // The other side only hears that the peer left.
+ expect(await pc.next()).toEqual({ kind: "text", data: '{"peer":"offline"}' });
+ });
+
+ it("never buffers: a frame for an absent peer is dropped and the sender hears 'offline'", async () => {
+ const room = randomRoom();
+ const phone = await open(h, room, "phone", { proof: P1 });
+ phone.send(new Uint8Array([1, 2, 3]));
+ expect(await phone.next()).toEqual({ kind: "text", data: '{"peer":"offline"}' });
+ const pc = await open(h, room, "pc", { proof: P1 });
+ expect(await pc.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ expect(await phone.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ expect(await pc.quiet(300)).toBe(true); // the dropped frame did not come back
+ });
+
+ it("tells the remaining side when the other leaves", async () => {
+ const { pc, phone } = await pair();
+ pc.close(1000, "bye");
+ expect(await phone.next()).toEqual({ kind: "text", data: '{"peer":"offline"}' });
+ });
+
+ it("answers a text 'ping' with 'pong' and closes on any other text (1003)", async () => {
+ const { pc, phone } = await pair();
+ phone.send("ping");
+ expect(await phone.next()).toEqual({ kind: "text", data: "pong" });
+ expect(await pc.quiet(200)).toBe(true); // a heartbeat is not forwarded
+ phone.send("hello there");
+ const m = await phone.next();
+ expect(m.kind === "close" && m.code).toBe(1003);
+ });
+
+ it("refuses a second key for a room that is held (1008) and leaves the first pair alone", async () => {
+ const { room, pc, phone } = await pair();
+ const intruder = await open(h, room, "pc", { proof: proofOf(2) });
+ const m = await intruder.next();
+ expect(m).toEqual({ kind: "close", code: 1008, reason: "join proof" });
+ pc.send(new Uint8Array([5]));
+ expect(await phone.next()).toEqual({ kind: "binary", data: new Uint8Array([5]) });
+ });
+
+ it("lets a role's new socket replace the old one (1000 'replaced') without telling the other side it left", async () => {
+ const { room, pc, phone } = await pair();
+ const again = await open(h, room, "pc", { proof: P1 });
+ expect(await pc.next()).toEqual({ kind: "close", code: 1000, reason: "replaced" });
+ expect(await again.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ expect(await phone.next()).toEqual({ kind: "text", data: '{"peer":"online"}' });
+ again.send(new Uint8Array([7]));
+ expect(await phone.next()).toEqual({ kind: "binary", data: new Uint8Array([7]) });
+ });
+
+ it("keeps rooms apart", async () => {
+ const a = await pair();
+ const b = await pair();
+ a.pc.send(new Uint8Array([1]));
+ expect(await a.phone.next()).toEqual({ kind: "binary", data: new Uint8Array([1]) });
+ expect(await b.phone.quiet(200)).toBe(true);
+ expect(await b.pc.quiet(100)).toBe(true);
+ });
+
+ it("closes a socket that floods (1008 'rate')", async () => {
+ const { pc, phone } = await pair();
+ for (let i = 0; i < 300; i++) phone.send(new Uint8Array([i & 255]));
+ let closed: Msg | undefined;
+ for (let i = 0; i < 400 && !closed; i++) {
+ const m = await phone.next(3000);
+ if (m.kind === "close") closed = m;
+ }
+ expect(closed).toEqual({ kind: "close", code: 1008, reason: "rate" });
+ // The other side received at most the burst and the refill, far fewer than 300.
+ let got = 0;
+ while (!(await pc.quiet(150))) {
+ const m = await pc.next();
+ if (m.kind === "binary") got++;
+ }
+ expect(got).toBeGreaterThan(30);
+ expect(got).toBeLessThan(150);
+ });
+
+ it("closes live sockets at their next frame when the access key is rotated, and refuses the old key", async () => {
+ const { room, pc, phone } = await pair();
+ await h.setAccessKey(OTHER_ACCESS);
+ try {
+ phone.send(new Uint8Array([1]));
+ const m = await phone.next();
+ expect(m).toEqual({ kind: "close", code: 1008, reason: "access key changed" });
+ expect(await h.connect(room, "phone", { key: ACCESS, proof: P1 })).toEqual({ refused: 401 });
+ const fresh = await open(h, room, "phone", { key: OTHER_ACCESS, proof: P1 });
+ expect(fresh).toBeTruthy();
+ void pc;
+ } finally {
+ await h.setAccessKey(ACCESS);
+ }
+ });
+ });
+}
diff --git a/android/relay/tests/env.d.ts b/android/relay/tests/env.d.ts
new file mode 100644
index 00000000..3ab5162f
--- /dev/null
+++ b/android/relay/tests/env.d.ts
@@ -0,0 +1,10 @@
+// Types for `import { env, exports } from "cloudflare:workers"` in the tests.
+declare namespace Cloudflare {
+ interface Env {
+ ROOM: DurableObjectNamespace<import("../src/room").Room>;
+ ACCESS_KEY?: string;
+ }
+ interface GlobalProps {
+ mainModule: typeof import("../src/index");
+ }
+}
diff --git a/android/relay/tests/node.guards.test.ts b/android/relay/tests/node.guards.test.ts
new file mode 100644
index 00000000..ca0957d3
--- /dev/null
+++ b/android/relay/tests/node.guards.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { readFileSync, readdirSync } from "node:fs";
+
+// Read as text from the repository (the Workers runtime has no host files, so these run with the Node tests).
+describe("source guards", () => {
+ const dir = new URL("../src/", import.meta.url);
+ const sources = readdirSync(dir).filter((f) => f.endsWith(".ts")).map((f) => [f, readFileSync(new URL(f, dir), "utf8")] as const);
+
+ it("the relay never logs, stores or calls out", () => {
+ for (const [file, text] of sources) {
+ const code = text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
+ for (const forbidden of ["console.", "storage.put", "storage.set", "storage.delete", ".sql", "KVNamespace", "R2Bucket", "D1Database", "fetch(\"http", "fetch(`http", "Queue", "waitUntil", "setAlarm"]) {
+ expect(code.includes(forbidden), `${file} uses ${forbidden}`).toBe(false);
+ }
+ }
+ });
+
+ it("the config logs nothing and holds no secret", () => {
+ const toml = readFileSync(new URL("../wrangler.toml", import.meta.url), "utf8");
+ expect(toml).toMatch(/\[observability\]\s*\nenabled = false/);
+ expect(toml).not.toMatch(/ACCESS_KEY\s*=/); // the key is a secret, set with `wrangler secret put`
+ expect(toml).not.toMatch(/\[vars\]/);
+ expect(toml).toMatch(/new_sqlite_classes = \["Room"\]/);
+ });
+});
diff --git a/android/relay/tests/node.relay.test.ts b/android/relay/tests/node.relay.test.ts
new file mode 100644
index 00000000..777932a4
--- /dev/null
+++ b/android/relay/tests/node.relay.test.ts
@@ -0,0 +1,111 @@
+import { afterAll, describe, expect, it } from "vitest";
+import { WebSocket } from "ws";
+import { startRelay } from "../tools/dev-relay.ts";
+import { ACCESS, behaviour, offer, proofOf, randomRoom, type Conn, type Harness, type Msg, type Options } from "./behaviour.ts";
+
+let relay: Awaited<ReturnType<typeof startRelay>>;
+
+function wrap(ws: WebSocket): Conn {
+ const queue: Msg[] = [];
+ let wake: (() => void) | undefined;
+ const push = (m: Msg) => {
+ queue.push(m);
+ wake?.();
+ };
+ ws.on("message", (data, isBinary) => {
+ const buf = Buffer.isBuffer(data) ? data : Buffer.concat(data as Buffer[]);
+ push(isBinary ? { kind: "binary", data: new Uint8Array(buf) } : { kind: "text", data: buf.toString() });
+ });
+ ws.on("close", (code, reason) => push({ kind: "close", code, reason: reason.toString() }));
+ const next = async (timeoutMs = 1500): Promise<Msg> => {
+ const until = Date.now() + timeoutMs;
+ while (queue.length === 0) {
+ if (Date.now() > until) throw new Error("timed out waiting for a message");
+ await new Promise<void>((r) => {
+ wake = r;
+ setTimeout(r, 25);
+ });
+ }
+ return queue.shift()!;
+ };
+ return {
+ next,
+ quiet: async (ms = 200) => {
+ const until = Date.now() + ms;
+ while (Date.now() < until) {
+ if (queue.length > 0) return false;
+ await new Promise((r) => setTimeout(r, 15));
+ }
+ return queue.length === 0;
+ },
+ send: (d) => ws.send(d),
+ close: (code, reason) => ws.close(code ?? 1000, reason ?? ""),
+ };
+}
+
+const harness = async (): Promise<Harness> => {
+ relay = await startRelay({ accessKey: ACCESS });
+ const base = `127.0.0.1:${relay.port}`;
+ return {
+ async http(path, method = "GET") {
+ const r = await fetch(`http://${base}${path}`, { method });
+ return { status: r.status, text: await r.text() };
+ },
+ connect(room, role, o: Options = {}) {
+ const protocols = o.protocols ?? offer(o.proof ?? proofOf(1));
+ const headers: Record<string, string> = {};
+ if (o.key !== null) headers.Authorization = `Bearer ${o.key ?? ACCESS}`;
+ return new Promise((resolve) => {
+ const ws = new WebSocket(`ws://${base}/v1/room/${room}?role=${role}`, protocols ? protocols.split(",").map((s) => s.trim()).filter(Boolean) : [], { headers });
+ ws.on("unexpected-response", (_req, res) => {
+ resolve({ refused: res.statusCode ?? 0 });
+ ws.terminate();
+ });
+ ws.on("error", () => {});
+ ws.on("open", () => resolve(wrap(ws)));
+ });
+ },
+ setAccessKey: async (key) => relay.setAccessKey(key),
+ roomsCreated: async () => relay.rooms(),
+ stop: () => relay.close(),
+ };
+};
+
+behaviour("Node twin", harness);
+
+describe("Node twin only", () => {
+ it("answers 429 after too many new connections from one address, before checking the key", async () => {
+ const r = await startRelay({ accessKey: ACCESS, connectsPerMinute: 3 });
+ try {
+ const statuses: number[] = [];
+ for (let i = 0; i < 5; i++) {
+ statuses.push(
+ await new Promise<number>((resolve) => {
+ const ws = new WebSocket(`ws://127.0.0.1:${r.port}/v1/room/${randomRoom()}?role=pc`, ["coucou.v1", `coucou.join.${proofOf(1)}`], { headers: { Authorization: "Bearer wrong-wrong-wrong-wrong" } });
+ ws.on("unexpected-response", (_q, res) => (resolve(res.statusCode ?? 0), ws.terminate()));
+ ws.on("error", () => {});
+ }),
+ );
+ }
+ expect(statuses).toEqual([401, 401, 401, 429, 429]);
+ } finally {
+ await r.close();
+ }
+ });
+
+ it("leaves no room behind when everyone has left", async () => {
+ const r = await startRelay({ accessKey: ACCESS });
+ try {
+ const ws = new WebSocket(`ws://127.0.0.1:${r.port}/v1/room/${randomRoom()}?role=pc`, ["coucou.v1", `coucou.join.${proofOf(1)}`], { headers: { Authorization: `Bearer ${ACCESS}` } });
+ await new Promise((res) => ws.on("open", res));
+ expect(r.rooms()).toBe(1);
+ ws.close();
+ await new Promise((res) => ws.on("close", res));
+ await new Promise((res) => setTimeout(res, 50));
+ expect(r.rooms()).toBe(0);
+ } finally {
+ await r.close();
+ }
+ });
+});
+afterAll(() => undefined);
diff --git a/android/relay/tests/worker.relay.test.ts b/android/relay/tests/worker.relay.test.ts
new file mode 100644
index 00000000..a0a5262d
--- /dev/null
+++ b/android/relay/tests/worker.relay.test.ts
@@ -0,0 +1,161 @@
+import { env, exports } from "cloudflare:workers";
+import { evictDurableObject, listDurableObjectIds, runInDurableObject } from "cloudflare:test";
+import { describe, expect, it } from "vitest";
+import worker from "../src/index.ts";
+import { ACCESS, behaviour, offer, open, proofOf, randomRoom, type Conn, type Harness, type Msg, type Options } from "./behaviour.ts";
+
+type Anything = Record<string, unknown>;
+const mutableEnv = env as unknown as Anything;
+
+function wrap(ws: WebSocket): Conn {
+ ws.binaryType = "arraybuffer"; // workerd's default is a Blob
+ const queue: Msg[] = [];
+ let wake: (() => void) | undefined;
+ const push = (m: Msg) => {
+ queue.push(m);
+ wake?.();
+ };
+ ws.addEventListener("message", (e) => {
+ const d = e.data as string | ArrayBuffer;
+ push(typeof d === "string" ? { kind: "text", data: d } : { kind: "binary", data: new Uint8Array(d) });
+ });
+ ws.addEventListener("close", (e) => push({ kind: "close", code: e.code, reason: e.reason }));
+ const next = async (timeoutMs = 1500): Promise<Msg> => {
+ const until = Date.now() + timeoutMs;
+ while (queue.length === 0) {
+ if (Date.now() > until) throw new Error("timed out waiting for a message");
+ await new Promise<void>((r) => {
+ wake = r;
+ setTimeout(r, 25);
+ });
+ }
+ return queue.shift()!;
+ };
+ return {
+ next,
+ quiet: async (ms = 200) => {
+ const until = Date.now() + ms;
+ while (Date.now() < until) {
+ if (queue.length > 0) return false;
+ await new Promise((r) => setTimeout(r, 15));
+ }
+ return queue.length === 0;
+ },
+ send: (d) => ws.send(d),
+ close: (code, reason) => ws.close(code ?? 1000, reason ?? ""),
+ };
+}
+
+async function upgrade(room: string, role: string, o: Options = {}): Promise<Response> {
+ const headers: Record<string, string> = { Upgrade: "websocket" };
+ if (o.key !== null) headers.Authorization = `Bearer ${o.key ?? ACCESS}`;
+ const protocols = o.protocols ?? offer(o.proof ?? proofOf(1));
+ if (protocols) headers["Sec-WebSocket-Protocol"] = protocols;
+ return exports.default.fetch(`https://relay.test/v1/room/${room}?role=${role}`, { headers });
+}
+
+const harness = async (): Promise<Harness> => ({
+ async http(path, method = "GET") {
+ const r = await exports.default.fetch(`https://relay.test${path}`, { method });
+ return { status: r.status, text: await r.text() };
+ },
+ async connect(room, role, o = {}) {
+ const res = await upgrade(room, role, o);
+ if (res.status !== 101) return { refused: res.status };
+ const ws = res.webSocket!;
+ ws.accept();
+ return wrap(ws);
+ },
+ async setAccessKey(key) {
+ mutableEnv.ACCESS_KEY = key; // the Worker and every Room read the configured key from env
+ },
+ roomsCreated: async () => (await listDurableObjectIds(env.ROOM)).length,
+ stop: async () => {},
+});
+
+behaviour("Worker (workerd)", harness);
+
+describe("Worker only", () => {
+ it("never contacts a room for a request it refuses (a stand-in room namespace records every call)", async () => {
+ const calls: string[] = [];
+ const fake = {
+ idFromName: (n: string) => (calls.push(`id:${n}`), n),
+ get: (id: string) => (calls.push(`get:${id}`), { fetch: async () => new Response(null, { status: 200 }) }),
+ };
+ const base = { ROOM: fake, ACCESS_KEY: ACCESS } as never;
+ const room = randomRoom();
+ const ws = { Upgrade: "websocket", "Sec-WebSocket-Protocol": offer(proofOf(1)) };
+ const refused = [
+ new Request("https://r.test/v1/room/bad?role=pc", { headers: { ...ws, Authorization: `Bearer ${ACCESS}` } }),
+ new Request(`https://r.test/v1/room/${room}?role=x`, { headers: { ...ws, Authorization: `Bearer ${ACCESS}` } }),
+ new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: ws }),
+ new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: { ...ws, Authorization: "Bearer nope-nope-nope-nope-nope" } }),
+ new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: { Upgrade: "websocket", Authorization: `Bearer ${ACCESS}` } }),
+ new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: { "Sec-WebSocket-Protocol": offer(proofOf(1)), Authorization: `Bearer ${ACCESS}` } }),
+ new Request(`https://r.test/v1/room/${room}?role=pc`, { method: "POST", headers: { ...ws, Authorization: `Bearer ${ACCESS}` } }),
+ ];
+ const statuses = [];
+ for (const r of refused) statuses.push((await worker.fetch(r, base)).status);
+ expect(statuses).toEqual([404, 404, 401, 401, 400, 426, 404]);
+ expect(calls).toEqual([]);
+ // And the same request, well-formed, reaches exactly one room, the one named by the id.
+ const ok = await worker.fetch(new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: { ...ws, Authorization: `Bearer ${ACCESS}` } }), base);
+ expect(ok.status).toBe(200);
+ expect(calls).toEqual([`id:${room}`, `get:${room}`]);
+ });
+
+ it("asks the rate limiter first: a limited address gets 429 before the key is even compared", async () => {
+ const keys: string[] = [];
+ const limited = { limit: async ({ key }: { key: string }) => (keys.push(key), { success: false }) };
+ const base = { ROOM: {}, ACCESS_KEY: ACCESS, CONNECT_LIMIT: limited } as never;
+ const room = randomRoom();
+ const r = await worker.fetch(new Request(`https://r.test/v1/room/${room}?role=pc`, { headers: { "CF-Connecting-IP": "203.0.113.9", Authorization: "Bearer wrong-wrong-wrong-wrong" } }), base);
+ expect(r.status).toBe(429);
+ expect(keys).toEqual(["203.0.113.9"]);
+ // A path that is not a room request costs the limiter nothing.
+ keys.length = 0;
+ expect((await worker.fetch(new Request("https://r.test/nope"), base)).status).toBe(404);
+ expect(keys).toEqual([]);
+ });
+
+ it("stores nothing: the room's storage stays empty through a whole conversation", async () => {
+ const room = randomRoom();
+ const pc = await open(await harness(), room, "pc");
+ const phone = await open(await harness(), room, "phone");
+ await pc.next();
+ await phone.next();
+ for (let i = 0; i < 20; i++) {
+ pc.send(new Uint8Array([i]));
+ await phone.next();
+ }
+ const stub = env.ROOM.get(env.ROOM.idFromName(room));
+ const keys = await runInDurableObject(stub, async (_instance, state) => [...(await state.storage.list()).keys()]);
+ expect(keys).toEqual([]);
+ });
+
+ it("survives hibernation: the roles, the join proof and the access generation live in the sockets", async () => {
+ const h = await harness();
+ const room = randomRoom();
+ const pc = await open(h, room, "pc");
+ const phone = await open(h, room, "phone");
+ await pc.next();
+ await phone.next();
+ await evictDurableObject(env.ROOM.get(env.ROOM.idFromName(room)), { webSockets: "hibernate" });
+ phone.send(new Uint8Array([42]));
+ expect(await pc.next(5000)).toEqual({ kind: "binary", data: new Uint8Array([42]) });
+ // The join proof is still enforced after the room woke up again.
+ const intruder = await open(h, room, "pc", { proof: proofOf(2) });
+ expect(await intruder.next()).toEqual({ kind: "close", code: 1008, reason: "join proof" });
+ });
+
+ it("a room with no socket left remembers nothing: the next pair may use another join proof", async () => {
+ const h = await harness();
+ const room = randomRoom();
+ const a = await open(h, room, "pc", { proof: proofOf(1) });
+ a.close(1000, "bye");
+ await new Promise((r) => setTimeout(r, 100));
+ const b = await open(h, room, "pc", { proof: proofOf(2) });
+ b.send(new Uint8Array([1])); // accepted: a different proof is fine for an empty room
+ expect(await b.next()).toEqual({ kind: "text", data: '{"peer":"offline"}' });
+ });
+});
diff --git a/android/relay/tools/dev-relay.ts b/android/relay/tools/dev-relay.ts
new file mode 100644
index 00000000..9e91c79a
--- /dev/null
+++ b/android/relay/tools/dev-relay.ts
@@ -0,0 +1,145 @@
+// The same relay in plain Node (the `ws` package): the twin of src/index.ts + src/room.ts. It enforces the same rules from the
+// same code (src/protocol.ts) so the Rust and Kotlin clients can be tested against a real server without Cloudflare, and so
+// the relay can be self-hosted on a small server behind a TLS proxy (docs/RELAY_LINK.md). Erasable TypeScript only:
+//
+// ACCESS_KEY=<key> PORT=8787 node android/relay/tools/dev-relay.ts
+//
+// It listens on plain ws:// (put a TLS terminator in front of it for the internet). Like the Worker it stores nothing,
+// logs nothing and fails closed without an access key.
+
+import { createServer } from "node:http";
+import { pathToFileURL } from "node:url";
+import type { Duplex } from "node:stream";
+import { WebSocketServer, type WebSocket } from "ws";
+import {
+ Bucket, MAX_FRAME, PEER_OFFLINE, PEER_ONLINE, RATE_BURST, RATE_PER_SECOND, SUBPROTOCOL,
+ accessGeneration, accessKeyOk, joinVerifier, otherRole, parseJoinProof, parseRoomRequest,
+ type Role,
+} from "../src/protocol.ts";
+
+interface Peer {
+ ws: WebSocket;
+ role: Role;
+ verifier: string;
+ gen: string;
+ bucket: Bucket;
+ replaced: boolean;
+}
+
+export interface Relay {
+ port: number;
+ /** Change (or remove) the access key while running, as `wrangler secret put` does. */
+ setAccessKey(key: string | undefined): void;
+ /** How many rooms have a live socket. A room with none leaves nothing behind. */
+ rooms(): number;
+ close(): Promise<void>;
+}
+
+export async function startRelay(options: { port?: number; host?: string; accessKey?: string; connectsPerMinute?: number } = {}): Promise<Relay> {
+ let accessKey = options.accessKey;
+ const rooms = new Map<string, Partial<Record<Role, Peer>> & { verifier?: string }>();
+ const connects = new Map<string, number[]>();
+ const wss = new WebSocketServer({
+ noServer: true,
+ maxPayload: MAX_FRAME, // a larger frame closes the socket with 1009
+ handleProtocols: () => SUBPROTOCOL,
+ });
+
+ const refuse = (socket: Duplex, status: number, text: string) => {
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`);
+ socket.destroy();
+ };
+
+ const server = createServer((req, res) => {
+ if (req.url === "/" && req.method === "GET") {
+ res.writeHead(200, { "content-type": "text/plain" }).end("Coucou link relay");
+ } else {
+ res.writeHead(req.url === "/" ? 405 : 404).end();
+ }
+ });
+
+ server.on("upgrade", async (req, socket, head) => {
+ const url = new URL(req.url ?? "/", "http://relay.invalid");
+ const target = req.method === "GET" ? parseRoomRequest(url) : null;
+ if (!target) return refuse(socket, 404, "Not Found");
+ if (options.connectsPerMinute) {
+ const ip = req.socket.remoteAddress ?? "unknown";
+ const now = Date.now();
+ const recent = (connects.get(ip) ?? []).filter((t) => now - t < 60_000);
+ if (recent.length >= options.connectsPerMinute) return refuse(socket, 429, "Too Many Requests");
+ connects.set(ip, [...recent, now]);
+ }
+ if (!(await accessKeyOk(accessKey, req.headers.authorization ?? null))) return refuse(socket, 401, "Unauthorized");
+ const proof = parseJoinProof((req.headers["sec-websocket-protocol"] as string | undefined) ?? null);
+ if (!proof) return refuse(socket, 400, "Bad Request");
+ const verifier = await joinVerifier(proof);
+ const gen = await accessGeneration(accessKey);
+
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ const room = rooms.get(target.room) ?? {};
+ const live = (Object.values(room).filter((v) => typeof v === "object") as Peer[]).filter((p) => !p.replaced);
+ if (live.length > 0 && live[0].verifier !== verifier) {
+ ws.close(1008, "join proof");
+ return;
+ }
+ const old = room[target.role];
+ if (old) {
+ old.replaced = true;
+ old.ws.close(1000, "replaced");
+ }
+ const me: Peer = { ws, role: target.role, verifier, gen, bucket: new Bucket(RATE_PER_SECOND, RATE_BURST), replaced: false };
+ room[target.role] = me;
+ rooms.set(target.room, room);
+ const peer = room[otherRole(target.role)];
+ if (peer && !peer.replaced && peer.ws.readyState === peer.ws.OPEN) {
+ ws.send(PEER_ONLINE);
+ peer.ws.send(PEER_ONLINE);
+ }
+
+ ws.on("message", async (data, isBinary) => {
+ if ((await accessGeneration(accessKey)) !== me.gen || !me.gen) return ws.close(1008, "access key changed");
+ if (!isBinary) {
+ if (data.toString() === "ping") return ws.send("pong"); // the platform's auto-response in the Worker
+ return ws.close(1003, "binary only");
+ }
+ const frame = Buffer.isBuffer(data) ? data : Buffer.concat(data as Buffer[]);
+ if (frame.length > MAX_FRAME) return ws.close(1009, "too big");
+ if (!me.bucket.take()) return ws.close(1008, "rate");
+ const other = room[otherRole(me.role)];
+ if (!other || other.replaced || other.ws.readyState !== other.ws.OPEN) return ws.send(PEER_OFFLINE);
+ other.ws.send(frame, { binary: true });
+ });
+
+ const left = () => {
+ if (room[me.role] === me) delete room[me.role];
+ if (!room.pc && !room.phone) rooms.delete(target.room);
+ if (me.replaced) return;
+ const other = room[otherRole(me.role)];
+ if (other && !other.replaced && other.ws.readyState === other.ws.OPEN) other.ws.send(PEER_OFFLINE);
+ };
+ ws.on("close", left);
+ ws.on("error", left);
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(options.port ?? 0, options.host ?? "127.0.0.1", resolve));
+ const address = server.address();
+ const port = typeof address === "object" && address ? address.port : 0;
+ return {
+ port,
+ setAccessKey: (key) => void (accessKey = key),
+ rooms: () => rooms.size,
+ close: () =>
+ new Promise<void>((resolve) => {
+ for (const c of wss.clients) c.terminate();
+ server.close(() => resolve());
+ server.closeAllConnections();
+ }),
+ };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const relay = await startRelay({ port: Number(process.env.PORT ?? 8787), host: process.env.HOST ?? "0.0.0.0", accessKey: process.env.ACCESS_KEY, connectsPerMinute: 30 });
+ if (!process.env.ACCESS_KEY) process.stderr.write("ACCESS_KEY is not set: every room request will be refused (fail closed)\n");
+ process.stdout.write(`Coucou link relay (Node) listening on port ${relay.port}\n`);
+}
diff --git a/android/relay/tools/e2e.sh b/android/relay/tools/e2e.sh
new file mode 100755
index 00000000..c8d08975
--- /dev/null
+++ b/android/relay/tools/e2e.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# End to end through a real relay: the Rust computer side and the Kotlin phone side, with the Cloudflare Worker (under
+# `wrangler dev`, i.e. workerd on this machine) or the Node twin in between. Nothing is deployed, nothing leaves this
+# computer: the relay listens on 127.0.0.1 and the credentials are fixed test values.
+#
+# android/relay/tools/e2e.sh worker # the real Worker code in workerd (default)
+# android/relay/tools/e2e.sh node # the Node twin
+#
+# PHONE_CMD overrides how the Kotlin test is run (default: Gradle, as CI does). The test task is cleaned first: Gradle does not
+# treat the environment as an input, so a cached "up to date" result would silently skip the test.
+set -euo pipefail
+
+MODE="${1:-worker}"
+ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
+PORT="${PORT:-8799}"
+# base64url of 32 bytes of 0x33: the same value both test halves use as the access key.
+ACCESS="MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM"
+LOG="$(mktemp -d)"
+export WRANGLER_SEND_METRICS=false
+export COUCOU_E2E_RELAY_URL="ws://127.0.0.1:${PORT}"
+
+cleanup() { kill "${RELAY_PID:-0}" "${PC_PID:-0}" 2>/dev/null || true; }
+trap cleanup EXIT
+
+case "$MODE" in
+ worker)
+ (cd "$ROOT/android/relay" && exec npx wrangler dev --ip 127.0.0.1 --port "$PORT" --var "ACCESS_KEY:$ACCESS" >"$LOG/relay.log" 2>&1) &
+ RELAY_PID=$!
+ ;;
+ node)
+ (cd "$ROOT/android/relay" && ACCESS_KEY="$ACCESS" PORT="$PORT" HOST=127.0.0.1 exec node --experimental-strip-types --no-warnings tools/dev-relay.ts >"$LOG/relay.log" 2>&1) &
+ RELAY_PID=$!
+ ;;
+ *) echo "usage: e2e.sh [worker|node]" >&2; exit 2 ;;
+esac
+
+echo "waiting for the relay ($MODE) on port $PORT"
+for _ in $(seq 1 120); do
+ if curl -fsS "http://127.0.0.1:${PORT}/" 2>/dev/null | grep -q "Coucou link relay"; then break; fi
+ sleep 1
+done
+curl -fsS "http://127.0.0.1:${PORT}/" | grep -q "Coucou link relay" || { echo "the relay did not start"; cat "$LOG/relay.log"; exit 1; }
+
+echo "starting the computer side (Rust)"
+(cd "$ROOT/windows" && cargo test -p coucou --lib relay_client::tests::e2e -- --ignored --nocapture >"$LOG/pc.log" 2>&1) &
+PC_PID=$!
+
+echo "running the phone side (Kotlin)"
+PHONE_CMD="${PHONE_CMD:-cd $ROOT/android && ./gradlew cleanTestDebugUnitTest testDebugUnitTest --tests '*RelayE2ETest' --console=plain}"
+if ! bash -c "$PHONE_CMD"; then
+ echo "the phone side failed"; tail -30 "$LOG/pc.log" || true; exit 1
+fi
+
+if wait "$PC_PID"; then
+ echo "END TO END OK ($MODE): the Rust computer and the Kotlin phone talked through the relay and the approval was decided"
+else
+ echo "the computer side failed"; tail -40 "$LOG/pc.log"; exit 1
+fi
diff --git a/android/relay/tools/gen-vectors.mjs b/android/relay/tools/gen-vectors.mjs
new file mode 100644
index 00000000..f1e9a0a8
--- /dev/null
+++ b/android/relay/tools/gen-vectors.mjs
@@ -0,0 +1,201 @@
+#!/usr/bin/env node
+// Generates android/relay/test-vectors.json: fixed inputs and the exact bytes the secure channel of
+// docs/RELAY_LINK.md must produce. The Rust side (phone_link/relay_crypto.rs) and the Kotlin side
+// (link/RelayCrypto.kt) both read this file, so the two implementations are checked against the same bytes.
+// Node's own crypto is the third, independent implementation.
+//
+// node android/relay/tools/gen-vectors.mjs writes test-vectors.json
+// node android/relay/tools/gen-vectors.mjs --check fails if the file is not what this script produces (CI)
+
+import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync } from "node:crypto";
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+const OUT = join(dirname(fileURLToPath(import.meta.url)), "..", "test-vectors.json");
+const hex = (b) => Buffer.from(b).toString("hex");
+const fromHex = (s) => Buffer.from(s, "hex");
+const seq = (start, n) => Buffer.from(Array.from({ length: n }, (_, i) => (start + i) & 0xff));
+const b64url = (b) => Buffer.from(b).toString("base64url");
+
+const LABEL = "coucou-relay/v1";
+const VER = 1;
+const T_INIT = 1, T_ACCEPT = 2, T_DATA = 3;
+const DIR = { p2h: 1, h2p: 2 }; // phone to computer ("host"), computer to phone
+
+// ── fixed inputs ────────────────────────────────────────────────────────────────
+const K = seq(0x00, 32);
+const roomBytes = seq(0xa0, 16);
+const room = b64url(roomBytes); // 22 characters, as in the URL
+const nPhone = seq(0x40, 16);
+const nPc = seq(0x60, 16);
+
+const hkdf = (ikm, salt, info, len) => Buffer.from(hkdfSync("sha256", ikm, salt, info, len));
+const hmac = (key, ...parts) => createHmac("sha256", key).update(Buffer.concat(parts.map((p) => Buffer.from(p)))).digest();
+
+const kAuth = hkdf(K, Buffer.alloc(0), `${LABEL} auth`, 32);
+const kJoin = hkdf(K, Buffer.alloc(0), `${LABEL} join`, 32);
+const session = hkdf(K, Buffer.concat([nPhone, nPc]), `${LABEL} session`, 64);
+const key = { p2h: session.subarray(0, 32), h2p: session.subarray(32, 64) };
+
+const u64 = (n) => {
+ const b = Buffer.alloc(8);
+ b.writeBigUInt64BE(BigInt(n));
+ return b;
+};
+const header = (type, counter) => Buffer.concat([Buffer.from([VER, type]), u64(counter)]);
+const nonce = (dir, counter) => Buffer.concat([Buffer.from([DIR[dir], 0, 0, 0]), u64(counter)]);
+const aad = (dir, type, counter, roomText = room) =>
+ Buffer.concat([Buffer.from(LABEL), Buffer.from(roomText), Buffer.from([DIR[dir]]), header(type, counter)]);
+
+// One v1 line (no newline), as a 4-byte length, the line, then zeros up to a multiple of 128 bytes.
+function pad(line) {
+ const body = Buffer.from(line, "utf8");
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(body.length);
+ const raw = Buffer.concat([len, body]);
+ const total = Math.max(128, Math.ceil(raw.length / 128) * 128);
+ return Buffer.concat([raw, Buffer.alloc(total - raw.length)]);
+}
+
+function seal(dir, counter, line, k = key[dir]) {
+ const plaintext = pad(line);
+ const c = createCipheriv("aes-256-gcm", k, nonce(dir, counter), { authTagLength: 16 });
+ c.setAAD(aad(dir, T_DATA, counter));
+ const ct = Buffer.concat([c.update(plaintext), c.final(), c.getAuthTag()]);
+ return { plaintext, frame: Buffer.concat([header(T_DATA, counter), ct]) };
+}
+
+function open(dir, frame, k = key[dir], roomText = room) {
+ if (frame.length < 10 + 16 + 128 || frame[0] !== VER || frame[1] !== T_DATA) return null;
+ const counter = frame.readBigUInt64BE(2);
+ const body = frame.subarray(10);
+ const d = createDecipheriv("aes-256-gcm", k, nonce(dir, counter), { authTagLength: 16 });
+ d.setAAD(aad(dir, T_DATA, counter, roomText));
+ d.setAuthTag(body.subarray(body.length - 16));
+ try {
+ return Buffer.concat([d.update(body.subarray(0, body.length - 16)), d.final()]);
+ } catch {
+ return null;
+ }
+}
+
+// ── handshake frames ────────────────────────────────────────────────────────────
+const initMac = hmac(kAuth, "init", room, nPhone);
+const acceptMac = hmac(kAuth, "accept", room, nPhone, nPc);
+const initFrame = Buffer.concat([header(T_INIT, 0), nPhone, initMac]);
+const acceptFrame = Buffer.concat([header(T_ACCEPT, 0), nPc, acceptMac]);
+
+// ── data frames ─────────────────────────────────────────────────────────────────
+const longLine = JSON.stringify({ type: "sessions", sessions: Array.from({ length: 3 }, (_, i) => ({ pillId: "integration_claude", agent: "Claude Code", state: "working", statusText: `step ${i}`, stepIndex: i, stepCount: 9, updatedAt: 1760000000000 + i })) });
+const cases = [
+ ["p2h", 0, JSON.stringify({ type: "hello", v: 1, token: "TOKEN-for-tests-only", device: "Test phone" })],
+ ["h2p", 0, JSON.stringify({ type: "welcome", v: 1, desktop: "Test PC", os: "linux" })],
+ ["p2h", 1, JSON.stringify({ type: "ping" })],
+ ["h2p", 1, longLine],
+ ["h2p", 2, JSON.stringify({ type: "pong" })],
+ ["p2h", 4294967295, JSON.stringify({ type: "ping" })], // the last counter of a session (2^32 - 1)
+].map(([dir, counter, line]) => {
+ const { plaintext, frame } = seal(dir, counter, line);
+ return { dir, counter, line, nonce: hex(nonce(dir, counter)), aad: hex(aad(dir, T_DATA, counter)), plaintext: hex(plaintext), frame: hex(frame) };
+});
+
+// ── frames that must be refused ─────────────────────────────────────────────────
+const good = fromHex(cases[0].frame);
+const flip = (buf, at) => {
+ const b = Buffer.from(buf);
+ b[at] ^= 0x01;
+ return b;
+};
+const negatives = [
+ { name: "a bit flipped in the ciphertext", dir: "p2h", frame: hex(flip(good, good.length - 20)), expect: "bad_tag" },
+ { name: "a bit flipped in the tag", dir: "p2h", frame: hex(flip(good, good.length - 1)), expect: "bad_tag" },
+ { name: "the counter in the header changed", dir: "p2h", frame: hex(flip(good, 9)), expect: "bad_tag" },
+ { name: "the frame type changed", dir: "p2h", frame: hex(flip(good, 1)), expect: "bad_header" },
+ { name: "an unknown version", dir: "p2h", frame: hex(flip(good, 0)), expect: "bad_header" },
+ { name: "a phone frame presented as a computer frame (reflection)", dir: "h2p", frame: cases[0].frame, expect: "bad_tag" },
+ { name: "truncated", dir: "p2h", frame: hex(good.subarray(0, good.length - 1)), expect: "bad_tag" },
+ { name: "shorter than a header and a tag", dir: "p2h", frame: hex(good.subarray(0, 20)), expect: "bad_header" },
+ { name: "another room", dir: "p2h", room: b64url(seq(0xb0, 16)), frame: cases[0].frame, expect: "bad_tag" },
+ { name: "another key", dir: "p2h", key: hex(seq(0x80, 32)), frame: cases[0].frame, expect: "bad_tag" },
+];
+for (const n of negatives) {
+ const k = n.key ? fromHex(n.key) : key[n.dir];
+ const opened = open(n.dir, fromHex(n.frame), k, n.room ?? room);
+ if (opened) throw new Error(`negative vector was accepted: ${n.name}`);
+}
+// Sequences the counter rule must refuse (the frames themselves are valid).
+const sequences = [
+ { name: "the same frame twice (replay)", dir: "p2h", counters: [0, 0], accepted: [true, false] },
+ { name: "a frame going back", dir: "p2h", counters: [0, 1, 0], accepted: [true, true, false] },
+ { name: "a gap (a frame was dropped)", dir: "p2h", counters: [0, 2], accepted: [true, false] },
+ { name: "the first frame is not counter 0", dir: "p2h", counters: [1], accepted: [false] },
+];
+
+// ── self-checks: the primitives, and "no (key, nonce) pair twice" ───────────────
+// RFC 5869 appendix A.1.
+{
+ const ikm = Buffer.alloc(22, 0x0b);
+ const salt = fromHex("000102030405060708090a0b0c");
+ const info = fromHex("f0f1f2f3f4f5f6f7f8f9");
+ const okm = hex(hkdf(ikm, salt, info, 42));
+ if (okm !== "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865") throw new Error("HKDF does not match RFC 5869");
+}
+{
+ const seen = new Set();
+ const note = (dir, counter, k) => {
+ const id = `${hex(k)}:${hex(nonce(dir, counter))}`;
+ if (seen.has(id)) throw new Error(`(key, nonce) used twice: ${dir} ${counter}`);
+ seen.add(id);
+ };
+ // Both directions of this session, then a second session with fresh nonces (as after a reconnect).
+ const second = hkdf(K, Buffer.concat([seq(0x50, 16), seq(0x70, 16)]), `${LABEL} session`, 64);
+ for (const [k1, k2] of [[key.p2h, key.h2p], [second.subarray(0, 32), second.subarray(32, 64)]]) {
+ for (let c = 0; c < 2000; c++) { note("p2h", c, k1); note("h2p", c, k2); }
+ }
+ if (hex(key.p2h) === hex(key.h2p)) throw new Error("the two directions share a key");
+ if (hex(key.p2h) === hex(second.subarray(0, 32))) throw new Error("two sessions share a key");
+ // Even if a bug made both directions use one key, the direction byte alone keeps the nonces apart.
+ if (hex(nonce("p2h", 5)) === hex(nonce("h2p", 5))) throw new Error("the direction is not in the nonce");
+}
+
+const out = {
+ _about: "Generated by android/relay/tools/gen-vectors.mjs. Do not edit by hand: change the script and regenerate. All byte strings are lowercase hex unless noted.",
+ version: VER,
+ label: LABEL,
+ frameTypes: { init: T_INIT, accept: T_ACCEPT, data: T_DATA },
+ directions: DIR,
+ rfc5869_a1: {
+ ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
+ salt: "000102030405060708090a0b0c",
+ info: "f0f1f2f3f4f5f6f7f8f9",
+ length: 42,
+ okm: "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
+ },
+ inputs: { key: hex(K), roomBytes: hex(roomBytes), room, nPhone: hex(nPhone), nPc: hex(nPc) },
+ derived: {
+ kAuth: hex(kAuth),
+ kJoin: hex(kJoin),
+ joinVerifier: hex(createHash("sha256").update(kJoin).digest()),
+ kP2H: hex(key.p2h),
+ kH2P: hex(key.h2p),
+ },
+ init: { macInput: hex(Buffer.concat([Buffer.from("init"), Buffer.from(room), nPhone])), mac: hex(initMac), frame: hex(initFrame) },
+ accept: { macInput: hex(Buffer.concat([Buffer.from("accept"), Buffer.from(room), nPhone, nPc])), mac: hex(acceptMac), frame: hex(acceptFrame) },
+ data: cases,
+ mustRefuse: negatives,
+ mustRefuseInOrder: sequences,
+};
+
+const text = JSON.stringify(out, null, 2) + "\n";
+if (process.argv.includes("--check")) {
+ const have = readFileSync(OUT, "utf8");
+ if (have !== text) {
+ console.error("android/relay/test-vectors.json is not what gen-vectors.mjs produces. Run: node android/relay/tools/gen-vectors.mjs");
+ process.exit(1);
+ }
+ console.log("test vectors are up to date");
+} else {
+ writeFileSync(OUT, text);
+ console.log(`wrote ${OUT}`);
+}
diff --git a/android/relay/tsconfig.json b/android/relay/tsconfig.json
new file mode 100644
index 00000000..87bcf7a7
--- /dev/null
+++ b/android/relay/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ES2022",
+ "moduleResolution": "bundler",
+ "lib": ["ES2022", "DOM"],
+ "types": ["@cloudflare/workers-types", "@cloudflare/vitest-plugin/types", "node"],
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "verbatimModuleSyntax": true
+ },
+ "include": ["src", "tests", "tools/*.ts", "*.ts"]
+}
diff --git a/android/relay/vitest.config.ts b/android/relay/vitest.config.ts
new file mode 100644
index 00000000..0b015dae
--- /dev/null
+++ b/android/relay/vitest.config.ts
@@ -0,0 +1,17 @@
+import { cloudflareTest } from "@cloudflare/vitest-plugin";
+import { defineConfig } from "vitest/config";
+
+// The Worker and its Room run in the Workers runtime (workerd, through Miniflare). The access key is a test value.
+export default defineConfig({
+ plugins: [
+ cloudflareTest({
+ wrangler: { configPath: "./wrangler.toml" },
+ miniflare: {
+ bindings: { ACCESS_KEY: "test-access-key-test-access-key-0123456789" },
+ // The tests open far more than 30 connections a minute from one "address"; the 429 path has its own test.
+ ratelimits: { CONNECT_LIMIT: { namespace_id: "1001", simple: { limit: 100000, period: 60 } } },
+ },
+ }),
+ ],
+ test: { include: ["tests/worker.*.test.ts"] },
+});
diff --git a/android/relay/vitest.node.config.ts b/android/relay/vitest.node.config.ts
new file mode 100644
index 00000000..9abe76d5
--- /dev/null
+++ b/android/relay/vitest.node.config.ts
@@ -0,0 +1,4 @@
+import { defineConfig } from "vitest/config";
+
+// The Node twin (tools/dev-relay.ts) and the pure rules, in plain Node.
+export default defineConfig({ test: { include: ["tests/node.*.test.ts"], environment: "node" } });
diff --git a/android/relay/wrangler.toml b/android/relay/wrangler.toml
new file mode 100644
index 00000000..96e6bb01
--- /dev/null
+++ b/android/relay/wrangler.toml
@@ -0,0 +1,25 @@
+# Coucou link relay (docs/RELAY_LINK.md). Deploy: see README.md.
+# No secret belongs in this file. The one secret, ACCESS_KEY, is set with: npx wrangler secret put ACCESS_KEY
+name = "coucou-link"
+main = "src/index.ts"
+compatibility_date = "2026-09-01"
+workers_dev = true
+
+# Nothing is logged: the relay forwards opaque frames and has nothing worth logging.
+[observability]
+enabled = false
+
+[[durable_objects.bindings]]
+name = "ROOM"
+class_name = "Room"
+
+# Durable Objects on the free plan must be SQLite-backed. The relay never uses the storage API.
+[[migrations]]
+tag = "v1"
+new_sqlite_classes = ["Room"]
+
+# New connections per source address (Workers Rate Limiting binding). Optional: the relay works without it.
+[[ratelimits]]
+name = "CONNECT_LIMIT"
+namespace_id = "1001"
+simple = { limit = 30, period = 60 }
diff --git a/android/scripts/gen-strings.mjs b/android/scripts/gen-strings.mjs
new file mode 100644
index 00000000..80f91d0c
--- /dev/null
+++ b/android/scripts/gen-strings.mjs
@@ -0,0 +1,36 @@
+// Generates app/src/main/res/values/strings.xml from i18n/app-strings.json. The app is English only.
+// Usage: node android/scripts/gen-strings.mjs [--check]
+// --check writes nothing and exits 1 if the committed file is stale.
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const target = path.join(root, "app/src/main/res/values/strings.xml");
+const app = JSON.parse(fs.readFileSync(path.join(root, "i18n/app-strings.json"), "utf8")).strings;
+
+const BS = String.fromCharCode(92);
+const esc = (s) =>
+ s.split(BS).join(BS + BS)
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
+ .replace(/'/g, BS + "'").replace(/"/g, BS + '"')
+ .replace(/^([@?])/, BS + "$1");
+
+// Placeholders must be positional printf arguments (%1$s), not {name}.
+if (Object.values(app).some((v) => /\{\w+\}/.test(v))) {
+ console.error("Placeholders are not supported; use %1$s in app-strings.json.");
+ process.exit(2);
+}
+
+const xml =
+ `<?xml version="1.0" encoding="utf-8"?>\n<!-- Generated by android/scripts/gen-strings.mjs. Do not edit. -->\n<resources>\n` +
+ Object.entries(app).map(([k, v]) => ` <string name="${k}">${esc(v)}</string>`).join("\n") + `\n</resources>\n`;
+
+if (process.argv.includes("--check")) {
+ // Windows checkouts may turn LF into CRLF; the content is what matters.
+ const stale = !fs.existsSync(target) || fs.readFileSync(target, "utf8").replace(/\r\n/g, "\n") !== xml;
+ if (stale) console.error(`stale: ${path.relative(root, target)}`);
+ process.exit(stale ? 1 : 0);
+}
+fs.writeFileSync(target, xml);
+console.log(`${Object.keys(app).length} strings`);
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 00000000..e758638d
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,9 @@
+pluginManagement {
+ repositories { google(); mavenCentral(); gradlePluginPortal() }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories { google(); mavenCentral() }
+}
+rootProject.name = "coucou-android"
+include(":app")
diff --git a/android/tools/dev-desktop.mjs b/android/tools/dev-desktop.mjs
new file mode 100644
index 00000000..72b29632
--- /dev/null
+++ b/android/tools/dev-desktop.mjs
@@ -0,0 +1,368 @@
+#!/usr/bin/env node
+// A pretend Coucou desktop for developing and testing the Android app without the real one.
+// Speaks docs/ANDROID_LINK.md (v1): TLS with a self-signed certificate, newline-delimited JSON.
+//
+// node android/tools/dev-desktop.mjs [--host IP] [--port N] [--name "My PC"] [--step MS] [--once] [--fake-chat] [--details] [--answers] [--diffs] [--usage] [--services]
+//
+// --details offers the "details" capability: the sessions then carry steps, finalLine, project (a folder
+// name) and color, like the real desktop with "Show session details on the phone" turned on. A phone that
+// did not ask for it gets the plain v1 sessions.
+//
+// --answers offers the "answers" capability: the scripted run then asks a FAKE question (two questions,
+// one single choice and one multi-select) and accepts an `answer` message, checked like the real desktop
+// (exact labels, one pick for a single choice, 1..n different picks for a multi-select).
+//
+// --diffs offers the "diffs" capability: Claude Code's session lists three files (file 1 a small change, file 2 a
+// long one of 250 lines that is cut to 200 and sent in two parts, file 3 too large to show) and `getDiff` is answered
+// like the real desktop does (kinds + - space @, 400 characters a line, parts of 100). Asking for any other file
+// is answered `gone`.
+//
+// --usage offers the "usage" capability: a Claude plan (5 hours 63 %, week 21 %) and a Codex plan (week 31 %, 2 free
+// resets) sent when the phone connects and every few steps with the percentages moving, like the real desktop's pills.
+//
+// --services offers the "services" capability with two FAKE cards (Stripe and Notion), as if the user had ticked both.
+// The cards carry only a headline and short lines, like the real ones.
+//
+// --fake-chat offers the "chat" capability with a FAKE provider, so the phone's Chat screen can be tried
+// without a key and without spending anything. Models: fake/echo, fake/other. Special messages:
+// /error a provider error /auth a refused key /slow a never-ending answer (Cancel it)
+// /long a 20 KB answer /rewrite a streamed text that the final answer replaces
+// anything else is answered word by word. Same limits as the real desktop (4000 characters,
+// one answer at a time, 12 sends per 10 minutes).
+//
+// It prints a pairing link (paste it in the app, or open it on the phone). Needs `openssl` on PATH.
+// Not for production: the real desktop link lives in the Tauri app.
+import tls from "node:tls";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+
+const arg = (name, def) => {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? process.argv[i + 1] : def;
+};
+const flag = (name) => process.argv.includes(`--${name}`);
+
+const V = 1;
+const MAX_LINE = 64 * 1024;
+const NAME = arg("name", os.hostname());
+const STEP_MS = Number(arg("step", "2500"));
+const TOKEN = arg("token", crypto.randomBytes(18).toString("base64url"));
+const lanIp = () => {
+ for (const list of Object.values(os.networkInterfaces()))
+ for (const a of list ?? []) if (a.family === "IPv4" && !a.internal) return a.address;
+ return "127.0.0.1";
+};
+const HOST = arg("host", lanIp());
+
+// The Mac's ApprovalRelay.fingerprint: SHA-256 of the fields joined by U+001F.
+export const fingerprint = (pill, session, tool, command, inputKey) =>
+ crypto.createHash("sha256").update([pill, session, tool, command, inputKey].join("\u001f"), "utf8").digest("hex");
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "coucou-dev-"));
+execFileSync("openssl", [
+ "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes",
+ "-keyout", path.join(dir, "key.pem"), "-out", path.join(dir, "cert.pem"),
+ "-days", "30", "-subj", "/CN=coucou-dev-desktop",
+], { stdio: "ignore" });
+const key = fs.readFileSync(path.join(dir, "key.pem"));
+const cert = fs.readFileSync(path.join(dir, "cert.pem"));
+fs.rmSync(dir, { recursive: true, force: true });
+const certSha256 = new crypto.X509Certificate(cert).fingerprint256.replaceAll(":", "").toLowerCase();
+
+const log = (...a) => console.log(...a);
+
+// Details the way the real desktop adds them (hub.rs): only for a phone that asked and was offered them.
+const DETAILS = {
+ integration_claude: { steps: ["Read · README.md", "Grep · TODO", "Edit · src/app.ts", "Bash · npm test", "Edit · src/app.ts"], project: "coucou", color: "#2DD4BF" },
+ agent_codex: { steps: ["Search · the code", "Read · lib.rs"], project: "api-server", color: "#E879F9" },
+ agent_gemini: { steps: [], project: "notes", color: "#8AB4F8" },
+};
+const FILES = {
+ integration_claude: [
+ { id: 1, name: "app.ts", added: 2, removed: 1 },
+ { id: 2, name: "long-file.ts", added: 125, removed: 125 },
+ { id: 3, name: "generated.json", added: 5400, removed: 0, tooLarge: true },
+ ],
+};
+const withFiles = (list) => list.map((s) => (FILES[s.pillId] ? { ...s, files: FILES[s.pillId] } : s));
+function fakeDiff(pillId, fileId) {
+ const f = (FILES[pillId] ?? []).find((x) => x.id === fileId);
+ if (!f) return [{ gone: true, name: "", added: 0, removed: 0, tooLarge: false, lines: [] }];
+ let rows = [];
+ if (f.tooLarge) rows = [];
+ else if (fileId === 2) rows = Array.from({ length: 250 }, (_, i) => [i === 0 ? "@" : i % 3 === 0 ? "+" : i % 3 === 1 ? "-" : " ", `row ${i} ` + "x".repeat(i === 5 ? 600 : 10)]);
+ else rows = [["@", "@@ 10"], [" ", "function greet(name) {"], ["-", " return 'Hello ' + name;"], ["+", " return `Hello, ${name}!`;"], [" ", "}"]];
+ const truncated = rows.length > 200;
+ rows = rows.slice(0, 200).map(([k, s]) => [k, s.slice(0, 400)]);
+ const chunks = [];
+ for (let i = 0; i < Math.max(1, rows.length); i += 100) chunks.push(rows.slice(i, i + 100));
+ return chunks.map((lines) => ({ gone: false, name: f.name, added: f.added, removed: f.removed, tooLarge: !!f.tooLarge, truncated, lines }));
+}
+const withDetails = (list, state) =>
+ list.map((s) => {
+ const d = DETAILS[s.pillId] ?? {};
+ const out = { ...s, ...(d.steps?.length ? { steps: d.steps } : {}), ...(d.project ? { project: d.project } : {}), ...(d.color ? { color: d.color } : {}) };
+ if (s.state === "finished") out.finalLine = "I updated the tests and everything passes.";
+ return out;
+ });
+
+// ── Fake chat (the messages are those of phone_link/chat.rs, with a fake provider) ─────────────
+const CHAT_MODELS = [
+ { id: "fake/echo", provider: "fake", label: "Fake · echo" },
+ { id: "fake/other", provider: "fake", label: "Fake · other" },
+];
+const CHAT_REASONS = {
+ 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.",
+ auth: "The provider refused the computer's key.",
+ provider: "The provider returned an error.",
+ canceled: "Canceled.",
+};
+const CHAT_MAX_TEXT = 4000;
+const CHAT_MAX_SENDS = 12;
+const CHAT_WINDOW_MS = 10 * 60 * 1000;
+const CHAT_PIECE = 8 * 1024;
+const chatSends = [];
+
+const FAKE_QUESTIONS = [
+ { question: "Which branch should I use?", multiSelect: false, options: [{ label: "main", description: "The default branch" }, { label: "develop", description: "" }] },
+ { question: "Which checks should I run?", multiSelect: true, options: [{ label: "Lint", description: "" }, { label: "Tests", description: "Unit tests" }, { label: "Build", description: "" }] },
+];
+
+// The same rules as phone_link/hub.rs: one list per question, labels exactly as offered and different;
+// exactly one for a single choice, at least one for a multi-select.
+function validPicks(questions, picks) {
+ if (!Array.isArray(picks) || picks.length !== questions.length) return null;
+ for (let i = 0; i < questions.length; i++) {
+ const p = picks[i];
+ const labels = questions[i].options.map((o) => o.label);
+ if (!Array.isArray(p) || p.length < 1 || new Set(p).size !== p.length) return null;
+ if (!p.every((x) => typeof x === "string" && labels.includes(x))) return null;
+ if (!questions[i].multiSelect && p.length !== 1) return null;
+ }
+ return picks;
+}
+
+function script(now) {
+ const s = (pillId, agent, state, statusText, stepIndex, stepCount) => ({ pillId, agent, state, statusText, stepIndex, stepCount, updatedAt: now });
+ return [
+ [s("integration_claude", "Claude Code", "thinking", "Reading the project", 1, 6)],
+ [s("integration_claude", "Claude Code", "working", "Editing files", 2, 6), s("agent_codex", "Codex", "searching", "Searching the code", 1, 4)],
+ "approval",
+ ...(flag("answers") ? ["question"] : []),
+ [s("integration_claude", "Claude Code", "working", "Building", 4, 6), s("agent_codex", "Codex", "question", "Which branch?", 3, 4)],
+ [s("integration_claude", "Claude Code", "finished", "Done", 6, 6), s("agent_codex", "Codex", "error", "Tests failed", 3, 4)],
+ [s("agent_gemini", "Gemini CLI", "sleeping", "Idle", 0, 0)],
+ ];
+}
+
+const server = tls.createServer({ key, cert, minVersion: "TLSv1.2" }, (sock) => {
+ sock.setNoDelay(true);
+ sock.setTimeout(90_000, () => sock.destroy());
+ const send = (o) => sock.writable && sock.write(JSON.stringify(o) + "\n");
+ let buf = "";
+ let authed = false;
+ let timer = null;
+ let pending = null; // { fingerprint }
+ let step = 0;
+ let chat = false; // negotiated in the hello
+ let details = false;
+ let answers = false;
+ let diffs = false;
+ let usage = false;
+ let services = false;
+ let asked = null; // { fingerprint, questions }
+ const sessionsMsg = (list) => ({ type: "sessions", sessions: diffs ? withFiles(details ? withDetails(list) : list) : details ? withDetails(list) : list });
+ let run = null; // { id, timer }
+ const chatError = (id, reason) => send({ type: "chatError", id, reason, message: CHAT_REASONS[reason] ?? "Something went wrong on the computer." });
+ const stopRun = () => { if (run) { clearTimeout(run.timer); clearInterval(run.timer); run = null; } };
+
+ const streamWords = (id, words, everyMs, done) => {
+ let i = 0;
+ const timer = setInterval(() => {
+ if (!run || run.id !== id) return clearInterval(timer);
+ if (i >= words.length) { clearInterval(timer); return done(); }
+ send({ type: "chatDelta", id, text: (i === 0 ? "" : " ") + words[i++] });
+ }, everyMs);
+ run.timer = timer;
+ };
+
+ const chatSend = (m) => {
+ const id = m.id;
+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) return;
+ const text = typeof m.text === "string" ? m.text : "";
+ if (!CHAT_MODELS.some((x) => x.id === m.model)) return chatError(id, "not_allowed");
+ if (!text.trim()) return chatError(id, "empty");
+ if ([...text].length > CHAT_MAX_TEXT) return chatError(id, "too_long");
+ if (run) return chatError(id, "busy");
+ const now = Date.now();
+ while (chatSends.length && now - chatSends[0] >= CHAT_WINDOW_MS) chatSends.shift();
+ if (chatSends.length >= CHAT_MAX_SENDS) return chatError(id, "rate");
+ chatSends.push(now);
+ log(`CHAT send ${m.model} ${JSON.stringify(text.slice(0, 60))}`);
+ run = { id, timer: null };
+ const done = (full) => { if (run?.id === id) { stopRun(); send(full === undefined ? { type: "chatDone", id } : { type: "chatDone", id, text: full }); } };
+ if (text.startsWith("/error")) { run.timer = setTimeout(() => { stopRun(); chatError(id, "provider"); }, 200); return; }
+ if (text.startsWith("/auth")) { run.timer = setTimeout(() => { stopRun(); chatError(id, "auth"); }, 200); return; }
+ if (text.startsWith("/slow")) return streamWords(id, Array.from({ length: 200 }, (_, i) => `slow${i}`), 300, () => done());
+ if (text.startsWith("/rewrite")) {
+ send({ type: "chatDelta", id, text: "<think>hmm" });
+ run.timer = setTimeout(() => done("Answer"), 100);
+ return;
+ }
+ if (text.startsWith("/long")) {
+ const big = "Lorem ipsum dolor sit amet. ".repeat(750);
+ for (let i = 0; i < big.length; i += CHAT_PIECE) send({ type: "chatDelta", id, text: big.slice(i, i + CHAT_PIECE) });
+ run.timer = setTimeout(() => done(), 50);
+ return;
+ }
+ streamWords(id, `Fake answer to: ${text}`.split(" "), 60, () => done());
+ };
+
+ const sendServices = () => {
+ if (!services) return;
+ send({
+ type: "services",
+ services: [
+ { id: "integration_stripe", title: "Stripe", headline: "12.50 EUR", reason: "Payments", items: [{ label: "Payment", detail: "+9.00 · 2m" }] },
+ { id: "integration_notion", title: "Notion", headline: "2", reason: "Recent", items: [{ label: "Roadmap", detail: "5m" }, { label: "Notes", detail: "1h" }] },
+ ],
+ });
+ };
+
+ const sendUsage = () => {
+ if (!usage) return;
+ const bump = (step * 7) % 30;
+ send({
+ type: "usage",
+ claude: { fiveHour: { pct: 40 + bump, resetsAt: Date.now() + 95 * 60_000 }, sevenDay: { pct: 21, resetsAt: Date.now() + 3 * 86_400_000 }, plan: "max", updatedAt: Date.now() },
+ codex: { sevenDay: { pct: 31, resetsAt: Date.now() + 2 * 86_400_000 }, resetCredits: 2, plan: "plus", updatedAt: Date.now() },
+ });
+ };
+
+ const advance = () => {
+ sendUsage();
+ if (step === 0) sendServices();
+ const entries = script(Date.now());
+ const e = entries[step % entries.length];
+ step++;
+ if (e === "question") {
+ const questions = FAKE_QUESTIONS;
+ const fp = fingerprint("integration_claude", "dev_session", "AskUserQuestion", JSON.stringify(questions), `q${step}`);
+ asked = { fingerprint: fp, questions };
+ send(sessionsMsg([
+ { pillId: "integration_claude", agent: "Claude Code", state: "question", statusText: "Asking you a question", stepIndex: 3, stepCount: 6, updatedAt: Date.now() },
+ ]));
+ send({ type: "question", pillId: "integration_claude", fingerprint: fp, createdAt: Date.now(), questions });
+ log(`QUESTION sent ${fp}`);
+ } else if (e === "approval") {
+ const command = "npm run build";
+ const fp = fingerprint("integration_claude", "dev_session", "Bash", command, `n${step}`);
+ pending = { fingerprint: fp };
+ send(sessionsMsg([
+ { pillId: "integration_claude", agent: "Claude Code", state: "approval", statusText: "Waiting for your approval", stepIndex: 3, stepCount: 6, updatedAt: Date.now() },
+ ]));
+ send({ type: "approval", pillId: "integration_claude", fingerprint: fp, tool: "Bash", command, createdAt: Date.now() });
+ log(`APPROVAL sent ${fp}`);
+ } else {
+ send(sessionsMsg(e));
+ }
+ };
+
+ const handle = (line) => {
+ let m;
+ try { m = JSON.parse(line); } catch { return sock.destroy(); }
+ if (!authed) {
+ if (m.type !== "hello") return sock.destroy();
+ const ok = m.v === V && typeof m.token === "string" &&
+ m.token.length === TOKEN.length && crypto.timingSafeEqual(Buffer.from(m.token), Buffer.from(TOKEN));
+ if (!ok) { send({ type: "error", code: "auth", message: "bad token or version" }); log("AUTH rejected"); return sock.end(); }
+ authed = true;
+ log(`HELLO ok device=${JSON.stringify(m.device)}`);
+ chat = flag("fake-chat") && Array.isArray(m.caps) && m.caps.includes("chat");
+ details = flag("details") && Array.isArray(m.caps) && m.caps.includes("details");
+ answers = flag("answers") && Array.isArray(m.caps) && m.caps.includes("answers");
+ diffs = flag("diffs") && Array.isArray(m.caps) && m.caps.includes("diffs");
+ services = flag("services") && Array.isArray(m.caps) && m.caps.includes("services");
+ usage = flag("usage") && Array.isArray(m.caps) && m.caps.includes("usage");
+ const offered = [...(chat ? ["chat"] : []), ...(details ? ["details"] : []), ...(answers ? ["answers"] : []), ...(diffs ? ["diffs"] : []), ...(usage ? ["usage"] : []), ...(services ? ["services"] : [])];
+ send({ type: "welcome", v: V, desktop: NAME, os: process.platform, ...(offered.length ? { caps: offered } : {}) });
+ advance();
+ timer = setInterval(advance, STEP_MS);
+ return;
+ }
+ switch (m.type) {
+ case "ping": return send({ type: "pong" });
+ case "bye": log("BYE"); return sock.end();
+ case "chatModels": return chat && send({ type: "chatModels", models: CHAT_MODELS });
+ case "chatSend": return chat && chatSend(m);
+ case "chatCancel": {
+ if (chat && run && run.id === m.id) { const id = run.id; stopRun(); chatError(id, "canceled"); log(`CHAT canceled ${id}`); }
+ return;
+ }
+ case "chatReset": {
+ if (chat) { if (run) { const id = run.id; stopRun(); chatError(id, "canceled"); } log("CHAT reset"); }
+ return;
+ }
+ case "getDiff": {
+ if (!diffs || typeof m.pillId !== "string" || !m.pillId || !Number.isInteger(m.fileId)) return;
+ log(`GETDIFF ${m.pillId} ${m.fileId}`);
+ const parts = fakeDiff(m.pillId, m.fileId);
+ parts.forEach((p, i) => send({ type: "diff", pillId: m.pillId, fileId: m.fileId, part: i, parts: parts.length, ...p }));
+ return;
+ }
+ case "answer": {
+ const picks = answers && asked && m.fingerprint === asked.fingerprint ? validPicks(asked.questions, m.picks) : null;
+ if (picks) {
+ log(`ANSWER accepted ${m.fingerprint} (${picks.length} question(s))`); // the labels are not logged
+ send({ type: "approvalResolved", fingerprint: asked.fingerprint });
+ asked = null;
+ if (flag("once")) setTimeout(() => process.exit(0), 200);
+ } else {
+ log(`ANSWER refused ${m.fingerprint}`);
+ }
+ return;
+ }
+ case "decision": {
+ if (pending && m.fingerprint === pending.fingerprint && (m.decision === "allow" || m.decision === "deny")) {
+ log(`DECISION ${m.decision} ${m.fingerprint}`);
+ send({ type: "approvalResolved", fingerprint: pending.fingerprint });
+ pending = null;
+ if (flag("once")) setTimeout(() => process.exit(0), 200);
+ } else {
+ log(`DECISION ignored ${m.fingerprint}`);
+ }
+ return;
+ }
+ default: return;
+ }
+ };
+
+ sock.on("data", (d) => {
+ buf += d.toString("utf8");
+ if (buf.length > MAX_LINE * 2) return sock.destroy();
+ let i;
+ while ((i = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, i);
+ buf = buf.slice(i + 1);
+ if (line.length > MAX_LINE) return sock.destroy();
+ if (line) handle(line);
+ }
+ });
+ sock.on("close", () => { if (timer) clearInterval(timer); stopRun(); });
+ sock.on("error", () => {});
+});
+
+server.listen(Number(arg("port", "47821")), "0.0.0.0", () => {
+ const port = server.address().port;
+ const link = `coucou://pair?v=${V}&host=${HOST}&port=${port}&fp=${certSha256}&token=${TOKEN}&name=${encodeURIComponent(NAME)}`;
+ log(JSON.stringify({ listening: port, fp: certSha256, link }));
+ if (!flag("quiet")) console.error(`\nPairing link (paste it in Coucou for Android):\n${link}\n`);
+});
diff --git a/android/tools/outfit-trace.mjs b/android/tools/outfit-trace.mjs
new file mode 100644
index 00000000..4ee197d8
--- /dev/null
+++ b/android/tools/outfit-trace.mjs
@@ -0,0 +1,153 @@
+#!/usr/bin/env node
+// Runs the PC's outfit drawing (windows/src/mochi/outfits.ts) against a recording context and prints every
+// drawing call as JSON. The Kotlin port (mochi/outfit/Outfits.kt) is replayed on the same cases and its calls
+// are compared number by number (OutfitParityTest), so the phone draws what the PC draws.
+//
+// node --import windows/tests/setup.mjs android/tools/outfit-trace.mjs > trace.json
+//
+// The case list is part of the output: the Kotlin test replays exactly those cases.
+import { drawOutfitBehind, drawOutfitFront, drawWardrobeIcon, makeHead } from "../../windows/src/mochi/outfits.ts";
+
+// ── CSS colours (the same forms the outfits use) ─────────────────────────────────
+function css(s) {
+ const t = s.trim();
+ if (t.startsWith("#")) {
+ const h = t.slice(1);
+ if (h.length === 3) return [...h].map((c) => parseInt(c + c, 16)).concat(1);
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)).concat(1);
+ }
+ const m = /^(rgba?)\((.*)\)$/.exec(t);
+ if (!m) throw new Error(`colour ${s}`);
+ const p = m[2].split(",").map((x) => Number(x.trim()));
+ return m[1] === "rgb" ? [p[0], p[1], p[2], 1] : [p[0], p[1], p[2], p[3]];
+}
+
+// ── Recording Path2D and context ─────────────────────────────────────────────────
+class RecPath {
+ constructor() { this.segs = []; }
+ moveTo(...a) { this.segs.push(["M", ...a]); }
+ lineTo(...a) { this.segs.push(["L", ...a]); }
+ quadraticCurveTo(...a) { this.segs.push(["Q", ...a]); }
+ bezierCurveTo(...a) { this.segs.push(["C", ...a]); }
+ arcTo(...a) { this.segs.push(["AT", ...a]); }
+ arc(...a) { this.segs.push(["A", ...a]); }
+ ellipse(...a) { this.segs.push(["E", ...a]); }
+ rect(...a) { this.segs.push(["R", ...a]); }
+ closePath() { this.segs.push(["Z"]); }
+ addPath(p) { this.segs.push(...p.segs); }
+}
+globalThis.Path2D = RecPath;
+
+function gradient(kind, args) {
+ return { kind, args, stops: [], addColorStop(o, c) { this.stops.push([o, ...css(c)]); } };
+}
+const styleOf = (s) => (typeof s === "string" ? ["solid", ...css(s)] : [s.kind, ...s.args, s.stops]);
+
+class Rec {
+ constructor(log) {
+ this.log = log;
+ this.canvas = { width: 640, height: 480 };
+ this.cur = new RecPath();
+ this.stack = [];
+ this.fillStyle = "#000000";
+ this.strokeStyle = "#000000";
+ this.lineWidth = 1;
+ this.lineCap = "butt";
+ this.lineJoin = "miter";
+ this.globalAlpha = 1;
+ this.skipRestore = false;
+ this.scratchLog = null;
+ }
+ save() {
+ this.stack.push([this.fillStyle, this.strokeStyle, this.lineWidth, this.lineCap, this.lineJoin, this.globalAlpha]);
+ this.log.push(["save"]);
+ }
+ restore() {
+ const s = this.stack.pop();
+ if (s) [this.fillStyle, this.strokeStyle, this.lineWidth, this.lineCap, this.lineJoin, this.globalAlpha] = s;
+ if (this.skipRestore) { this.skipRestore = false; return; }
+ this.log.push(["restore"]);
+ }
+ translate(x, y) { this.log.push(["translate", x, y]); }
+ scale(x, y) { this.log.push(["scale", x, y]); }
+ rotate(a) { this.log.push(["rotate", a]); }
+ setTransform() {}
+ getTransform() { return {}; }
+ clearRect() {}
+ beginPath() { this.cur = new RecPath(); }
+ moveTo(...a) { this.cur.moveTo(...a); }
+ lineTo(...a) { this.cur.lineTo(...a); }
+ quadraticCurveTo(...a) { this.cur.quadraticCurveTo(...a); }
+ bezierCurveTo(...a) { this.cur.bezierCurveTo(...a); }
+ arcTo(...a) { this.cur.arcTo(...a); }
+ arc(...a) { this.cur.arc(...a); }
+ ellipse(...a) { this.cur.ellipse(...a); }
+ closePath() { this.cur.closePath(); }
+ fill(p) { this.log.push(["fill", (p ?? this.cur).segs.slice(), styleOf(this.fillStyle)]); }
+ stroke(p) { this.log.push(["stroke", (p ?? this.cur).segs.slice(), styleOf(this.strokeStyle), this.lineWidth, this.lineCap, this.lineJoin]); }
+ clip(p, rule) { this.log.push(["clip", p.segs.slice(), rule === "evenodd"]); }
+ fillRect(x, y, w, h) { this.log.push(["fill", [["R", x, y, w, h]], styleOf(this.fillStyle)]); }
+ createLinearGradient(...a) { return gradient("lin", a); }
+ createRadialGradient(x, y, r0, x2, y2, r1) { return gradient("rad", [x, y, r0, r1]); }
+ drawImage() {
+ // withLayer: save(); setTransform(); globalAlpha *= alpha; drawImage(scratch); restore().
+ const last = this.log.pop();
+ if (!last || last[0] !== "save") throw new Error("unexpected layer sequence");
+ this.log.push(["layer", this.globalAlpha, this.scratchLog.splice(0)]);
+ this.skipRestore = true;
+ }
+}
+
+// outfits.ts keeps one scratch canvas for good, so there is one scratch recorder too.
+const scratchLog = [];
+const scratch = new Rec(scratchLog);
+globalThis.document = { createElement: () => ({ width: 0, height: 0, getContext: () => scratch }) };
+
+function newMain() {
+ const log = [];
+ scratchLog.length = 0;
+ const main = new Rec(log);
+ main.scratchLog = scratchLog;
+ return { main, log };
+}
+
+// ── The cases ────────────────────────────────────────────────────────────────────
+export const OUTFITS = ["partyHat", "beanie", "crown", "sunglasses", "roundGlasses", "bow", "scarf", "witchHat", "pumpkin", "santaHat", "bunnyEars"];
+const HEADS = [
+ { R: 40, yaw: 0, pitch: 0, physDx: 0, physDy: 0 },
+ { R: 60, yaw: 0.4, pitch: -0.2, physDx: 0.3, physDy: -0.2 },
+ { R: 12, yaw: 0, pitch: 0, physDx: 0, physDy: 0 },
+ { R: 50, yaw: 2.2, pitch: 0.1, physDx: 0, physDy: 0 },
+ { R: 45, yaw: -0.7, pitch: 0.3, physDx: -0.4, physDy: 0.5 },
+];
+const STATES = [
+ { presence: 1, morph: 0 },
+ { presence: 0.6, morph: 0 },
+ { presence: 0.3, morph: 0 },
+ { presence: 1, morph: 0.4 },
+ { presence: 1, morph: 0.6 },
+];
+
+const cases = [];
+for (const outfit of OUTFITS) {
+ HEADS.forEach((head, hi) => {
+ STATES.forEach((state, si) => {
+ if (si > 0 && hi > 1) return; // the transitions are checked on two heads
+ for (const part of ["behind", "front"]) cases.push({ kind: part, outfit, head, state });
+ });
+ });
+}
+for (const outfit of OUTFITS) cases.push({ kind: "icon", outfit, size: 40 });
+
+function run(c) {
+ const { main, log } = newMain();
+ if (c.kind === "icon") {
+ drawWardrobeIcon(main, c.size, c.outfit, "none", "AUTO"); // a chosen outfit: the little Mochi, no label
+ } else {
+ const h = makeHead(c.head.R, c.head.yaw, c.head.pitch, c.head.physDx, c.head.physDy);
+ (c.kind === "behind" ? drawOutfitBehind : drawOutfitFront)(main, c.outfit, h, c.state);
+ }
+ return log;
+}
+
+process.stdout.write(JSON.stringify(cases.map((c) => ({ ...c, ops: run(c) }))));