Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge main into phone polish and seal branch history requests

deehw0c5e15e0333d
diff --cc docs/research/2026-09-28-phone-overnight.md
index c89ced773,000000000..b8413c6f6
mode 100644,000000..100644
--- a/docs/research/2026-09-28-phone-overnight.md
+++ b/docs/research/2026-09-28-phone-overnight.md
@@@ -1,216 -1,0 +1,236 @@@
+# Phone app, overnight 2026-09-27 → 28
+
+The goal set at bedtime was to make the Harness phone app world class. That meant:
+- test coverage and edge cases;
+- fixing the bugs found;
+- improving the UI/UX;
+- a panel of AI users playing the target audience, whose feedback drives the fine-tuning.
+
+That audience is people with strong consumer-app taste who now run Claude Code and Codex and want to manage them from a phone.
+
- Everything below is on branch `phone-overnight-polish` (pushed to origin), in [PR #398](https://github.com/autonomous-ai/openharness/pull/398). Nothing has been merged or released. **The last section is the handoff for the next agent.**
++This work is tracked in [PR #398](https://github.com/autonomous-ai/openharness/pull/398), from branch `phone-overnight-polish`. The user has authorized merging it to `main` and installing a local iPhone build for manual review; the PR records the merge status. No store release is included. **The last section is the handoff for the mobile team.**
+
+## In one screen
+
- - **Tests:** 486 → 1,555 overnight → **1,600** after continuation (plus 25 render tests skipped in the ordinary suite; all 25 pass when rendering is enabled). The whole suite passes. `flutter analyze` is clean outside `third_party/`.
- - **Coverage:** 50.4% → 87.0% overnight → **88.8%** (18,185/20,485 lines), not counting `third_party/`.
++- **Tests:** 486 → 1,555 overnight → **1,614** after continuation and main integration (plus 25 render tests skipped in the ordinary suite; all 25 pass when rendering is enabled). The whole suite passes. `flutter analyze` is clean outside `third_party/`.
++- **Coverage:** 50.4% → 87.0% overnight → **88.7%** (18,450/20,790 lines; 88.8% before integrating main's branch/PR-history feature), not counting `third_party/`.
+
+ | Area | Coverage |
+ |---|---|
+ | e2ee, api, auth, notify, theme | 100% |
+ | viewer | 99.2% |
+ | p2p | 98.5% |
- | core | 97.2% |
++ | core | 96.3% |
+ | usage | 95.0% |
+ | ws | 94.8% |
+ | analytics | 92.1% |
+ | widgets | 89.8% |
- | phone | 89.1% |
++ | phone | 89.0% |
+ | shared | 81.2% |
+ | state | 83.0% |
+ | demo | 79.9% |
+ | terminal | 84.4% |
+ | logging | 87.6% |
+ | settings | 100.0% |
+ | clipboard | 88.9% |
+
+- **Dead code:**
+ - 52 files and about 17,100 lines the phone never runs were deleted. Each deletion was proved with tree-shaken AOT builds for iOS and Android.
+ - The desktop's half of `AppNotifier` was cut: 7,100 more lines, 13 files. `viewer` is now non-nullable.
+ - The continuation removes the remaining handoff list: unused dial routing and grid navigation, local plaintext transport, the unauthenticated local API mode, local-file opening and the CLI log channel. The cleanup was prepared and tested in a disposable copy before application.
- - **Bugs:** 40 real bugs fixed, each with a regression test (listed below). The continuation fixes queued log notifications after disposal and misleading local-daemon explanations for phone backend failures.
++- **Bugs:** 41 real bugs fixed, each with a regression test (listed below). The continuation fixes queued log notifications after disposal and misleading local-daemon explanations for phone backend failures. Main integration also fixes encryption of branch/PR-history requests.
+- **Test safety:** every test now runs in a throwaway home (`test/flutter_test_config.dart`), so no test can read or write a developer's `~/.harness`. `test/test_home_guard_test.dart` pins this.
+- **Offline verification:** HTTP clients are blocked by default in tests. API and WebSocket tests now use in-memory transports, including handshakes, token refreshes and reconnects. The simulator tour launches `SampleApp` directly without reading a saved account.
+- **Review panel:** the four requested personas completed rounds 3 and 4. All now score the app **8+/10**; the round-4 mean is **8.05/10**. [Round-3/4 report](2026-09-28-phone-panel-rounds-3-4.md).
+
+## The review panel
+
+Five personas each reviewed renders of every phone screen. In round 2 they also saw an 18-screen walk-through of the real app, recorded on the iOS simulator in sample mode.
+
+| Persona | Lens | Round 1 | Round 2 | Round 3 | Round 4 |
+|---|---|---|---|---|---|
+| Maya | design lead on two iconic consumer apps | 6 | 7 | 7 | 8 |
+| Theo | founder of a Things/Superhuman/Linear-style productivity app | 6 | – | – | – |
+| Priya | runs 6–10 Claude Code and Codex harnesses across three machines | 6 | 7 | 7.5 | 8.2 |
+| Sam | first-time user with consumer taste; Claude Code on the Mac, no Harness | 6 | 7 | 7 | 8 |
+| Jordan | former Apple Design Award juror (HIG, accessibility) | 6 | 7 | 7 | 8 |
+
+### Round 1 findings that all five agreed on, and what happened
+
+| Finding | Outcome |
+|---|---|
+| The terminal is clipped at the right edge (a blocker, 5/5) | **A fixture bug, not the app.** The render test seeded a 46-column screen into a 42-column view. Fixed the fixture; the simulator walk-through confirms the live app fits. |
+| The mic covers the agent's input line | **Kept.** Your decision: "the current mic location is perfect". |
+| Voice sends words you never saw | **Kept.** Your decision: auto-send. |
+| "Harness" confuses as a noun | **Kept.** A harness is a session: one agent, many harnesses. It is now taught where it is first met: New ("A harness is one session of an agent"), How Harness works, and the "N harnesses" count. |
+| Every other computer needs its own password | **Fixed.** A locked computer unlocks by scanning its Add Phone QR; the password stays as the fallback for servers. |
+| Two different set-up screens | **Fixed.** There is one set-up page (the website's download menu). Signed in, it also watches for the computer and pairs by scan. |
+| Settings duplicates and unclear labels | **Fixed:** "Phone name", "App colors", the lone "usage" header removed, readable heading contrast. |
+| VoiceOver can't read the terminal or reach Find or New | **Fixed.** |
+| The scroll-position tag "[22/39]" is jargon | **Removed.** Your call: "we don't need the scrolling indicator". |
+
+### Round 2 fixes
+
+- **The sample.** Its agents stopped parroting your words back ("On it — run the tests…"). This matters because the "how it works" video is recorded from the sample. It also announces permissions the way the daemon does ("Approve Bash command: psql …") rather than "Do you want to proceed?", and names its computer "studio" rather than the fixture id "sample-studio".
+- **The line above the mic** hides while you read history; it used to print over the rows being read.
+- **The key strip** opens on its own keys. It used to scroll to the agent's `shift+tab` hint on every open, which pushed **esc** off the edge while the agent said "esc to interrupt".
+- **VoiceOver:** it can cancel a voice take, hears "Asking: …" when a question opens, and reads the line above the mic as a live region.
+- **Copy:** "5 harnesses", "Leave the sample" (both places), "Choose an agent and a project".
+- **The scan page** says the link is end-to-end encrypted, which was the first-time user's trust gap.
+- **New** shows branch, approvals and profile all the time. The `[+]` toggle is gone; it hid the two things worth checking before a harness starts, over an empty half-screen.
+- **Settings:** Usage, Computers and Phone name join the account group. There is no lone Usage card, and Phone name is no longer filed under *terminal*.
+- **"Stop this harness…"** stays small at the foot of the menu but is now red; faint grey read as disabled.
+- **Form rows** put the label on the value's first line; "approvals" used to sit beside its note.
+
+### Rounds 3 and 4
+
+- The attention line has a fixed yellow dot, solid backing and readable text aligned to the terminal gutter.
+- Chooser sheets fit their content, align headings with rows and support native drag dismissal.
+- Field placeholders have stronger contrast, verified numerically in a regression test.
+- Unlock uses the desktop's verified `Machines ▸ computer ▸ Set password` route and identifies the password as the Harness phone password.
+- The sample is prominent on Welcome and setup, and labels pickup, Focus, Find and New. Its terminal input hint fits beside the mic.
+- The Settings avatar is neutral. Incomplete sign-in codes visibly disable Sign in. New's compact keyboard summary puts the project first.
+- All 25 screens were rendered again. The sample simulator walkthrough was recorded again and now captures 19 states, including the written help page.
+
+These are AI persona reviews of offline artifacts. They establish the visual score; live VoiceOver, real-device speech and production connection behavior require separate verification.
+
+## Bugs fixed (each with a regression test)
+
+**Sign-in and pairing**
+- A scanned pairing code no longer outlives its session.
+- A refresh in flight cannot bring back a signed-out session.
+- A rate-limited refresh no longer signs the phone out.
+- No sign-out from a closed socket, and no hot loop on a refused token.
+- Linking never throws, so Unlock and Pairing cannot hang for good.
+- Pairing times out on a dial that never opens, and keeps a lockout's retry time.
+- A scanned code whose account cannot be read no longer hangs on "Pairing…".
+- Pairing by password names this phone to the computer (it was "harness link").
+
+**Connection**
+- A replaced relay connection can no longer speak for its machine.
+- A replayed welcome or rekey cannot roll the group key back.
+- A data channel closing under an open link no longer throws uncaught.
+- A second `terminal_ready` for one open no longer leaks a heartbeat.
+- A locked state file no longer stops a machine reconnecting for good.
+- Phone backend failures no longer tell the user that a local daemon is down or restarting.
++- Branch/PR-history requests are encrypted and held until the handshake completes; the machine no longer rejects them with `E2EE_REQUIRED`.
+- A terminal switched off by an unanswered negotiation is asked about again.
+
+**Terminal and Focus**
+- The terminal follows a keyframe that swaps its screen, not only a rebuild from above.
+- A pager guess reopened after its stream died no longer takes the terminal.
+- A tap reopens a dead stream.
+- The kept screen of an agent read a moment ago is shown, not a blank page.
+- A conversation open in a terminal is refused in words, not as a lost reply.
+- A question's refusal of a voice answer says why, not "terminal not taking input".
+- A resume the machine never received is sent again, not checked forever.
+- A stopped harness stays on the phone; the minute's sync sees every field it draws.
+
+**Layout**
+- An emoji where a name is cut no longer crashes Focus or Settings.
+- The Focus title and the sample's end card no longer overflow at large text.
+- The welcome screen and pairing scroll instead of overflowing.
+- New's dock scrolls instead of overflowing on a small phone.
+- The attaching skeleton shows with Reduce Motion on.
+
+**Dialogs**
+- A field inside an app dialog gets the focus it asks for, and the keyboard.
+- A rename answer landing as the dialog closes no longer pops the page under it.
+
+**Usage and notifications**
+- A reset time past what a DateTime holds no longer drops a machine's usage.
+- A partial or failed usage cycle keeps the figures it could not renew.
+- One failed start of the notification plugin no longer silences the launch.
+- A notification body is never cut through the middle of an emoji.
+
+**Privacy and logs**
+- The debug log keeps the length of a harness's first task and a Find search, never the words.
+- Log redaction blanks plain-base64 bearer tokens, Basic auth and sign-in codes in URLs.
+- An analytics event trimmed while on the wire no longer takes the next one with it.
+- A busy analytics visit keeps `analytics.json` within a minute of the clock.
+- A queued log update no longer notifies a disposed stream.
+
+## Decisions already made by the user (do not re-propose)
+
+- Voice keeps auto-send.
+- The mic stays where it is; the terminal is full screen under it.
+- Keep the word "harness" (harness = session; one agent, many harnesses). Teaching it is fine; renaming it is not.
+- No scroll-position indicator. The "api-fix asking" label stays.
+- PRs only. The user merges and releases; nothing is merged or released without their explicit word.
+
- ## Handoff for the next agent
++## Handoff for the mobile team
+
+### State
+
- - Branch `phone-overnight-polish`, pushed. [PR #398](https://github.com/autonomous-ai/openharness/pull/398) is open for the user to review and merge. The continuation and its validation are included; no merge or release has run.
++- Branch `phone-overnight-polish`; [PR #398](https://github.com/autonomous-ai/openharness/pull/398) contains the continuation and main integration. The user explicitly authorized merging and a local iPhone install for manual review. Check the PR for the resulting merge commit; no store release was requested.
+- Merged into it and finished: `coverage-rest` (coverage engineer), `desktop-cut` (the desktop's half of the notifier), and the phone-screens and state-core engineers' passes. No engineer is still running.
+- Never commit `mobile/ios/Runner.xcodeproj/project.pbxproj`. It carries the local signing team and stays modified in the worktree.
+
++### Code map for the mobile team
++
++The runtime is a standalone Flutter package in `mobile/`; agents run on linked computers, never on the phone. Shared code was copied from desktop and now differs substantially: port fixes deliberately rather than replacing directories.
++
++| Location under `mobile/` | Responsibility |
++|---|---|
++| `lib/main.dart`, `lib/app_shell.dart` | Startup, authentication and root shell |
++| `lib/phone/` | Focus terminal, Find, New, voice, approvals, pairing and settings pages; `PhoneShell` owns one navigation stack |
++| `lib/state/` | `AppNotifier`, machine/agent lifecycle, terminal panes and desk synchronization |
++| `lib/terminal/`, `third_party/xterm/` | Terminal sessions/rendering, input, links and media; xterm is a patched vendor copy |
++| `lib/{auth,api,viewer,e2ee,ws,p2p}/` | Sign-in/linking, backend API, encrypted relay and WebRTC transport |
++| `lib/{core,settings,shared,theme}/` | Models, preferences and shared UI foundations |
++| `lib/demo/` | Offline sample runtime, including its own entry point |
++| `test/`, `test/render/`, `integration_test/` | Regression tests, 25 screen renders and the sample simulator tour |
++
++The full tests run from `mobile/` in the monorepo: protocol checks read CLI source, and a branch-history UI test imports a desktop font fixture. Desktop-only routing, local CLI transport and grid controls have been removed. The new `session_work_page.dart` preserves main's current branch and PR-history UI.
++
+### How to run
+
+From `mobile/`, with Flutter 3.47.2:
+
+- **Everything:** `flutter test`, about one minute. For coverage, `flutter test --coverage`, then read `coverage/lcov.info`.
+- **Screen renders:** `PHONE_RENDER_DIR=<dir> flutter test test/render/phone_screens_render_test.dart`. It writes 25 PNGs, one per screen. The fixture terminal is 42 columns, so canned lines must fit in 42.
+- **Walk-through on the iOS simulator, sample mode only:** `HARNESS_JOURNEY_OUT=<dir> flutter drive --driver=test_driver/journey_driver.dart --target=integration_test/tour_test.dart`.
+
+### Rules
+
+- **No real account, device or daemon from any automated or AI-driven input.** Personas and engineers drive only sample mode, renders and the simulator in sample mode.
+ - No test may use the network.
+ - Engineers do not push; the lead merges their branches.
+- Unset `TMUX` in tests.
+- Every git and gh action is done as `deehw`.
+- No private data in the repo (no home paths, real usernames or emails).
+
+### Continuation completed
+
+1. Opened PR #398 with this report as its starting summary.
+2. Ran the four-person panel twice more. Round 4: Maya 8, Priya 8.2, Sam 8, Jordan 8; all would use it daily.
+3. Completed the round-2 attention-line, sheet, placeholder, Unlock-copy, sample-discovery and avatar work.
+4. Removed every item in the remaining dead-code list: `SpokenTaskRequest` and its unused routing stream/handler; `selectAutonomousEnv`; `hasNavigationRail` and unused pin/grid-keyboard methods; `paneFocusRequest`, `seedSwarm`, `openAgentFromDial`; `DialState.restore`; local plaintext WebSockets; ApiClient's no-auth local mode; the local-machine terminal-file branch; and `cliLog`. Caller searches and the CLI's local-only event routing established that these paths cannot serve the phone. The explicitly approved patch was tested before and after application.
+5. Added coverage in the requested order: settings persistence/reset; clipboard failures; logging lifecycle; terminal preferences, downloads and link opening; sample requests/lifecycle; and layout restoration/write coalescing. Every new real bug has a regression test.
- 6. Final validation: **1,600 tests pass**, 25 conditional render skips; **88.8% line coverage** excluding `third_party/`; analyzer clean outside `third_party/`. The separate 25-render run and 19-state sample simulator tour pass.
++6. Final validation: **1,614 tests pass**, 25 conditional render skips; **88.7% line coverage** excluding `third_party/`; analyzer clean outside `third_party/`. The separate 25-render run and 19-state sample simulator tour pass.
++
++7. Integrated current `main`, retaining branch/PR history while keeping the phone cleanup. The protocol parity test caught an unsealed `git_pull_request`; a codec regression now verifies handshake gating and encryption. The numeric scroll-position tag remains removed, with its existing scrolling test passing.
+
+### Remaining observations
+
+- The [round-4 report](2026-09-28-phone-panel-rounds-3-4.md) records optional finishing details: retain computer/project identity in asking Find rows, improve long-value spacing and compact agent labels, and simplify recovery/glossary copy. None blocks the panel's 8/10 threshold.
+- Future coverage work can concentrate on the remaining state and sample branches. The desktop-only paths removed in this continuation should not be restored merely to exercise them in tests.
+- The proposals below remain exactly as left by the user. No proposal has been implemented or reclassified as approved.
+
+### Proposals that need the user's decision (do not build without it)
+
+- **Push notifications** that say what a harness wants, with Yes/No as notification actions. Priya and Sam both named this as the thing that makes the app daily.
+- **A one-line Focus header** (`fix-login · studio:web`), pinned while reading history. The branch line would move to the title sheet.
+- **Dynamic Type.** `lib/app_shell.dart` pins text scaling to the in-app "Text size", so iOS Larger Text is ignored. Jordan rated this a blocker.
+- **Settings duplicates:** "Text size" beside the terminal's "Size", and "App colors" beside "Colors". All four personas asked for one of each. They mirror separate desktop settings, which is why they were kept.
+- **Streaming the words into the `>` line while recording.** This is display only; auto-send is unchanged. First check whether the speech engine gives partial results.
+- **The pick-up screen.** Two personas called it Find with a headline; they suggest launching into the last harness, or Find.
+- **Unseen finished harnesses under "needs you"**, with their last line.
+- **Discoverability:** a visible `⌄` on the Focus title, and a visible route to Find and New for Voice Control and Switch Control users.
+- **Sentence case** ("New harness", "Open folder"). This touches desktop naming, which uses "New Harness".
+
+### Outside this branch
+
+- **Desktop PR #393** ("Your phones", with Remove, on the Mac) is waiting for the user to merge it.
+- **Website `/pair` page:** PR autonomous-ai/autonomous-code#4 needs a `_web` tag to deploy.
+- **TestFlight** is blocked until someone is on the release Mac, which has the App Store Connect key. Until then, the phone is a local `devicectl` install only.
diff --cc mobile/README.md
index 8dfab72d7,63d6ef3a8..9225b05d6
--- a/mobile/README.md
+++ b/mobile/README.md
@@@ -2,22 -2,22 +2,29 @@@
A viewer onto the machines this device has linked — one agent at a time, on a phone.
++Start with the [mobile team handoff](../docs/research/2026-09-28-phone-overnight.md)
++for recent changes, the code map, validation and outstanding product decisions.
++
```bash
flutter pub get
flutter analyze # 0 issues outside third_party/xterm
--flutter test
++env -u TMUX flutter test
flutter run # -d <your device>
flutter build ios --debug --no-codesign
flutter build apk --debug
```
--## This package depends on nothing else in this repo
++## Standalone runtime, monorepo tests
`harness_mobile` is standalone. It used to be a thin shell over `path: ../desktop`, which meant every
desktop-only concern was a phone concern too: the app pulled in `window_manager`, `file_selector`,
`desktop_drop`, `sqlite3` and `go_router`, and the phone build was pinned to a Flutter app whose
targets are macOS and Linux.
++Run the full tests from `mobile/` inside this repository: encryption protocol checks read CLI
++source, and the branch-history UI tests use a desktop font fixture. Automated app interaction
++uses only the offline sample and simulator; tests must not contact real accounts or daemons.
++
The app it runs now lives under `lib/`, in the same folders the desktop app uses for it:
| | |
@@@ -33,41 -33,41 +40,26 @@@
Two folders are this package's own, and have no counterpart on the desktop:
--- **`lib/phone/`** — the shell a phone needs that a window does not: tabs, cards, sheets, the
-- one-agent-at-a-time terminal page.
++- **`lib/phone/`** — Focus, Find, New, voice input, approvals, onboarding and settings. `PhoneShell`
++ owns one navigation stack rooted in `AgentHome`, with the full-screen terminal in `TerminalPage`.
- **`lib/p2p/`** — the phone's second wire to each machine. The `terminal-v1` WebRTC data channel the
harness CLI opens with werift on the desktop's behalf, so a terminal rides p2p or TURN when it can
and the relay only when it must.
++`lib/demo/` provides the offline sample runtime. `test/render/` captures the phone screens;
++`integration_test/tour_test.dart` opens `SampleApp` directly for the simulator walkthrough.
++
## The account's tabs are the desk's, here too
--The tabs a person has are one document per account on the backend (`/api/desk`), the same on every
--computer they sign in on. The desktop owns its half of that in `desktop/lib/state/desk_sync.dart`,
--which is **vendored here unchanged**; `lib/state/phone_desk.dart` is this package's own other half,
--and it is deliberately not the window's:
--
--- A window's tabs ARE its `swarms`, so the desktop diffs that projection after every layout change.
-- A phone's `swarms` are not tabs — they are where the pager attaches the agents either side of the
-- one on screen — so nothing here is projected onto the desk.
--- The phone reads the tabs, follows them (`desk_changed` rides each machine's relay socket, since a
-- phone holds no adapter socket of its own), and writes exactly twice: an agent created here joins
-- the tab the phone is in, and one deleted here leaves every tab that held it.
--- Which tab is open, and where you were inside it, stay on the device — as they do per window.
--
--What the person sees of it is one mark beside `⋯` in the terminal's header, which brings a panel up
--from the bottom (`lib/phone/desk_tabs_popup.dart`): the tabs as a row of names, and the agents of
--the one picked as a list of rows under it — the Agents tab's own rows. A name changes the list and
--nothing else, so another tab can be read into without leaving the terminal you are in; a row is
--what opens an agent. The swipe then walks
--that tab's agents rather than the whole account (`lib/phone/desk_groups.dart`).
--
--**The terminal keeps the screen**: a rail of tabs standing across the top was tried and taken out —
--it cost a line and a half of somebody's session, all day, for a choice made a few times a day.
--
--The tabs are re-read every 15s while the app is in the foreground (`PhoneDesk.pollInterval`), and
--that is not belt-and-braces here: `desk_changed` reaches a phone only over a machine's relay socket,
--so a backend that does not forward it, or a moment with no machine connected, delivers nothing at
--all.
++The account's tabs are stored on the backend (`/api/desk`). `lib/state/desk_sync.dart` models
++that shared document; `lib/state/phone_desk.dart` handles the phone's reads and explicit writes.
++The phone's `swarms` are temporary terminal containers for the pager, not a projection of the
++account's tabs. Swiping must never rewrite the shared desk.
++
++The phone follows desk updates over machine relay sockets and polls every 15 seconds in the
++foreground. Creating or deleting a harness updates its desk membership; explicit tab operations
++also live in `PhoneDesk`. The current tab and position remain device-local. `lib/phone/desk_groups.dart`
++resolves the tab's agents for navigation.
## It is a VIEWER build, always
@@@ -81,34 -80,26 +73,14 @@@ through it or a browser, and the grid'
## Keeping in step with `../desktop`
--The shared half of `lib/` was **vendored** from `desktop/lib/`, not rewritten, and outside
- `lib/phone/` and `lib/p2p/` the two trees are byte-identical apart from the package name and the
- files below. So a fix that belongs on both sides can be carried across with `diff`:
-`lib/phone/` and `lib/p2p/` the two trees are byte-identical apart from the package name and six
-files. So a fix that belongs on both sides can be carried across with `diff`:
++Much of `lib/` originated in `desktop/lib/`, but the copies now differ substantially. Mobile
++removes desktop routing, local CLI supervision and transport, grid controls and local file access.
++It also owns its authentication, encryption and phone-specific lifecycle handling.
--```bash
--# What has drifted, ignoring the package rename
--cd mobile/lib && for f in $(find . -name '*.dart' | sed 's|^\./||'); do
-- [ -f "../../desktop/lib/$f" ] || continue
-- diff -q <(sed 's|package:harness_mobile/|package:harness/|g' "$f") "../../desktop/lib/$f" >/dev/null \
-- || echo "DIFFERS: $f"
--done
--```
-
-The six that are expected to differ, and why:
-
-| File | Why |
-|---|---|
-| `main.dart` | mounts `PhoneShell` and the p2p transport, not `SwarmScreen` |
-| `app_shell.dart` | no managed window: `window_manager` ships for macOS/Windows/Linux only |
-| `widgets/update_notice.dart` | same — it was wrapped in a window drag area |
-| `screens/login_screen.dart`, `widgets/bootstrapping_screen.dart`, `widgets/engine_identity.dart` | assets are this package's own, so they no longer name a `package:` to load from |
++Port shared protocol and model fixes deliberately. Check `core/agent_git_context.dart`,
++`e2ee/envelope.dart`, `state/app_state.dart` and their regression tests when upstream adds RPCs
++or agent fields. `test/encrypted_down_types_test.dart` compares the phone's encryption rules with
++the CLI's source so a new machine request cannot silently leave unencrypted.
- The files expected to differ, and why:
-
- | File | Why |
- |---|---|
- | `main.dart` | mounts `PhoneShell` and the p2p transport, not `SwarmScreen` |
- | `app_shell.dart` | no managed window: `window_manager` ships for macOS/Windows/Linux only; and no application menu, update band, provisioning screens or desktop sign-in |
- | `widgets/engine_identity.dart` | assets are this package's own, so it no longer names a `package:` to load from |
-
- `lib/core/desktop_window.dart` and `lib/widgets/window_chrome.dart` have no copy here at all, and
- neither have the desktop screens a phone can never reach: the sign-in and boot screens (the phone
- has `PhoneWelcome` and `PhoneBoot`), first-run provisioning, the update notice, the firmware
- flasher, the layout palette and the shortcuts sheet.
-
- Nor has the code only those screens and a local CLI reached: the provisioner, the updater, local CLI
- discovery and its runner, the CLI and browser sign-in, pane presets and arrangements. So
- `state/app_state.dart`, `state/swarm.dart`, `state/terminal_pane.dart`, `state/pane_layout_store.dart`
- and `auth/` differ from the desktop's by that cut as well — a fix carried across from there lands in
- what is left.
-`lib/core/desktop_window.dart` and `lib/widgets/window_chrome.dart` have no copy here at all.
++`third_party/xterm/` is patched code: preserve its mobile input, rendering and accessibility changes.
++Never commit local signing edits to `ios/Runner.xcodeproj/project.pbxproj`.
diff --cc mobile/lib/e2ee/envelope.dart
index 75b85aa4a,75b85aa4a..6e3de6905
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@@ -44,6 -44,6 +44,8 @@@ const Set<String> encryptedDownTypes =
// outright beside it — this one among them. Sent in the clear it came back
// `E2EE_REQUIRED`, which on this screen read as a folder with no branches.
'git_project_info',
++ // The harness's branch and pull-request history is a machine RPC too.
++ 'git_pull_request',
'codex_profiles_list',
'codex_profile_link',
// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missing
@@@ -100,8 -100,8 +102,13 @@@ bool sealsDown(String type, {required b
encryptedDownTypes.contains(type) ||
(strictDown && strictDownTypes.contains(type));
--Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>
-- utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');
++Uint8List _aad(
++ int v,
++ String type,
++ String dbSessionId,
++ String k,
++ String epoch,
++) => utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');
/// Seals [payload] under [key]: [k] is 'p' (pairwise session) or 'g' (the machine's group key,
/// which also carries an [epoch]).
@@@ -137,7 -137,7 +144,11 @@@ Map<String, dynamic>? unwrapPayload
) {
final v = env['v'], k = env['k'], n = env['n'], ct = env['ct'];
final epoch = env['epoch'] ?? '';
-- if (v is! int || k is! String || n is! int || ct is! String || epoch is! String) {
++ if (v is! int ||
++ k is! String ||
++ n is! int ||
++ ct is! String ||
++ epoch is! String) {
return null;
}
final Uint8List sealed;
@@@ -146,11 -146,11 +157,17 @@@
} on FormatException {
return null;
}
-- final clear = aeadOpen(key, n, _aad(v, frameType, dbSessionId ?? '', k, epoch), sealed);
++ final clear = aeadOpen(
++ key,
++ n,
++ _aad(v, frameType, dbSessionId ?? '', k, epoch),
++ sealed,
++ );
return clear == null ? null : jsonObjectOf(clear);
}
--bool isWrapped(Object? payload) => payload is Map && payload.containsKey('__e2e');
++bool isWrapped(Object? payload) =>
++ payload is Map && payload.containsKey('__e2e');
/// UTF-8 JSON that must be an object; null for anything else.
Map<String, dynamic>? jsonObjectOf(List<int> utf8Json) {
diff --cc mobile/lib/phone/terminal_page.dart
index e6d32e9df,e6b373bd8..faa6037a3
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@@ -42,8 -41,10 +43,9 @@@ import 'held_height.dart'
import 'phone_sheet.dart';
import 'phone_status.dart';
import 'settings_page.dart';
+ import 'session_work_page.dart';
import 'terminal_action_column.dart';
import 'terminal_chrome_scroll.dart';
-import 'terminal_header.dart';
import 'terminal_input_dock.dart';
import 'terminal_search.dart';
import 'tty.dart';
@@@ -2290,9 -2355,32 +2294,10 @@@ class _TerminalPageState extends State<
// Where it runs, written as everywhere else: `hn` over `M2:autonomous-harness ⑂ main`.
title: [
'$agentName · $machineName',
- if (agent.project?.label case final folder?) ':$folder',
+ if (agent.displayProject?.label case final folder?) ':$folder',
].join(),
- titleBranch: agent.project?.shownBranch,
+ titleBranch:
+ agent.gitContext?.branchLabel ?? agent.displayProject?.shownBranch,
- // The agent, then where it runs — the machine, then the folder with its parent beside the
- // branch — each behind its icon. The header has no room for the path.
- titleParts: [agentName],
- // The engine mark carrying the header's own dot: the sheet's anchor, and the same picture of
- // this agent the header draws above it. The ring is the sheet's ground, which the dot is
- // notched out of.
- titleLeading: ValueListenableBuilder<PhoneSummary>(
- valueListenable: _actionsStatus,
- builder: (context, status, _) {
- AppTheme.watch(context);
- return BadgedEngineMark(
- agent: agent,
- status: status,
- ring: AppPalette.panelBg,
- size: 40,
- );
- },
- ),
- titleDetail: AgentPlaceLines(
- machineName: machineName,
- project: agent.displayProject,
- ),
// Three cards: what acts on THIS agent, the screens the app itself has, and — alone at the
// end — the one act that cannot be undone. No caption over the first: the name above it
// already says which harness its rows act on, which is also why they no longer repeat
diff --cc mobile/lib/state/app_state.dart
index 36e4bb9e4,de00f2e2a..9321ffb17
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@@ -14,7 -16,11 +14,8 @@@ import '../auth/auth_session.dart'
import '../auth/peer_link_client.dart';
import '../auth/sign_in_client.dart';
import '../auth/cli_link.dart';
-import '../auth/cli_login.dart';
-import '../bootstrap/environment_provisioner.dart';
-import '../core/viewer_mode.dart';
import '../core/config.dart';
+ import '../core/agent_git_context.dart';
import '../core/agent_preference.dart';
import '../core/engine_availability.dart';
import '../core/device_name.dart';
diff --cc mobile/test/e2ee/relay_session_crypto_test.dart
index 5273081e9,000000000..81dd2b5e1
mode 100644,000000..100644
--- a/mobile/test/e2ee/relay_session_crypto_test.dart
+++ b/mobile/test/e2ee/relay_session_crypto_test.dart
@@@ -1,553 -1,0 +1,575 @@@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/envelope.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/e2ee/primitives.dart';
+import 'package:harness_mobile/e2ee/relay_session_crypto.dart';
+import 'package:harness_mobile/e2ee/replay_window.dart';
+import 'package:harness_mobile/e2ee/terminal_cipher.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/viewer/e2ee_relay_codec.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+import 'machine_session.dart';
+
+/// The phone's end of a session against the machine's ([MachineSession]): what it lets through,
+/// and — the point of it — what it refuses from a relay that replays, reorders or forges.
+void main() {
+ late E2eeIdentity phone;
+ late E2eeIdentity machineIdentity;
+
+ setUpAll(() async {
+ phone = await E2eeIdentity.generate();
+ machineIdentity = await E2eeIdentity.generate();
+ });
+
+ Future<RelaySessionCrypto> client() => RelaySessionCrypto.start(
+ machineId: machineId,
+ identity: phone,
+ peerPub: machineIdentity.pub,
+ );
+
+ /// A session both ends have agreed.
+ Future<(RelaySessionCrypto, MachineSession)> agreed({
+ Map<String, Object?> features = const {'terminalP2p': 1, 'strictDown': 1},
+ }) async {
+ final session = await client();
+ final machine = await MachineSession.answer(
+ session.helloFrame(),
+ identity: machineIdentity,
+ );
+ expect(
+ await session.handleWelcome(await machine.welcome(features: features)),
+ isTrue,
+ );
+ return (session, machine);
+ }
+
+ group('the hello', () {
+ test('names this phone and is signed by it', () async {
+ final session = await client();
+ final hello = session.helloFrame();
+ expect(hello['type'], 'e2e_hello');
+ final payload = hello['payload'] as Map<String, dynamic>;
+ expect(b64d(payload['identityPub'] as String), phone.pub);
+ expect(
+ await verifySignature(
+ phone.pub,
+ lvCat(['e2e-hello-v1', machineId, b64d(payload['ephPub'] as String)]),
+ b64d(payload['sig'] as String),
+ ),
+ isTrue,
+ );
+ expect(session.ready, isFalse);
+ expect(session.terminalP2pVersion, 0);
+ });
+ });
+
+ group('the welcome', () {
+ test('from the pinned machine makes the session usable', () async {
+ final (session, _) = await agreed();
+ expect(session.ready, isTrue);
+ expect(session.terminalP2pVersion, 1);
+ expect(session.strictDown, isTrue);
+ });
+
+ test('features it does not understand read as none', () async {
+ final (session, _) = await agreed(
+ features: {'terminalP2p': '1', 'strictDown': true},
+ );
+ expect(session.terminalP2pVersion, 0);
+ expect(session.strictDown, isFalse);
+ });
+
+ test('signed by any other machine is refused', () async {
+ final session = await client();
+ final impostor = await MachineSession.answer(session.helloFrame());
+ expect(await session.handleWelcome(await impostor.welcome()), isFalse);
+ expect(session.ready, isFalse);
+ });
+
+ test('with a field missing, mangled or not opening is refused', () async {
+ final session = await client();
+ final machine = await MachineSession.answer(
+ session.helloFrame(),
+ identity: machineIdentity,
+ );
+ final good = await machine.welcome();
+ for (final bad in <Map<String, dynamic>>[
+ {...good}..remove('ephPub'),
+ {...good, 'sig': ''},
+ {...good, 'enc': 7},
+ {...good, 'ephPub': '!!not base64!!'},
+ {...good, 'enc': b64e(List.filled(40, 1))},
+ {...good, 'ephPub': b64e(List.filled(31, 1))},
+ ]) {
+ expect(await session.handleWelcome(bad), isFalse, reason: '$bad');
+ }
+ for (final initial in <Map<String, Object?>>[
+ {'epoch': 'e1'},
+ {'groupKey': b64e(List.filled(32, 1))},
+ {'groupKey': '', 'epoch': 'e1'},
+ {'groupKey': b64e(List.filled(32, 1)), 'epoch': ''},
+ ]) {
+ expect(
+ await session.handleWelcome(await machine.welcome(initial: initial)),
+ isFalse,
+ reason: '$initial',
+ );
+ }
+ expect(session.ready, isFalse);
+ });
+
- test('a signed welcome over a malformed key is refused, not thrown', () async {
- final session = await client();
- final hello = session.helloFrame()['payload'] as Map<String, dynamic>;
- final webEphPub = b64d(hello['ephPub'] as String);
- final shortKey = List.filled(31, 9);
- final sig = await machineIdentity.sign(
- lvCat(['e2e-welcome-v1', machineId, webEphPub, shortKey]),
- );
- expect(
- await session.handleWelcome({
- 'ephPub': b64e(shortKey),
- 'sig': b64e(sig),
- 'enc': b64e(List.filled(40, 1)),
- }),
- isFalse,
- );
- expect(session.ready, isFalse);
- });
++ test(
++ 'a signed welcome over a malformed key is refused, not thrown',
++ () async {
++ final session = await client();
++ final hello = session.helloFrame()['payload'] as Map<String, dynamic>;
++ final webEphPub = b64d(hello['ephPub'] as String);
++ final shortKey = List.filled(31, 9);
++ final sig = await machineIdentity.sign(
++ lvCat(['e2e-welcome-v1', machineId, webEphPub, shortKey]),
++ );
++ expect(
++ await session.handleWelcome({
++ 'ephPub': b64e(shortKey),
++ 'sig': b64e(sig),
++ 'enc': b64e(List.filled(40, 1)),
++ }),
++ isFalse,
++ );
++ expect(session.ready, isFalse);
++ },
++ );
+
+ // ⚠️ A welcome is signed, but nothing in it is fresh: the relay can hand the same one back at
+ // any time. Taken twice, it reset the group key to the one it carried, undoing the rekey the
+ // machine sent when it revoked a client — and that client still holds the old key.
+ test('a second one, even a genuine replay, changes nothing', () async {
+ final (session, machine) = await agreed();
+ final welcome = await machine.welcome();
+ final oldKey = Uint8List.fromList(machine.groupKey);
+ expect(
+ session.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 9)), 'e2'),
+ ),
+ isTrue,
+ );
+
+ expect(await session.handleWelcome(welcome), isFalse);
+
+ // Still on the rotated key: the machine's next broadcast opens…
+ expect(
+ session.unwrapIncoming(machine.group('text_delta', {'text': 'fresh'})),
+ isNotNull,
+ );
+ // …and one sealed under the revoked key, by whoever still holds it, does not.
+ final forged = {
+ 'type': 'text_delta',
+ 'payload': wrapPayload(oldKey, 'g', 99, 'text_delta', null, {
+ 'text': 'forged',
+ }, epoch: 'e1'),
+ };
+ expect(session.unwrapIncoming(forged), isNull);
+ });
+ });
+
+ group('rekey', () {
+ test('rotates the group key the broadcasts open under', () async {
+ final (session, machine) = await agreed();
+ expect(
+ session.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 3)), 'e2'),
+ ),
+ isTrue,
+ );
+ final clear = session.unwrapIncoming(machine.group('done', {'ok': true}));
+ expect(clear!['payload'], {'ok': true});
+ });
+
+ test('before the session is up, or malformed, is refused', () async {
+ final session = await client();
+ expect(session.handleRekey({'n': 1, 'enc': 'x'}), isFalse);
+ final (live, machine) = await agreed();
+ final good = machine.rekey(Uint8List.fromList(List.filled(32, 3)), 'e2');
+ for (final bad in <Map<String, dynamic>>[
+ {'n': '1', 'enc': good['enc']},
+ {'n': good['n'], 'enc': ''},
+ {'n': good['n'], 'enc': '%%%'},
+ {'n': good['n'] + 1, 'enc': good['enc']},
+ {'n': -1, 'enc': good['enc']},
+ ]) {
+ expect(live.handleRekey(bad), isFalse, reason: '$bad');
+ }
+ expect(live.handleRekey(good), isTrue);
+ });
+
+ test('a rekey that opens but says nothing usable is refused', () async {
+ final (session, machine) = await agreed();
+ final n = machine.s2cCounter++;
+ final enc = aeadSeal(
+ machine.keys.s2c,
+ n,
+ utf8Bytes('e2e-rekey'),
+ utf8Bytes(jsonEncode({'groupKey': '', 'epoch': 'e2'})),
+ );
+ expect(session.handleRekey({'n': n, 'enc': b64e(enc)}), isFalse);
+ });
+
+ // ⚠️ The machine seals a rekey on its pairwise counter, so it is replay-checked like any frame
+ // there. Unchecked, an OLD rekey handed back after a newer one rolled the group key back to
+ // one a client revoked in between still holds.
+ test('an old one handed back after a newer one is refused', () async {
+ final (session, machine) = await agreed();
+ final first = machine.rekey(Uint8List.fromList(List.filled(32, 4)), 'e2');
+ final revokedKnows = Uint8List.fromList(machine.groupKey);
+ final second = machine.rekey(
+ Uint8List.fromList(List.filled(32, 5)),
+ 'e3',
+ );
+ expect(session.handleRekey(first), isTrue);
+ expect(session.handleRekey(second), isTrue);
+
+ expect(session.handleRekey(first), isFalse);
+ expect(session.handleRekey(second), isFalse);
+
+ final forged = {
+ 'type': 'text_delta',
+ 'payload': wrapPayload(revokedKnows, 'g', 50, 'text_delta', null, {
+ 'text': 'forged',
+ }, epoch: 'e2'),
+ };
+ expect(session.unwrapIncoming(forged), isNull);
+ expect(
+ session.unwrapIncoming(machine.group('text_delta', {'text': 'real'})),
+ isNotNull,
+ );
+ });
+ });
+
+ group('frames up from the machine', () {
+ test('one never sealed passes as it is', () async {
+ final (session, _) = await agreed();
+ final frame = {
+ 'type': 'node_status',
+ 'payload': {'online': true},
+ };
+ expect(session.unwrapIncoming(frame), same(frame));
+ expect(session.unwrapIncoming({'type': 'x'}), isNotNull);
+ });
+
+ test('a sealed one opens once, in any order, within the window', () async {
+ final (session, machine) = await agreed();
+ final a = machine.target('agents_list_result', {'agents': []});
+ final b = machine.target('agents_list_result', {
+ 'agents': [1],
+ });
+ expect(session.unwrapIncoming(b)!['payload'], {
+ 'agents': [1],
+ });
+ expect(session.unwrapIncoming(a)!['payload'], {'agents': []});
+ // Replayed: both refused.
+ expect(session.unwrapIncoming(a), isNull);
+ expect(session.unwrapIncoming(b), isNull);
+ });
+
+ test('one from before the window is refused', () async {
+ final (session, machine) = await agreed();
+ final stale = machine.target('x', {'n': 1});
+ machine.s2cCounter += e2eeReplayWindowSize + 10;
+ expect(session.unwrapIncoming(machine.target('x', {'n': 2})), isNotNull);
+ expect(session.unwrapIncoming(stale), isNull);
+ });
+
+ test('a sealed one relabelled as another type is refused', () async {
+ final (session, machine) = await agreed();
+ final frame = machine.target('session_get_result', {'text': 'secret'});
+ expect(
+ session.unwrapIncoming({...frame, 'type': 'agents_list_result'}),
+ isNull,
+ );
+ // The genuine one still opens: a refusal spends nothing.
+ expect(session.unwrapIncoming(frame), isNotNull);
+ });
+
+ test('an envelope of the wrong shape is refused, not thrown', () async {
+ final (session, machine) = await agreed();
+ final good = machine.target('x', {'a': 1});
+ final env = (good['payload'] as Map)['__e2e'] as Map<String, dynamic>;
+ for (final bad in <Map<String, dynamic>>[
+ {
+ 'type': 'x',
+ 'payload': {'__e2e': 'not a map'},
+ },
+ {'type': 7, 'payload': good['payload']},
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'n': '1'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'ct': '%%%'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {...env, 'v': '1'},
+ },
+ },
+ {
+ 'type': 'x',
+ 'payload': {
+ '__e2e': {
+ ...env,
+ 'ct': b64e([1, 2]),
+ },
+ },
+ },
+ ]) {
+ expect(session.unwrapIncoming(bad), isNull, reason: '$bad');
+ }
+ });
+
+ test('a sealed one before the welcome is refused', () async {
+ final session = await client();
+ final machine = await MachineSession.answer(session.helloFrame());
+ expect(session.unwrapIncoming(machine.target('x', {})), isNull);
+ expect(session.unwrapIncoming(machine.group('x', {})), isNull);
+ });
+
+ test('a broadcast opens once, for its epoch and its session', () async {
+ final (session, machine) = await agreed();
+ final first = machine.group('user_message', {
+ 'text': 'hi',
+ }, dbSessionId: 's1');
+ final second = machine.group('user_message', {
+ 'text': 'there',
+ }, dbSessionId: 's1');
+ expect(session.unwrapIncoming(first)!['payload'], {'text': 'hi'});
+ expect(session.unwrapIncoming(second)!['payload'], {'text': 'there'});
+ // Replayed, or reordered behind a later one: broadcasts only ever move forward.
+ expect(session.unwrapIncoming(first), isNull);
+ // Moved to another conversation: its AAD says otherwise.
+ final third = machine.group('user_message', {
+ 'text': 'x',
+ }, dbSessionId: 's1');
+ expect(session.unwrapIncoming({...third, 'dbSessionId': 's2'}), isNull);
+ // From an epoch this session is not on.
+ machine.epoch = 'e9';
+ expect(session.unwrapIncoming(machine.group('x', {})), isNull);
+ });
+ });
+
+ group('frames down to the machine', () {
+ test(
+ 'a sealed type goes sealed, on a counter the machine can open',
+ () async {
+ final (session, machine) = await agreed();
+ final one = session.wrapOutgoing({
+ 'type': 'terminal_input',
+ 'payload': {'data': 'ls'},
+ });
+ final two = session.wrapOutgoing({
+ 'type': 'terminal_input',
+ 'payload': {'data': 'pwd'},
+ });
+ expect(machine.openDown(one), {'data': 'ls'});
+ expect(machine.openDown(two), {'data': 'pwd'});
+ expect(
+ ((one['payload'] as Map)['__e2e'] as Map)['n'],
+ lessThan(((two['payload'] as Map)['__e2e'] as Map)['n'] as int),
+ );
+ },
+ );
+
+ test('a type the relay may read goes as it is', () async {
+ final (session, _) = await agreed();
+ final frame = {
+ 'type': 'machine_select',
+ 'payload': {'machineId': 'm'},
+ };
+ expect(session.wrapOutgoing(frame), same(frame));
+ expect(session.wrapOutgoing({'type': 1}), isNotNull);
+ });
+
+ test('before the session is up nothing is sealed', () async {
+ final session = await client();
+ final frame = {'type': 'terminal_input', 'payload': {}};
+ expect(session.wrapOutgoing(frame), same(frame));
+ });
+ });
+
+ group('terminal bytes', () {
+ TerminalBinaryFrame input(String text) => TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 1,
+ bytes: utf8Bytes(text),
+ compressed: false,
+ );
+
+ test('are sealed only once the session is up', () async {
+ final session = await client();
+ expect(session.encryptTerminal(input('x')), isNull);
+ expect(session.decryptTerminal(Uint8List(40)), isNull);
+ });
+
+ test('go down on their own key and counter', () async {
+ final (session, machine) = await agreed();
+ final first = session.encryptTerminal(input('a'))!;
+ final second = session.encryptTerminal(input('b'))!;
+ final opened1 = openTerminalBinary(machine.terminalC2s, first)!;
+ final opened2 = openTerminalBinary(machine.terminalC2s, second)!;
+ expect(utf8.decode(opened1.frame.bytes), 'a');
+ expect(opened2.counter, opened1.counter + 1);
+ // Not under the JSON frames' key: the two never share a nonce.
+ expect(openTerminalBinary(machine.keys.c2s, first), isNull);
+ });
+
+ test('a frame too big to seal takes no counter', () async {
+ final (session, machine) = await agreed();
+ final huge = TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 1,
+ bytes: Uint8List(terminalLocalMaxPayloadBytes + 1),
+ compressed: false,
+ );
+ expect(session.encryptTerminal(huge), isNull);
+ final next = session.encryptTerminal(input('after'))!;
+ expect(openTerminalBinary(machine.terminalC2s, next)!.counter, 0);
+ });
+
+ test('come up once each, in any order', () async {
+ final (session, machine) = await agreed();
+ final a = machine.terminal('first');
+ final b = machine.terminal('second');
+ expect(utf8.decode(session.decryptTerminal(b)!.bytes), 'second');
+ expect(utf8.decode(session.decryptTerminal(a)!.bytes), 'first');
+ expect(session.decryptTerminal(a), isNull);
+ expect(session.decryptTerminal(b), isNull);
+ });
+
+ test('a flipped byte anywhere is refused', () async {
+ final (session, machine) = await agreed();
+ final sealed = machine.terminal('secret');
+ for (final at in [0, 4, 5, 7, 12, 17, 20, sealed.length - 1]) {
+ final bad = Uint8List.fromList(sealed)..[at] ^= 0x01;
+ expect(session.decryptTerminal(bad), isNull, reason: 'byte $at');
+ }
+ expect(session.decryptTerminal(sealed), isNotNull);
+ });
+ });
+
+ group('as the relay codec', () {
++ test('branch and pull-request history waits for encryption', () async {
++ final session = await client();
++ final codec = E2eeRelayCodec(session);
++ final request = {
++ 'type': 'git_pull_request',
++ 'payload': {'agentId': 'hn', 'history': true, 'offset': 4},
++ };
++ expect(codec.encodeFrame(request), isNull);
++
++ final machine = await MachineSession.answer(
++ codec.helloFrame(),
++ identity: machineIdentity,
++ );
++ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
++ final sealed = codec.encodeFrame(request)!;
++ expect(isWrapped(sealed['payload']), isTrue);
++ expect(machine.openDown(sealed), request['payload']);
++ });
++
+ test('holds a sealed or strict frame until the session is up', () async {
+ final session = await client();
+ final codec = E2eeRelayCodec(session);
+ expect(codec.helloFrame()['type'], 'e2e_hello');
+ expect(
+ codec.encodeFrame({'type': 'terminal_input', 'payload': {}}),
+ isNull,
+ );
+ expect(codec.encodeFrame({'type': 'dsh_install', 'payload': {}}), isNull);
+ expect(
+ codec.encodeFrame({'type': 'machine_select', 'payload': {}}),
+ isNotNull,
+ );
+ final machine = await MachineSession.answer(
+ codec.helloFrame(),
+ identity: machineIdentity,
+ );
+ // A codec's hello is fixed for its session — the same ephemeral each time it is asked.
+ expect(
+ (codec.helloFrame()['payload'] as Map)['ephPub'],
+ (session.helloFrame()['payload'] as Map)['ephPub'],
+ );
+ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
+ expect(codec.terminalP2pVersion, 1);
+ final sealed = codec.encodeFrame({
+ 'type': 'dsh_install',
+ 'payload': {'url': 'u'},
+ })!;
+ expect(machine.openDown(sealed), {'url': 'u'});
+ expect(
+ codec.handleRekey(
+ machine.rekey(Uint8List.fromList(List.filled(32, 2)), 'e2'),
+ ),
+ isTrue,
+ );
+ expect(codec.decodeFrame(machine.target('x', {'a': 1}))!['payload'], {
+ 'a': 1,
+ });
+ });
+
+ test('turns loopback terminal frames into relay ones and back', () async {
+ final (session, machine) = await agreed();
+ final codec = E2eeRelayCodec(session);
+ final local = encodeTerminalLocal(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.input,
+ streamId: streamId,
+ seq: 3,
+ bytes: utf8Bytes('echo hi'),
+ compressed: false,
+ ),
+ )!;
+ final wire = codec.encodeBinary(local)!;
+ expect(
+ utf8.decode(openTerminalBinary(machine.terminalC2s, wire)!.frame.bytes),
+ 'echo hi',
+ );
+ expect(codec.encodeBinary(Uint8List.fromList([1, 2, 3])), isNull);
+
+ final back = codec.decodeBinary(machine.terminal('hi'))!;
+ expect(utf8.decode(decodeTerminalLocal(back)!.bytes), 'hi');
+ expect(codec.decodeBinary(Uint8List(8)), isNull);
+ });
+
+ test('a machine this phone never linked gets no codec at all', () async {
+ final keys = ViewerKeyStore(storage: MemoryKeyValueStore());
+ final codecs = viewerRelayCodecs(keys);
+ expect(await codecs('never-linked'), isNull);
+ await keys.pin(machineId, machineIdentity.pub);
+ final codec = await codecs(machineId);
+ expect(codec, isA<E2eeRelayCodec>());
+ // Pinned to exactly that machine: its welcome opens the session, another's does not.
+ final machine = await MachineSession.answer(
+ codec!.helloFrame(),
+ identity: machineIdentity,
+ );
+ expect(await codec.handleWelcome(await machine.welcome()), isTrue);
+ final other = await codecs(machineId);
+ final impostor = await MachineSession.answer(other!.helloFrame());
+ expect(await other.handleWelcome(await impostor.welcome()), isFalse);
+ });
+ });
+}