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.

Mobile: first session ready to send, Harness OS version and settings (#1644)

tony496sd763e16d614b
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 90a4ed077..c4d6254a5 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -20,7 +20,7 @@ automatically proven improvement. Changes still need review, tests and a deliber
| Which features get tried and used again? | First measured installations and daily first/repeat feature reach | Locally deduplicated installation-days, not unique accounts. Reads the apps make on their own (history, history paging, Store list, model list; `PRODUCT_USAGE_AUTOMATIC_ACTIONS`) count reliability only. The Store and model lists get reach only from the request an app marks `userAction` when a person opens them (`<action>_user_*`, `PRODUCT_USAGE_USER_OPENED_ACTIONS`); history has none. |
| Where do app flows break? | Setup, Harness/tmux/clipboard steps, sign-in, workspace/remote connections, computer linking, viewer-pane opening and manual update checking/staging; a setup step whose tool was missing at a check (`setup_desktop_setup_<step>_missing`); the agents a new computer downloads beside setup (`setup_desktop_agent_download_<opencode\|codex\|claude>_started`, `_ok`, `_failed`, with under 1 min, 1–5 min and over 5 min) | Fixed started/ok/failed/cancelled/unknown counts and coarse duration buckets. Opening a viewer pane is not rendering its content; staging an update is not a successful relaunch. A setup step stays open from the first check until its tool is in place, so a tool that was missing and then installed is one ok step and one `_missing` mark; only a setup that ends failed fails its step. Earlier Desktop releases counted every check that found a tool missing as a failed step (on 2026-10-16 the Harness step read 72 failed of 221 while 0 setups failed): compare releases separately. `_missing` is any tool a check found absent or out of date (a Harness CLI older than this Desktop needs, on a computer already in use, counts too), not only new computers. A step left waiting (the review, a Linux Terminal handoff, manual mode, someone who walks away) now ends `unknown` at the 15-minute observation bound instead of `failed`, so expect `setup_*_unknown` to rise, mostly on Linux. `_missing` and the download counts are anonymous setup counts only. A download whose prerequisite (curl, Harness's Node) never arrived counts as started and failed; `ok` means the agent's program is in place, judged per engine. |
| Where does the phone's onboarding stall? | After sign-in: waiting for the first computer, opening its session, the first message, the notification prompt. A sign-in that went through, by button, counted again under the account's sharing. Waits past a minute split into 1–5 min, 5–15 min, 15 min–1 h and over 1 h for the computer and the first message. Once per step per sign-in: `resumed` (reopened in a run that did not sign in), "Not you? Sign out", the address sent from the share sheet, a joining computer that wants its password or is offline, `joined_after_leaving` (the computer turned up after the app left the wait), `new_account` (a sign-in that created the account). Once per install: `first_open` (signed out `setup_phone_first_open`, signed in `ui_phone_first_open`) | Stage totals per day, not a linked funnel. A wait's `ok` is a computer that turned up while its screen was open: add `joined_after_leaving` for the computers that came while the app was away (16–19 October 2026: 5 `ok` in 49 fresh waits, while 91% of the phone's people had a computer on the same account). `new_account` is an account minutes old at sign-in, its first Harness sign-in anywhere. `first_open` is set once per install by a local flag that is never sent: the step between a store's download and a sign-in. Subtract `resumed` from starts for fresh starts; an unmatched start is a closed app or a step still waiting. A resumed step's duration starts at the reopening. Signed-in sign-in counts are successes only; failures and cancels before an account remain the signed-out counts', but a success is marked `retried` (a failed or cancelled try came first in that app run) or `switched` (another button was tried first). Phone reports carry release and iOS/Android, so every phone count also splits by those two margins (above 20 collector days); debug builds are not kept. A chosen sign-out sends what is queued first (up to 2 s), so "Not you? Sign out" reaches the totals. The first message is the first line sent after the hand-over in any session, or a task typed into New Harness; before 2026-10-20 only the session the hand-over opened counted and leaving it cancelled the step (compare releases separately). Each step of a sign-in that created its account is marked `new_account` when counted and `new_account_ok` when it ends ok, so new people's funnel reads apart. The phone sends what it queued as it leaves the screen, since iOS can end a suspended app with its counts still in RAM. |
-| How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers is `unknown`, one whose computers never answer stays started. What a launch waited on is counted beside it, once each, until a computer answers or the app leaves the screen (`ui_phone_app_start_<why>`): `no_computer` and `list_failed` (the account's list had none, or could not be read), `offline` (it said every computer was offline), `locked` (a computer wanted the phone's password), `connect_failed` (a dial to a computer said to be online failed) and `waited_1m` (a minute on screen); a launch can name several. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. The phone's `remote_connect` is one computer's socket dialling, from connecting or reconnecting until it connects (`ok`) or drops (`failed`). `cancelled` is a dial still going when the app went to the background (the pause, not the app switcher or a system sheet): a suspended app never hears the socket's answer, so the dial ends there rather than staying without an outcome, and a dial after the app is back is a new count. From build 72, the release after 1.0.8 (71), a dial still in progress when the app goes to the background ends `cancelled`; earlier builds, 1.0.8 (71) included, left it without an outcome (79 of the 252 on 2026-10-20): compare releases separately. `connect_user` and `connect_auto` are not ended this way. |
+| How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers (the app hidden, at the latest sent to the background) is `unknown`, one whose computers never answer stays started. What a launch waited on is counted beside it, once each, until a computer answers or the app leaves the screen (`ui_phone_app_start_<why>`): `no_computer` and `list_failed` (the account's list had none, or could not be read), `offline` (it said every computer was offline), `locked` (a computer wanted the phone's password), `connect_failed` (a dial to a computer said to be online failed) and `waited_1m` (a minute on screen); a launch can name several. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. The phone's `remote_connect` is one computer's socket dialling, from connecting or reconnecting until it connects (`ok`) or drops (`failed`). `cancelled` is a dial still going when the app went to the background (the pause, not the app switcher or a system sheet): a suspended app never hears the socket's answer, so the dial ends there rather than staying without an outcome, and a dial after the app is back is a new count. The two dials beside it end the same way: a `connect_auto` or `connect_user` dial still going at the pause is `cancelled`, an asked-for dial's 12 s deadline goes with it, and the socket's answer after the pause counts nothing more. From build 72, the release after 1.0.8 (71), a `remote_connect`, `connect_auto` or `connect_user` dial still in progress when the app goes to the background ends `cancelled`; earlier builds, 1.0.8 (71) included, left it without an outcome (79 of the 252 `remote_connect` dials on 2026-10-20): compare releases separately. |
| Are the phone's side pages used? | Find and Computers opens, by a sideways swipe on the terminal or by a button (Computers' row in Settings, its link on a long wait at home) | Which page and which way, nothing more. Find's key and screen-reader actions are not counted; a swipe that lets Find go back opened nothing. |
| Does Desktop's Add Phone card get used, and where else is Add Phone opened? | The card's flow (`ui_desktop_phone_offer_*`): started once it is on screen, `ok` by its Add Phone, `cancelled` by its ×, `unknown` when it went another way (Add Phone opened from elsewhere, a sign-out); every Add Phone opening by its way in (`ui_desktop_add_phone_<offer\|titlebar\|menu\|account\|machines\|command>`) | The card is offered once per computer, so its starts are computers, not people, and it has no 15-minute bound: started minus outcomes is an app closed with the card still up. An opening is the dialog shown, not a phone paired. `menu` includes a key bound to Harness ▸ Add Phone… on macOS; `command` is `> add phone` or a key bound to it elsewhere. A computer that opened signed in was marked offered without ever showing the card; from 2026-10-20 it shows the card once after one of its own harnesses finishes a turn, if the account has no phone or browser, counted apart as `ui_desktop_phone_offer_after_work_*` (vocabulary 4). The same card also shows to a person back after 5 minutes or more away to one of their harnesses that waited on them or finished meanwhile, counted as `ui_desktop_phone_offer_away_waited_*` / `ui_desktop_phone_offer_away_finished_*` (vocabulary 4): at most 3 cards a computer, every kind together, and none once a card's × or Add Phone was used there ([design](design/2026-10-20-desktop-phone-conversion.md)). The browser counts none. Vocabulary 3: counted from the start, but sent only once the local CLI has answered that it forwards them, so a Desktop on an older CLI sends none. |
| Is measurement losing coverage? | Updated collector installation-days, pruned queues, full observation maps, unmatched app starts | Loss signals warrant caution. No signal does not prove complete collection. |
diff --git a/docs/research/2026-10-14-mobile-onboarding/index.html b/docs/research/2026-10-14-mobile-onboarding/index.html
index 86f828747..0a1777f6a 100644
--- a/docs/research/2026-10-14-mobile-onboarding/index.html
+++ b/docs/research/2026-10-14-mobile-onboarding/index.html
@@ -85,7 +85,7 @@
.ph .st.err { color: var(--pred); }
.ph .st .ic { color: var(--pyellow); font-size: 3.6cqw; vertical-align: -.6cqw; margin-right: 1.5cqw; }
@keyframes blink { 50% { opacity: 0; } }
- @media (prefers-reduced-motion: reduce) { .ph .st .cur, .ph .caret { animation: none; } }
+ @media (prefers-reduced-motion: reduce) { .ph .st .cur, .ph .caret, .ph .out .cur.blink { animation: none; } }
.ph .foot { position: absolute; left: 9cqw; right: 9cqw; bottom: 10.8cqw; }
.ph .foot > * + .btn { margin-top: 2.56cqw; }
.ph .quiet { height: 11.3cqw; display: grid; place-items: center; font: 500 3.33cqw var(--mono); color: var(--pfaint); }
@@ -213,6 +213,21 @@
.ph .out .box { display: block; border-left: .6cqw solid #6d8cff; background: #222220; padding: 2.4cqw 3cqw; margin: 3cqw 0 1.4cqw; white-space: pre-wrap; }
.ph .out .logo { font-size: 2.15cqw; line-height: 1.05; color: #d4d4cc; display: block; width: max-content; margin: 4cqw auto 0; }
.ph .out .cur { display: inline-block; width: 1.8cqw; height: 3.6cqw; background: #e5e5e0; vertical-align: -.6cqw; }
+ .ph .out .cur.blink { animation: blink 1s steps(1) infinite; }
+ /* The keyboard the first session opens with: the key bar (terminal_key_bar.dart) over the system's keys. */
+ .ph .kb { position: absolute; left: 0; right: 0; bottom: 0; height: 66cqw; background: #2c2c2e; z-index: 3; padding: 1.6cqw 1.6cqw 0; overflow: hidden; }
+ .ph .kb .bar { display: flex; gap: 1.4cqw; font: 3cqw/1 var(--mono); color: var(--pt); white-space: nowrap; }
+ .ph .kb .bar span { background: #3d3d3f; border-radius: 1.4cqw; padding: 2cqw 2.6cqw; }
+ .ph .kb .rows { margin-top: 3cqw; display: grid; gap: 2.2cqw; }
+ .ph .kb .row { display: flex; gap: 1.3cqw; justify-content: center; }
+ .ph .kb .row i { flex: 0 0 8.2cqw; height: 10cqw; border-radius: 1.4cqw; background: #5c5c5e; }
+ .ph .kb .row i.w { flex-basis: 44cqw; }
+ /* The first session's suggestion over the mic, with its Send (first_task_suggestion.dart). */
+ .ph .sug { position: absolute; left: 4cqw; right: 4cqw; bottom: 30cqw; z-index: 2; background: var(--pg); padding: 1.5cqw 0 1.5cqw; }
+ .ph .sug .l { text-align: center; font: 3.33cqw/1.45 var(--mono); color: var(--pt); margin-bottom: 1.8cqw; }
+ .ph .sug .pill { display: flex; align-items: center; gap: 2cqw; border: .3cqw solid #55554f; border-radius: 6cqw; padding: 1cqw 1cqw 1cqw 3.6cqw; font: 3cqw/1.35 var(--mono); color: var(--pt); }
+ .ph .sug .pill span { flex: 1; }
+ .ph .sug .pill b { background: var(--pgreen); color: #111; border-radius: 5cqw; padding: 2.2cqw 4.4cqw; font-weight: 600; }
.ph .sline { position: absolute; left: 4cqw; right: 4cqw; bottom: 30cqw; text-align: center; font: 3.33cqw/1.45 var(--mono); color: var(--pt); background: var(--pg); padding: 2cqw 0 1.5cqw; z-index: 2; }
.ph .mic { position: absolute; left: 50%; bottom: 12cqw; width: 15.4cqw; height: 15.4cqw; transform: translateX(-50%); border-radius: 50%; background: #262626;
border: .4cqw solid #44443f; display: grid; place-items: center; z-index: 2; box-shadow: 0 1.5cqw 4cqw rgba(0,0,0,.6); font-size: 6.6cqw; color: var(--pt); }
@@ -339,13 +354,14 @@
<a href="#ready">3 · Ready</a> →
<a href="#session">4 · Your session</a>.<br>
Google or Apple; Continue with email and QR code sit under them as one line of words. No Skip, no sample, no tour.
- <a href="#existing-users">Phones already in use</a> that are signed out enter at the welcome; signed-in phones open on their last session.</div>
+ <a href="#existing-users">Phones already in use</a> that are signed out enter at the welcome; signed-in phones open on their last session.<br>
+ <b>Updated 2026-10-23</b> (<a href="https://github.com/autonomous-ai/openharness/pull/1634">#1634</a>): <a href="#session">section 4</a>, the first session's keyboard, typed task, Send and mic.</div>
<p class="note">Every word on these screens comes from one file, <code>mobile/lib/phone/welcome/onboarding_copy.dart</code>, so the same step reads the same on every screen.</p>
<div class="principles">
<div><b>One screen, then your work</b>No tour on the phone. The first screen says what Harness does in one line, and two buttons sign you in right there.</div>
<div><b>The phone finds the computer</b>"On your computer, go to autonomous.ai/go". Signed in there with the same account, the computer joins and the phone moves on by itself.</div>
- <div><b>Straight into the session</b>The phone opens the session the computer opened, with one line by the mic. No list to pick from, no tips.</div>
- <div><b>Nothing else on these screens</b>No page dots, no sample link, no notification prompt. Notifications are asked for after the first thing you send.</div>
+ <div><b>Straight into the session</b>The phone opens the session the computer opened. A fresh one opens with its task in the prompt and the keyboard up; any other with one line by the mic. No list to pick from, no tips.</div>
+ <div><b>Nothing else on these screens</b>No page dots, no sample link, no notification prompt, no microphone prompt. Notifications are asked for after the first thing you send.</div>
</div>
<!-- ===================== 1. WELCOME ===================== -->
@@ -646,8 +662,8 @@
A computer that turns out to want a password, or that the account says is down, ends the wait: what home shows for those is what to do about them (<a href="#arrival">section 5</a>).</p>
<!-- ===================== 4. SESSION ===================== -->
- <h2 id="session">4. Your session: one line by the mic</h2>
- <p class="lede">The phone has no first-session logic of its own: it opens the session the computer opened and says one line over the mic until the first thing is sent. Every other session is in Find, a swipe right away.</p>
+ <h2 id="session">4. Your session: the task ready to send</h2>
+ <p class="lede">The phone opens the session the computer opened. A fresh one — OpenCode with the desktop's starter, or Claude Code or Codex at an empty prompt — opens with its task in the prompt and the keyboard up: Return sends it, or change it first. Any other session gets one line over the mic until the first thing is sent. Every other session is in Find, a swipe right away.</p>
<div class="flow">
<div class="step">
<div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
@@ -655,12 +671,38 @@
<div class="out"><span class="logo"> ▄
█▀▀█ █▀▀█ █▀▀█ █▀▀▄ █▀▀▀ █▀▀█ █▀▀█ █▀▀█
█ █ █ █ █▀▀▀ █ █ █ █ █ █ █ █▀▀▀
-▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀</span><span class="box"><span class="u">make a small web page that shows today's date</span><span class="cur" style="margin-left:.6cqw"></span>
+▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀</span><span class="box"><span class="u">make a small web page that shows today's date</span><span class="cur blink" style="margin-left:.6cqw"></span>
+<span class="bl">Build</span> <span class="dim">·</span> Muse Spark 1.3 Free</span></div>
+ <div class="kb"><div class="bar"><span>esc</span><span>^C</span><span>tab</span><span>clear</span><span>paste</span><span>⇧</span><span>ctrl</span><span>←</span></div><div class="rows"><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i class="w"></i><i></i></div></div></div>
+ </div>
+ <p class="cap"><b>New to coding agents.</b> OpenCode with the desktop's starter task typed in, not sent. The keyboard is up and the caret blinks at the end of the task: Return sends it.</p>
+ </div>
+ <div class="step">
+ <div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
+ <div class="ttl"><b>first-project</b><span>MacBook Pro:first-project</span></div>
+ <div class="out"><span class="logo"> ▄
+█▀▀█ █▀▀█ █▀▀█ █▀▀▄ █▀▀▀ █▀▀█ █▀▀█ █▀▀█
+█ █ █ █ █▀▀▀ █ █ █ █ █ █ █ █▀▀▀
+▀▀▀▀ █▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀</span><span class="box"><span class="u">make a small web page that shows today's date</span>
<span class="bl">Build</span> <span class="dim">·</span> Muse Spark 1.3 Free</span><span class="dim"> ctrl+p commands</span></div>
- <div class="sline">Send it, or say anything.</div>
+ <div class="sug"><div class="l">Send it, or say anything.</div><div class="pill"><span>make a small web page that shows today's date</span><b>Send</b></div></div>
<div class="mic"><svg class="i"><use href="#i-mic"/></svg></div>
<div class="home"></div></div>
- <p class="cap"><b>New to coding agents.</b> OpenCode with the desktop's starter task typed in, not sent.</p>
+ <p class="cap"><b>The keyboard put away.</b> The task as it now stands, with Send. The mic sends it too: it shows itself listening but records nothing and asks for no microphone, and its second tap sends the prompt.</p>
+ </div>
+ <div class="step">
+ <div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
+ <div class="ttl"><b>my-app</b><span>MacBook Pro:my-app</span></div>
+ <div class="out"><span class="cc">╭───────────────────────────────╮</span>
+<span class="cc">│</span> <span class="cc">✻</span> <span class="u">Welcome to Claude Code!</span> <span class="cc">│</span>
+<span class="cc">│</span> <span class="dim">/help for help</span> <span class="cc">│</span>
+<span class="cc">│</span> <span class="dim">cwd: ~/my-app</span> <span class="cc">│</span>
+<span class="cc">╰───────────────────────────────╯</span>
+
+<span class="u">&gt; Explain this project to me</span><span class="cur blink" style="margin-left:.6cqw"></span></div>
+ <div class="kb"><div class="bar"><span>esc</span><span>^C</span><span>tab</span><span>clear</span><span>paste</span><span>⇧</span><span>ctrl</span><span>←</span></div><div class="rows"><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><div class="row"><i></i><i></i><i class="w"></i><i></i></div></div></div>
+ </div>
+ <p class="cap"><b>Agents, but no past sessions.</b> A fresh Claude Code or Codex: the phone types the first New Harness idea into its empty prompt, not sent, and the keyboard is up. Put away, the line is "Say what to build, or send this:" over the same task and its Send.</p>
</div>
<div class="step">
<div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
@@ -680,21 +722,6 @@
<div class="home"></div></div>
<p class="cap"><b>Already uses Claude Code or Codex.</b> Their latest conversation, resumed where they left it.</p>
</div>
- <div class="step">
- <div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
- <div class="ttl"><b>my-app</b><span>MacBook Pro:my-app</span></div>
- <div class="out"><span class="cc">╭───────────────────────────────╮</span>
-<span class="cc">│</span> <span class="cc">✻</span> <span class="u">Welcome to Claude Code!</span> <span class="cc">│</span>
-<span class="cc">│</span> <span class="dim">/help for help</span> <span class="cc">│</span>
-<span class="cc">│</span> <span class="dim">cwd: ~/my-app</span> <span class="cc">│</span>
-<span class="cc">╰───────────────────────────────╯</span>
-
-<span class="u">&gt;</span> <span class="cur"></span></div>
- <div class="sline">Say what to build.</div>
- <div class="mic"><svg class="i"><use href="#i-mic"/></svg></div>
- <div class="home"></div></div>
- <p class="cap"><b>Agents, but no past sessions.</b> A fresh session at an empty prompt.</p>
- </div>
<div class="step">
<div class="ph"><div class="sb"><span>9:41</span><span class="bat"></span></div><div class="island"></div>
<div class="ttl"><b>docs-review</b><span>studio:harness</span><span>⑂ main</span></div>
@@ -713,9 +740,9 @@
</div>
<div class="tablewrap"><table>
<tr><th>Who</th><th>The desktop's first tab</th><th>The phone opens</th><th>By the mic, once</th></tr>
- <tr><td>New to coding agents</td><td>OpenCode with a starter task typed, not sent; Codex and Claude Code beside it on their own sign-in</td><td>OpenCode, the task waiting</td><td class="m">Send it, or say anything.</td></tr>
+ <tr><td>New to coding agents</td><td>OpenCode with a starter task typed, not sent; Codex and Claude Code beside it on their own sign-in</td><td>OpenCode, the task waiting in its box, keyboard up</td><td class="m">Send it, or say anything. — the task, with Send</td></tr>
<tr><td>Already uses Claude Code or Codex</td><td>Their most recently active conversations, resumed</td><td>The most recent one, history and all</td><td class="m">Pick up where you left off.</td></tr>
- <tr><td>Has agents, no past sessions</td><td>A fresh session for each agent</td><td>That agent, at an empty prompt</td><td class="m">Say what to build.</td></tr>
+ <tr><td>Has agents, no past sessions</td><td>A fresh session for each agent</td><td>That agent, the first New Harness idea typed into its prompt, keyboard up</td><td class="m">Say what to build, or send this: — the task, with Send</td></tr>
<tr><td>Harness already on the computer</td><td>Nothing changes</td><td>The session most recently in use</td><td class="m">Talk to it.</td></tr>
</table></div>
@@ -738,7 +765,9 @@
</div>
</div>
<p class="note" style="line-height:1.7"><b>Which session:</b> after ②, the computer set up for this phone; signed in to an account that already has computers, the first of them to be ready. The phone opens the session most recently in use there.<br>
- <b>The line</b> sits centred over the mic in the terminal's ground and goes with the first send. It is never shown in the sample.<br>
+ <b>The line</b> sits centred over the mic in the terminal's ground and goes with the first send. In a fresh session it carries the task with a Send: the prompt as it stands at the tap, so what was changed on the keyboard is what goes, replacing what the prompt holds, never joined to it. An OpenCode box emptied on the keyboard still offers the desktop's starter, never a task the screen did not show; a prompt holding a paste the agent shows as a marker (<code>[Pasted text #1 +12 lines]</code>) goes by Return as it is. It is never shown in the sample.<br>
+ <b>The keyboard</b> comes up once, as soon as the fresh session's prompt is drawn, with the caret blinking at the end of the task — not over a question the agent asks first, such as Claude Code's trust prompt, which is answered where it is drawn. Put away, it stays away. The first send — Return, Send or the mic — puts it away once the prompt has emptied, so what the harness does with the task is on screen; a Return that sent nothing (a file picked after <code>@</code>) keeps it up, and so does Return after the first send.<br>
+ <b>The mic in a fresh session</b> sends the task and records nothing: the listening face and meter, no microphone permission prompt (one in the middle of the onboarding costs more than the words are worth), and its second tap sends the prompt as it stands. Only that session's mic: Find's and New's record as always. While a question is on screen it records, since a spoken answer is for the question. From the first send on it records again, and the permission is asked the first time it does.<br>
<b>No tips before the first look.</b> The four Focus tips used to come over the first session, then the notification prompt. Now neither: the tips come back only from Settings ▸ Show the tips again.<br>
<b>A computer linked by its password</b> (not by sign-in) opens on "Pick up where you left off", a list of every session to tap into, rather than guessing one.</p>
diff --git a/mobile/integration_test/first_task_test.dart b/mobile/integration_test/first_task_test.dart
new file mode 100644
index 000000000..6770decbd
--- /dev/null
+++ b/mobile/integration_test/first_task_test.dart
@@ -0,0 +1,342 @@
+import 'dart:io' show Platform;
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:xterm/xterm.dart' show Terminal;
+
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/engine_availability.dart';
+import 'package:harness_mobile/core/first_task.dart';
+import 'package:harness_mobile/demo/main_sample.dart' show SampleApp;
+import 'package:harness_mobile/demo/sample_mode.dart' show SampleMode;
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/new_agent_draft.dart';
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/phone/phone_shell.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/first_task_suggestion.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/tty_controls.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/phone/voice_mic_button.dart';
+import 'package:harness_mobile/phone/welcome/onboarding_copy.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+import '../test/voice_fakes.dart';
+
+const _studio = 'sample-studio';
+
+/// The first session's chips and New Harness's engine choice, in the real app on a phone, over the
+/// offline sample: its computer stands in for the owner's, so no account, no network and no real
+/// computer is touched. A screenshot at each step.
+///
+/// HARNESS_PHONE=iphone14 flutter drive -d <phone> --driver=test_driver/first_task_driver.dart \
+/// --target=integration_test/first_task_test.dart
+///
+/// Android needs its surface converted to an image before a screenshot can read it (once).
+void main() {
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('first session chips, and the engine New Harness opens on', (
+ tester,
+ ) async {
+ var step = 0;
+ var surfaceReady = !Platform.isAndroid;
+ Future<void> shot(String name) async {
+ await tester.pump(const Duration(milliseconds: 300));
+ if (!surfaceReady) {
+ await binding.convertFlutterSurfaceToImage();
+ await tester.pump();
+ surfaceReady = true;
+ }
+ step++;
+ await binding.takeScreenshot('${step.toString().padLeft(2, '0')}-$name');
+ }
+
+ Future<void> wait([int ms = 600]) async {
+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ Future<void> waitFor(Finder finder, {int seconds = 20}) async {
+ for (var i = 0; i < seconds * 10; i++) {
+ if (finder.evaluate().isNotEmpty) return;
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ fail('never appeared: $finder');
+ }
+
+ late AppNotifier notifier;
+ Future<void> openAgent(String agentId) async {
+ PhoneShellScope.maybeOf(tester.element(find.byType(AgentHome)))!
+ .onOpenAgent(_studio, agentId);
+ await wait(2000);
+ }
+
+ String screenOf(String agentId) {
+ final session = notifier.paneOfAgent(_studio, agentId)?.session;
+ if (session == null) return '';
+ final lines = session.terminal.buffer.lines;
+ return [for (var i = 0; i < lines.length; i++) lines[i].toString()]
+ .join('\n')
+ .replaceAll(RegExp(r'\s*\n\s*'), ' ');
+ }
+
+ String agentRow() => tester
+ .widget<TtyFormRow>(
+ find.byWidgetPredicate((w) => w is TtyFormRow && w.label == 'agent'),
+ )
+ .value;
+
+ Future<void> openNewHarness() async {
+ await openAgent('sample-fix-login');
+ await tester.dragFrom(
+ tester.getCenter(find.byType(AgentHome).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await wait(900);
+ await tester.tap(find.byKey(const ValueKey('find-new-harness')));
+ await waitFor(find.byType(NewAgentPage));
+ await wait(1200);
+ }
+
+ Future<void> leaveNewHarness() async {
+ Navigator.of(tester.element(find.byType(NewAgentPage))).pop();
+ await wait(900);
+ // A form left keeps its draft, engine included (saved as it is taken down); each visit here
+ // starts fresh.
+ newAgentDraft = null;
+ }
+
+ await tester.pumpWidget(const SampleApp());
+ await waitFor(find.text('fix-login', findRichText: true));
+ await wait(3000);
+ notifier = tester.widget<PhoneShell>(find.byType(PhoneShell)).notifier;
+ // The sample's computer is signed in to Claude Code and Codex, Claude Code used last.
+ await shot('computer-reached');
+
+ // New Harness on a computer with Claude signed in: it opens on Claude Code.
+ await openNewHarness();
+ expect(agentRow(), 'Claude Code');
+ await shot('new-harness-claude-signed-in');
+ await leaveNewHarness();
+
+ // Nothing signed in on the computer: OpenCode, never an engine that cannot be used.
+ notifier.machineStates[_studio]!.engines.replace(const [
+ EngineAvailability(engine: 'claude', installed: true, signedIn: false),
+ EngineAvailability(engine: 'codex', installed: true, signedIn: false),
+ EngineAvailability(engine: 'opencode', installed: true, signedIn: false),
+ ]);
+ await openNewHarness();
+ expect(agentRow(), 'OpenCode');
+ await shot('new-harness-nothing-signed-in');
+ await leaveNewHarness();
+ notifier.machineStates[_studio]!.engines.replace(const [
+ EngineAvailability(
+ engine: 'claude',
+ installed: true,
+ signedIn: true,
+ lastUsedAt: 2,
+ ),
+ EngineAvailability(engine: 'codex', installed: true, signedIn: false),
+ ]);
+
+ // A harness of the person's own, started on Claude Code. The sample's tour is over (its guide
+ // would otherwise own the line by the mic), as it is on a real computer.
+ SampleMode.maybeOf(tester.element(find.byType(AgentHome)))!.endCardSeen =
+ true;
+ await openNewHarness();
+ expect(agentRow(), 'Claude Code');
+ await tester.tap(find.text('project'));
+ await wait(500);
+ await tester.tap(
+ find.textContaining('studio:~/code/web', findRichText: true),
+ );
+ await wait(500);
+ await tester.tap(find.text('Start'));
+ await wait(3000);
+ final agentId = notifier
+ .stateOf(_studio)!
+ .agents
+ .map((agent) => agent.id)
+ .singleWhere((id) => id.startsWith('sample-new-'));
+
+ // The first session, as the hand-over from the onboarding opens it.
+ // Leaving a session spends its line, so the harness's page goes first and is opened again.
+ await openAgent('sample-api-tests');
+ notifier.firstSessionLine = (
+ machineId: _studio,
+ agentId: agentId,
+ text: OnboardingCopy.micSayWhat,
+ );
+ await openAgent(agentId);
+ await waitFor(find.text(OnboardingCopy.micSayWhat));
+ expect(find.text(firstTaskIdeas.first, findRichText: true), findsOneWidget);
+ for (final other in firstTaskIdeas.skip(1)) {
+ expect(find.text(other, findRichText: true), findsNothing);
+ }
+ await shot('first-session-suggestion');
+
+ // Send sends the suggestion at once, and the computer gets it. (The sample never spends the
+ // line: a sample's sends do not answer the onboarding — `_onLineSent` — so its suggestion stays;
+ // the real page below shows it go.)
+ await tester.tap(find.byKey(FirstSessionSuggestion.sendKey));
+ await wait(200);
+ await shot('send-tapped');
+ await wait(2500);
+ expect(screenOf(agentId), contains('> ${firstTaskIdeas.first}'));
+ await shot('task-on-the-computer');
+
+ // The production page over a fake transport, and the production voice controller over a fake
+ // recorder and recognizer: no microphone, no network. A page is opened for each run.
+ final language = ValueNotifier('en');
+ addTearDown(language.dispose);
+ Future<
+ ({
+ AppNotifier app,
+ TerminalSession session,
+ VoiceInputController voice,
+ FakeTranscriber transcriber,
+ List<(String, Object)> sent,
+ })
+ >
+ openRealPage({
+ TerminalSessionStatus status = TerminalSessionStatus.controlling,
+ }) async {
+ final sent = <(String, Object)>[];
+ late TerminalSession session;
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, payload) async {
+ sent.add((type, payload));
+ if (type == 'message') {
+ session.terminal.write(
+ '\r\n> ${(payload as Map)['content']}\r\n⏺ On it.\r\n',
+ );
+ }
+ return true;
+ },
+ sendBinary: (frame) async => true,
+ )
+ ..status = status
+ ..streamId = 'stream';
+ app.adoptSessionForTest(session);
+ // What the agent had drawn before the first message: its welcome and an empty prompt.
+ session.seedScreen(
+ Terminal(maxLines: 500)..write(
+ '\u2554 Welcome to Claude Code!\r\n cwd: ~/code/web\r\n\r\n> ',
+ ),
+ );
+ final transcriber = FakeTranscriber();
+ final voice = VoiceInputController(
+ transcriber: transcriber.call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ app.firstSessionLine = (
+ machineId: 'm',
+ agentId: 'a',
+ text: OnboardingCopy.micSayWhat,
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: TerminalPage(
+ notifier: app,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await waitFor(find.text(OnboardingCopy.micSayWhat));
+ return (
+ app: app,
+ session: session,
+ voice: voice,
+ transcriber: transcriber,
+ sent: sent,
+ );
+ }
+
+ Future<void> closeRealPage(
+ VoiceInputController voice,
+ AppNotifier app,
+ ) async {
+ await tester.pumpWidget(const SizedBox());
+ voice.dispose();
+ app.dispose();
+ }
+
+ List<Object?> messages(List<(String, Object)> sent) => [
+ for (final m in sent)
+ if (m.$1 == 'message') (m.$2 as Map)['content'],
+ ];
+ final send = find.byKey(FirstSessionSuggestion.sendKey);
+ bool sendEnabled() =>
+ tester
+ .widget<FirstSessionSuggestion>(find.byType(FirstSessionSuggestion))
+ .onSend !=
+ null;
+
+ // Send is disabled while the session does not take input (here resyncing), and wakes with it.
+ final waiting = await openRealPage(status: TerminalSessionStatus.resyncing);
+ expect(sendEnabled(), isFalse);
+ await shot('send-disabled-app-page');
+ await tester.tap(send, warnIfMissed: false);
+ await wait(300);
+ expect(messages(waiting.sent), isEmpty);
+ waiting.session.status = TerminalSessionStatus.controlling;
+ waiting.session.notifyListeners();
+ await wait(300);
+ expect(sendEnabled(), isTrue);
+ await shot('send-enabled-app-page');
+
+ // One tap sends exactly the suggestion once, and the suggestion goes with the line.
+ await tester.tap(send);
+ await tester.tap(send, warnIfMissed: false);
+ await wait(300);
+ await shot('send-tapped-app-page');
+ await wait(1500);
+ expect(messages(waiting.sent), [firstTaskIdeas.first]);
+ expect(waiting.app.firstSessionLine, isNull);
+ expect(send, findsNothing);
+ expect(find.text(firstTaskIdeas.first), findsNothing);
+ await shot('suggestion-gone-app-page');
+ await closeRealPage(waiting.voice, waiting.app);
+
+ // The mic is the other way in: the real controller and mic button, an injected transcript.
+ final spoken = await openRealPage();
+ await shot('voice-suggestion-app-page');
+ spoken.transcriber.replies.add('add a login page');
+ await tester.tap(find.byType(VoiceMicButton));
+ await wait(600);
+ expect(spoken.voice.status, VoiceInputStatus.listening);
+ // The take is on: the suggestion and its line wait, nothing is left standing over an empty row.
+ expect(send, findsNothing);
+ expect(find.text(OnboardingCopy.micSayWhat), findsNothing);
+ await shot('voice-listening-app-page');
+ await tester.tap(find.byType(VoiceMicButton));
+ await wait(1500);
+ expect(messages(spoken.sent), ['add a login page']);
+ expect(spoken.app.firstSessionLine, isNull);
+ expect(send, findsNothing);
+ await shot('voice-sent-suggestion-gone-app-page');
+ await closeRealPage(spoken.voice, spoken.app);
+ });
+}
diff --git a/mobile/integration_test/tour_test.dart b/mobile/integration_test/tour_test.dart
index ff38cfb3e..3b2be5de0 100644
--- a/mobile/integration_test/tour_test.dart
+++ b/mobile/integration_test/tour_test.dart
@@ -1,3 +1,5 @@
+import 'dart:io' show Platform;
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@@ -15,8 +17,15 @@ void main() {
testWidgets('a tour of every screen', (tester) async {
var step = 0;
+ var surfaceReady = !Platform.isAndroid;
Future<void> shot(String name) async {
await tester.pump(const Duration(milliseconds: 300));
+ // Android draws into a SurfaceView the screenshot cannot read until it becomes an image, once.
+ if (!surfaceReady) {
+ await binding.convertFlutterSurfaceToImage();
+ await tester.pump();
+ surfaceReady = true;
+ }
step++;
await binding.takeScreenshot('${step.toString().padLeft(2, '0')}-$name');
}
@@ -89,7 +98,8 @@ void main() {
await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
await wait(900);
await shot('menu');
- await tester.tapAt(const Offset(200, 150));
+ // Above the sheet: on a shorter screen (a 360 × 780 Android) the sheet starts above y = 150.
+ await tester.tapAt(const Offset(200, 40));
await wait(700);
// Find, and each of its modes.
diff --git a/mobile/lib/core/client_build.dart b/mobile/lib/core/client_build.dart
new file mode 100644
index 000000000..6137c03c7
--- /dev/null
+++ b/mobile/lib/core/client_build.dart
@@ -0,0 +1,77 @@
+import 'dart:async';
+import 'dart:io' show Platform;
+
+import 'package:flutter/foundation.dart';
+
+import 'app_version.dart';
+
+/// What the relay socket tells the backend of the build that opened it (`/api/web-ws?client=mobile`), so
+/// its count of the phone's opens (`relay_mobile_opens`) can be read by release, and a debug build or a
+/// simulator left open cannot pass for the store's. Nothing that tells one phone from another.
+///
+/// Read by the backend as `?release=` (a plain x.y.z, else the open counts under `unknown`) and
+/// `?debug=1` (opens from a debug or simulator build are counted apart, not under a release).
+@immutable
+class ClientBuild {
+ const ClientBuild({this.release, this.debug = false});
+
+ /// The public release (`1.0.9`, no build number), or null where it is not a plain x.y.z.
+ final String? release;
+
+ /// A build that is not a release build, or one running in the iOS Simulator.
+ final bool debug;
+
+ /// The socket's extra query: nothing for a build that says neither.
+ Map<String, String> get query => {
+ 'release': ?release,
+ if (debug) 'debug': '1',
+ };
+}
+
+final _plainRelease = RegExp(r'^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){2}$');
+
+/// The build, from what the platform says of it. Apart from [runningClientBuild] so a test can name
+/// each input.
+///
+/// A debug or profile build is `debug` (what `flutter run` makes, on a phone, a simulator or an
+/// emulator), as is anything running in the iOS Simulator (the simulator's own environment names it).
+/// An Android emulator running a release build is not told apart: Android has no such mark without
+/// native code.
+@visibleForTesting
+ClientBuild clientBuildOf({
+ required String? version,
+ required bool releaseMode,
+ required TargetPlatform platform,
+ required Map<String, String> environment,
+}) => ClientBuild(
+ release: version != null && _plainRelease.hasMatch(version) ? version : null,
+ debug:
+ !releaseMode ||
+ (platform == TargetPlatform.iOS &&
+ environment.containsKey('SIMULATOR_DEVICE_NAME')),
+);
+
+Future<ClientBuild>? _running;
+
+/// This build, read once and kept: the socket asks at every dial, so only the first can wait.
+/// Never throws: a version that cannot be read is a release the backend counts as `unknown`.
+Future<ClientBuild> runningClientBuild() => _running ??= _read();
+
+Future<ClientBuild> _read() async {
+ String? version;
+ try {
+ version = await runningAppVersion();
+ } catch (_) {}
+ var environment = const <String, String>{};
+ if (!kIsWeb) {
+ try {
+ environment = Platform.environment;
+ } catch (_) {}
+ }
+ return clientBuildOf(
+ version: version,
+ releaseMode: kReleaseMode,
+ platform: defaultTargetPlatform,
+ environment: environment,
+ );
+}
diff --git a/mobile/lib/core/engine_availability.dart b/mobile/lib/core/engine_availability.dart
index 86564cb66..98adff110 100644
--- a/mobile/lib/core/engine_availability.dart
+++ b/mobile/lib/core/engine_availability.dart
@@ -21,6 +21,8 @@ class EngineAvailability {
this.supportsCodexHome = false,
this.installable = false,
this.installCommand,
+ this.signedIn,
+ this.lastUsedAt,
});
final String engine;
@@ -51,6 +53,11 @@ class EngineAvailability {
/// [installable] covers remote ones — is not a thing to do unannounced.
final String? installCommand;
+ /// Reported by this computer, never inferred from installation or this phone's history.
+ /// Null from an older computer that does not report credentials or session activity.
+ final bool? signedIn;
+ final int? lastUsedAt;
+
static EngineAvailability? fromJson(Object? raw) {
if (raw is! Map) return null;
final engine = raw['engine'];
@@ -66,6 +73,10 @@ class EngineAvailability {
installCommand: installCommand is String && installCommand.isNotEmpty
? installCommand
: null,
+ signedIn: raw['signedIn'] is bool ? raw['signedIn'] as bool : null,
+ lastUsedAt: raw['lastUsedAt'] is num
+ ? (raw['lastUsedAt'] as num).toInt()
+ : null,
);
}
}
diff --git a/mobile/lib/core/first_engine.dart b/mobile/lib/core/first_engine.dart
new file mode 100644
index 000000000..85d84dac9
--- /dev/null
+++ b/mobile/lib/core/first_engine.dart
@@ -0,0 +1,21 @@
+import 'engine_availability.dart';
+
+/// Desktop's New Harness account-agent rule (`state/new_harness.dart`): only
+/// this computer's installed, signed-in Claude Code or Codex; latest use wins.
+/// An older daemon that cannot report sign-in cannot establish either fact.
+String firstEngine(MachineEngines? engines) {
+ String best = 'opencode';
+ var bestAt = -1;
+ for (final id in const ['claude', 'codex']) {
+ final engine = engines?[id];
+ if (engine == null || !engine.installed || engine.signedIn != true) {
+ continue;
+ }
+ final at = engine.lastUsedAt ?? 0;
+ if (best == 'opencode' || at > bestAt) {
+ best = id;
+ bestAt = at;
+ }
+ }
+ return best;
+}
diff --git a/mobile/lib/core/first_task.dart b/mobile/lib/core/first_task.dart
index 3356645ee..f0b65c528 100644
--- a/mobile/lib/core/first_task.dart
+++ b/mobile/lib/core/first_task.dart
@@ -1,6 +1,13 @@
// What a machine accepts as a harness's first task (`prompt` on `agent_create`) — the desktop's
// rule, kept to the same answer as `desktop/lib/core/first_task.dart`.
+/// The first tasks offered by New Harness and the phone's first session.
+const firstTaskIdeas = [
+ 'Explain this project to me',
+ 'Find a bug and fix it',
+ 'Run the tests',
+];
+
/// The engines that can be opened with a first message: the non-null entries of the CLI's
/// `FIRST_PROMPT_ARGS` (cli/src/lib/engineLaunch.ts). A machine refuses a first message for any
/// other engine (`PROMPT_UNSUPPORTED`). test/first_task_test.dart holds the two lists to the same
diff --git a/mobile/lib/demo/sample_runtime.dart b/mobile/lib/demo/sample_runtime.dart
index 51598146b..fb4b1cda3 100644
--- a/mobile/lib/demo/sample_runtime.dart
+++ b/mobile/lib/demo/sample_runtime.dart
@@ -321,6 +321,11 @@ class SampleRuntime implements SampleHarnessHost {
{
'engine': engine,
'installed': engine == 'claude' || engine == 'codex',
+ // Both signed in, Claude Code used last: New Harness opens on it, as the sample's
+ // harnesses show.
+ if (engine == 'claude' || engine == 'codex') 'signedIn': true,
+ if (engine == 'claude') 'lastUsedAt': 2,
+ if (engine == 'codex') 'lastUsedAt': 1,
'installable': true,
'command': engine,
if (engine == 'codex') 'supportsCodexHome': true,
diff --git a/mobile/lib/measurement/product_connections.dart b/mobile/lib/measurement/product_connections.dart
index e9b883af8..c2fb35243 100644
--- a/mobile/lib/measurement/product_connections.dart
+++ b/mobile/lib/measurement/product_connections.dart
@@ -103,6 +103,25 @@ class ProductConnections {
entry.finish(outcome);
}
+ /// The app went to the background with these dials open: each ends `cancelled`, as `remote_connect`'s do —
+ /// the phone left before the socket answered, and a suspended app may never hear it. Both kinds end, and
+ /// an asked-for dial's [manualDeadline] goes with it, so nothing is counted `failed` later. They leave the
+ /// maps as they end: the socket's own answer finds none to end again, and a dial once the app is back is
+ /// a new count.
+ void cancelOpen() {
+ final asked = _manual.values.toList();
+ final own = _pending.values.toList();
+ _manual.clear();
+ _pending.clear();
+ for (final entry in asked) {
+ entry.deadline.cancel();
+ entry.finish(ProductOutcome.cancelled);
+ }
+ for (final finish in own) {
+ finish(ProductOutcome.cancelled);
+ }
+ }
+
/// Drops every open observation uncounted: a sign-out, another account, a sharing change.
void clear() {
_pending.clear();
diff --git a/mobile/lib/phone/computer_password_page.dart b/mobile/lib/phone/computer_password_page.dart
new file mode 100644
index 000000000..feb1a46b4
--- /dev/null
+++ b/mobile/lib/phone/computer_password_page.dart
@@ -0,0 +1,204 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Computers ▸ a Harness OS computer ▸ Change password: its one password — the disk's, asked at
+/// every start where it is encrypted (and what Unlock sends), and its account's, for SSH, sudo and
+/// the lock screen — changed together, as the installer set them (CLI osDevice.ts `password`,
+/// os/setup.py `change_password`). The current one is checked there first.
+class ComputerPasswordPage extends StatefulWidget {
+ const ComputerPasswordPage({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+
+ @override
+ State<ComputerPasswordPage> createState() => _ComputerPasswordPageState();
+}
+
+class _ComputerPasswordPageState extends State<ComputerPasswordPage> {
+ final _current = TextEditingController();
+ final _new = TextEditingController();
+ final _repeat = TextEditingController();
+ bool _busy = false;
+ bool _reveal = false;
+ String _error = '';
+
+ AppNotifier get _app => widget.notifier;
+ String get _name =>
+ _app.stateOf(widget.machineId)?.machine.displayName ?? 'The computer';
+
+ @override
+ void dispose() {
+ _current.dispose();
+ _new.dispose();
+ _repeat.dispose();
+ super.dispose();
+ }
+
+ Future<void> _change() async {
+ final current = _current.text, next = _new.text;
+ String why = '';
+ if (current.isEmpty) {
+ why = 'Enter the current password.';
+ } else if (next.isEmpty) {
+ why = 'Enter a new password.';
+ } else if (next != _repeat.text) {
+ why = 'The new passwords are not the same.';
+ } else if (next == current) {
+ why = 'That is the password already.';
+ }
+ if (why.isNotEmpty) {
+ setState(() => _error = why);
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _error = '';
+ });
+ final reply = await _app.osDevice(widget.machineId, {
+ 'action': 'password',
+ 'current': current,
+ 'next': next,
+ }, timeout: const Duration(seconds: 100));
+ if (!mounted) return;
+ if (reply['ok'] == true) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ content: Text(
+ reply['disk'] == true
+ ? 'Password changed. Use the new one to unlock $_name when it starts.'
+ : 'Password changed.',
+ ),
+ ),
+ );
+ Navigator.of(context).maybePop();
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error =
+ reply['message'] as String? ??
+ (reply['error'] == 'UNAVAILABLE'
+ ? 'Could not reach $_name. Try again.'
+ : 'The password did not change. Try again.');
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ Text say(String text) => Text(text, style: tty.style(color: tty.dim));
+ final encrypted = _app.harnessOsComputers[widget.machineId]?.encrypted;
+ Widget eye() => AppIconButton(
+ icon: _reveal ? LucideIcons.eyeOff300 : LucideIcons.eye300,
+ size: 20,
+ tooltip: _reveal ? 'Hide passwords' : 'Show passwords',
+ color: tty.dim,
+ onPressed: () => setState(() => _reveal = !_reveal),
+ );
+ TtyField field(
+ Key key,
+ TextEditingController controller,
+ String hint, {
+ bool focus = false,
+ VoidCallback? submit,
+ }) => TtyField(
+ key: key,
+ controller: controller,
+ hint: hint,
+ autofocus: focus,
+ keyboardType: TextInputType.visiblePassword,
+ obscure: !_reveal,
+ maxLength: 128,
+ onSubmitted: _busy ? null : submit,
+ trailing: [eye()],
+ );
+ return Scaffold(
+ backgroundColor: tty.ground,
+ resizeToAvoidBottomInset: false,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom +
+ MediaQuery.viewInsetsOf(context).bottom +
+ 24,
+ ),
+ children: [
+ const TtyText(
+ 'Change password',
+ size: TtySize.display,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ say(
+ '$_name has one password, and this changes it everywhere at once: '
+ '${encrypted == false ? '' : 'unlocking it when it starts (Unlock on this phone, or its screen), '}'
+ 'SSH, sudo and its lock screen.',
+ ),
+ const SizedBox(height: 16),
+ field(
+ const Key('password-current'),
+ _current,
+ 'Current password',
+ focus: true,
+ ),
+ const SizedBox(height: 12),
+ field(const Key('password-new'), _new, 'New password'),
+ const SizedBox(height: 12),
+ field(
+ const Key('password-repeat'),
+ _repeat,
+ 'New password again',
+ submit: () => unawaited(_change()),
+ ),
+ if (_error.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ Text(
+ _error,
+ key: const Key('password-error'),
+ style: tty.style(color: tty.red),
+ ),
+ ],
+ const SizedBox(height: 20),
+ TtyPrimaryButton(
+ key: const Key('password-change'),
+ label: 'Change password',
+ busy: _busy,
+ busyLabel: 'Changing… (a few seconds)',
+ onPressed: () => unawaited(_change()),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/computer_ssh_page.dart b/mobile/lib/phone/computer_ssh_page.dart
new file mode 100644
index 000000000..75ba020b7
--- /dev/null
+++ b/mobile/lib/phone/computer_ssh_page.dart
@@ -0,0 +1,177 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'settings_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Computers ▸ a Harness OS computer ▸ SSH: on or off (off as installed), and the private addresses
+/// it answers on, for `ssh me@<address>` from a computer on the same network (CLI osDevice.ts `ssh`,
+/// os/setup.py `ssh`).
+class ComputerSshPage extends StatefulWidget {
+ const ComputerSshPage({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+
+ @override
+ State<ComputerSshPage> createState() => _ComputerSshPageState();
+}
+
+class _ComputerSshPageState extends State<ComputerSshPage> {
+ Map<String, dynamic>? _state;
+ bool _busy = true;
+ String _error = '';
+
+ AppNotifier get _app => widget.notifier;
+ String get _name =>
+ _app.stateOf(widget.machineId)?.machine.displayName ?? 'The computer';
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_ask('status'));
+ }
+
+ Future<void> _ask(String state) async {
+ setState(() {
+ _busy = true;
+ _error = '';
+ });
+ final reply = await _app.osDevice(widget.machineId, {
+ 'action': 'ssh',
+ 'state': state,
+ }, timeout: const Duration(seconds: 40));
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ if (reply.containsKey('enabled')) {
+ _state = reply;
+ } else {
+ _error =
+ reply['message'] as String? ??
+ 'Could not reach $_name. Pull down to try again.';
+ }
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ Text say(String text, {Color? color}) =>
+ Text(text, style: tty.style(color: color ?? tty.dim));
+ final on = _state?['enabled'] == true || _state?['active'] == true;
+ final user = _state?['user'] as String? ?? 'me';
+ final addresses = [
+ for (final row in (_state?['addresses'] as List?) ?? const [])
+ if (row is Map && row['address'] is String) row,
+ ];
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: RefreshIndicator(
+ onRefresh: () => _ask('status'),
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom + 24,
+ ),
+ children: [
+ const TtyText(
+ 'SSH',
+ size: TtySize.display,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ if (_error.isNotEmpty)
+ say(_error, color: tty.red)
+ else if (_state == null)
+ const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ else ...[
+ say(
+ on
+ ? 'SSH is on. Anyone on the same network who has $_name\'s password can sign in to it.'
+ : 'SSH is off. Turn it on to reach $_name from another computer on the same network.',
+ ),
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ key: const Key('ssh-state'),
+ title: 'SSH',
+ value: on ? 'On' : 'Off',
+ ),
+ for (final row in addresses)
+ SettingsRow(
+ key: ValueKey('ssh-address-${row['address']}'),
+ title: row['address'] as String,
+ detail: on
+ ? 'ssh $user@${row['address']} · tap to copy'
+ : row['interface'] as String?,
+ onTap: on
+ ? () {
+ unawaited(
+ Clipboard.setData(
+ ClipboardData(
+ text: 'ssh $user@${row['address']}',
+ ),
+ ),
+ );
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(
+ const SnackBar(
+ content: Text('Copied.'),
+ ),
+ );
+ }
+ : null,
+ ),
+ if (addresses.isEmpty)
+ const SettingsRow(
+ title: 'No address',
+ detail: 'It is not on a network right now.',
+ ),
+ ],
+ ),
+ const SizedBox(height: 20),
+ TtyPrimaryButton(
+ key: const Key('ssh-toggle'),
+ label: on ? 'Turn SSH off' : 'Turn SSH on',
+ busy: _busy,
+ busyLabel: on ? 'Turning off…' : 'Turning on…',
+ onPressed: () => unawaited(_ask(on ? 'off' : 'on')),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/computer_version_page.dart b/mobile/lib/phone/computer_version_page.dart
new file mode 100644
index 000000000..635117556
--- /dev/null
+++ b/mobile/lib/phone/computer_version_page.dart
@@ -0,0 +1,488 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'phone_navigation.dart';
+import 'phone_status.dart';
+import 'phone_sheet.dart';
+import 'settings_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+import 'unlock_computer_page.dart';
+
+/// A version as a person reads it: the release, without the build pacman names a package by
+/// (`0.1.8.r1792577066.g8df82cc2bc-1` is `0.1.8`). Anything else as it is.
+String? shortVersion(String? version) {
+ if (version == null) return null;
+ return RegExp(r'^\d+\.\d+\.\d+').firstMatch(version)?.group(0) ?? version;
+}
+
+/// Computers ▸ a Harness OS computer ▸ Version: what it runs, part by part — its OS, hn and the CLI
+/// (CLI osDevice.ts `update.parts`) — with a dot where a new one waits, and its Update.
+///
+/// hn and the CLI come as one runtime: updated together, with no restart. A new OS restarts the
+/// computer once it is in (`harness update --reboot`); an encrypted one then waits for its password,
+/// unlocked from here ([UnlockComputerPage]).
+class ComputerVersionPage extends StatefulWidget {
+ const ComputerVersionPage({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+
+ @override
+ State<ComputerVersionPage> createState() => _ComputerVersionPageState();
+}
+
+class _ComputerVersionPageState extends State<ComputerVersionPage> {
+ bool _asking = true;
+ bool _starting = false;
+
+ /// Started from here and not finished: what it is doing, said under a spinner.
+ String _started = '';
+
+ /// A restart is part of it: the computer goes offline, and comes back (or waits to be unlocked).
+ bool _restarting = false;
+
+ /// It went offline for its restart.
+ bool _wentDown = false;
+
+ /// The update started here carried a new OS: named with the rest once it is in.
+ bool _systemUpdate = false;
+
+ /// A new OS on a computer that does not restart itself: done when the update is in, waiting for it.
+ bool _manualRestart = false;
+
+ /// How it ended: done (green) or not confirmed (red).
+ String _finished = '';
+ bool _finishedWell = false;
+ Timer? _watch;
+
+ /// How long an update gets before the page stops waiting and says so.
+ static const _updateFor = Duration(minutes: 6);
+
+ AppNotifier get _app => widget.notifier;
+ String get _id => widget.machineId;
+ String get _name => _app.stateOf(_id)?.machine.displayName ?? 'The computer';
+
+ @override
+ void initState() {
+ super.initState();
+ _app.addListener(_changed);
+ unawaited(_refresh());
+ }
+
+ @override
+ void dispose() {
+ _watch?.cancel();
+ _app.removeListener(_changed);
+ super.dispose();
+ }
+
+ /// Unlocked and online again after the restart: the rest of the update. hn and the CLI waiting
+ /// with it are activated by the first check after a restart, a few minutes in; asked for now,
+ /// under the same spinner, until each part says its new version.
+ Future<void> _unlock(String hotspot) async {
+ await Navigator.of(context).push(
+ phoneRoute(
+ (_) => UnlockComputerPage(
+ notifier: _app,
+ machineId: _id,
+ hotspotName: hotspot,
+ ),
+ ),
+ );
+ // Back without it online (the person left the Unlock page): nothing to finish yet.
+ if (!mounted || !_isOnline()) return;
+ setState(() {
+ _restarting = false;
+ _wentDown = false;
+ _finished = '';
+ _started = 'Finishing the update…';
+ });
+ // Its own answer, not the one from before the restart: the phone's line to the restarted daemon
+ // comes back a little after the account says it is online.
+ final stale = _app.osStatus[_id];
+ final deadline = DateTime.now().add(const Duration(minutes: 2));
+ while (mounted && DateTime.now().isBefore(deadline)) {
+ await _app.refreshOsStatus(_id, force: true);
+ if (!identical(stale, _app.osStatus[_id])) break;
+ await Future<void>.delayed(const Duration(seconds: 4));
+ }
+ if (!mounted) return;
+ if (_app.updateAvailable(_id) && !_app.updateRestarts(_id)) {
+ await _app.osDevice(_id, {'action': 'update'});
+ if (!mounted) return;
+ setState(() => _started = 'Finishing the update: hn and the CLI…');
+ }
+ _follow(encrypted: true);
+ }
+
+ /// From going down to its Wi-Fi up at the password: how long the computer's startup takes.
+ static const _hotspotAfter = Duration(seconds: 20);
+
+ /// Counted down under the spinner once it went down, then Unlock.
+ void _awaitHotspot() {
+ final hotspot = _app.harnessOsComputers[_id]?.hotspot ?? 'Harness-…';
+ var left = _hotspotAfter.inSeconds;
+ void say() => setState(
+ () => _started =
+ '$_name is restarting. Its Wi-Fi "$hotspot" opens in about ${left}s…',
+ );
+ say();
+ _watch = Timer.periodic(const Duration(seconds: 1), (_) {
+ if (!mounted) return;
+ left--;
+ if (left > 0) {
+ say();
+ return;
+ }
+ _watch?.cancel();
+ setState(() {
+ _started = '';
+ _finishedWell = true;
+ _finished =
+ '$_name updated and restarted. It waits for its password on "$hotspot": unlock it here.';
+ });
+ });
+ }
+
+ /// Online both ways: the account says it runs, and this phone's own line to it is not down — the
+ /// first to know when it restarts (a clean restart tells the relay at once; the account's list
+ /// is only as fresh as its last read).
+ bool _isOnline() {
+ final state = _app.stateOf(_id);
+ if (state != null &&
+ phoneMachineStatusOf(state) == PhoneMachineStatus.offline) {
+ return false;
+ }
+ return _app.machines.where((m) => m.machineId == _id).firstOrNull?.status ==
+ 'running';
+ }
+
+ String _versionsNow() {
+ final parts = _app.osParts(_id);
+ String? of(String key) => shortVersion(parts[key]?['running'] as String?);
+ // A daemon that does not name its parts (released before them) still says which CLI it runs.
+ final update = _app.osStatus[_id]?['update'];
+ final cli =
+ of('cli') ?? (update is Map ? update['runtime'] as String? : null);
+ final named = [
+ if (of('os') != null && _systemUpdate) 'Harness OS ${of('os')}',
+ if (of('hn') != null) 'hn ${of('hn')}',
+ if (cli != null) 'CLI $cli',
+ ];
+ return named.isEmpty ? '' : ': ${named.join(', ')}';
+ }
+
+ /// Asked every few seconds until the update is in: the computer answers again with nothing
+ /// waiting. With a restart, it first goes offline; an encrypted one then waits to be unlocked.
+ void _follow({required bool encrypted}) {
+ final deadline = DateTime.now().add(_updateFor);
+ var asking = false;
+ _watch?.cancel();
+ _watch = Timer.periodic(const Duration(seconds: 5), (_) async {
+ if (asking || !mounted || _started.isEmpty) return;
+ asking = true;
+ try {
+ if (_restarting) {
+ // The account's word, asked afresh: the list held here is not, while this page waits.
+ try {
+ await _app.refreshMachines();
+ } catch (_) {
+ // Asked again in a moment.
+ }
+ if (!mounted || _started.isEmpty) return;
+ }
+ if (_restarting && !_isOnline()) {
+ _wentDown = true;
+ if (encrypted) {
+ // Down for its restart: its startup opens its Wi-Fi some 20 seconds later, waiting
+ // for its password. The rest is the Unlock page's.
+ _watch?.cancel();
+ _awaitHotspot();
+ return;
+ }
+ }
+ final before = _app.osStatus[_id];
+ await _app.refreshOsStatus(_id, force: true);
+ if (!mounted || _started.isEmpty) return;
+ final answered = !identical(before, _app.osStatus[_id]);
+ final restartRequired =
+ (_app.osStatus[_id]?['update'] as Map?)?['restartRequired'] == true;
+ if (answered && _manualRestart && restartRequired) {
+ // An older computer does not restart itself: the update is in, the restart is someone's.
+ _watch?.cancel();
+ setState(() {
+ _started = '';
+ _finishedWell = true;
+ _finished = 'The update is in. Restart $_name to finish it.';
+ });
+ return;
+ }
+ final settled =
+ answered &&
+ !_app.updateAvailable(_id) &&
+ !_app.updateRestarts(_id) &&
+ (!_restarting || _wentDown);
+ if (settled) {
+ _watch?.cancel();
+ setState(() {
+ _started = '';
+ _finishedWell = true;
+ _finished = 'Updated${_versionsNow()}.';
+ });
+ return;
+ }
+ if (DateTime.now().isAfter(deadline)) {
+ _watch?.cancel();
+ setState(() {
+ _started = '';
+ _finishedWell = false;
+ _finished =
+ '$_name has not said the update is in. Pull down to ask it again.';
+ });
+ }
+ } finally {
+ asking = false;
+ }
+ });
+ }
+
+ void _changed() {
+ if (mounted) setState(() {});
+ }
+
+ Future<void> _refresh() async {
+ if (_started.isEmpty) _finished = '';
+ setState(() => _asking = true);
+ await _app.refreshOsStatus(_id, force: true);
+ if (mounted) setState(() => _asking = false);
+ }
+
+ Future<void> _update() async {
+ final restarts = _app.updateRestarts(_id);
+ final encrypted = _app.harnessOsComputers[_id]?.encrypted ?? false;
+ final hotspot = _app.harnessOsComputers[_id]?.hotspot ?? 'Harness-…';
+ final parts = _app.osParts(_id);
+ // A computer that names its parts takes the restart with the update; an older one leaves it to
+ // someone at the computer.
+ final restartsItself = parts.isNotEmpty;
+ if (restarts) {
+ final confirmed = await confirmPhoneAction(
+ context,
+ icon: LucideIcons.rotateCw300,
+ title: 'Update and restart $_name?',
+ message: [
+ restartsItself
+ ? 'The new Harness OS needs a restart: $_name restarts by itself once it is in.'
+ : 'The new Harness OS needs a restart: restart $_name when it is in.',
+ 'Harnesses running there stop, and start again after the restart.',
+ if (encrypted)
+ 'After the restart it waits for its password: unlock it from this phone near it, on its Wi-Fi "$hotspot".',
+ ].join(' '),
+ confirmLabel: 'Update',
+ );
+ if (!confirmed || !mounted) return;
+ }
+ setState(() => _starting = true);
+ final reply = await _app.osDevice(_id, {
+ 'action': 'update',
+ if (restarts) 'reboot': true,
+ });
+ if (!mounted) return;
+ setState(() => _starting = false);
+ if (reply['started'] == true) {
+ setState(() {
+ _restarting = restarts && restartsItself;
+ _systemUpdate = restarts;
+ _manualRestart = restarts && !restartsItself;
+ _wentDown = false;
+ _finished = '';
+ _started = !restarts
+ ? 'Updating hn and the CLI… Its harnesses keep running.'
+ : restartsItself
+ ? 'Updating Harness OS… $_name restarts once it is in.'
+ : 'Updating… Restart $_name when it says so, to finish.';
+ });
+ _follow(encrypted: encrypted);
+ } else {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ content: Text(
+ reply['error'] == 'BUSY'
+ ? '$_name is already updating.'
+ : 'Could not start the update. Try again.',
+ ),
+ ),
+ );
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final parts = _app.osParts(_id);
+ final available = _app.updateAvailable(_id);
+ final restartRequired =
+ (_app.osStatus[_id]?['update'] as Map?)?['restartRequired'] == true;
+ final computer = _app.harnessOsComputers[_id];
+ // Gone down for its restart, or offline: what it last said, nothing to start.
+ final online = !(_restarting && _wentDown) && _isOnline();
+ Text say(String text) => Text(text, style: tty.style(color: tty.dim));
+
+ SettingsRow row(String key, String title) {
+ final part = parts[key];
+ final runningFull = part?['running'] as String?;
+ final nextFull = part?['next'] as String?;
+ final running = shortVersion(runningFull);
+ // hn and the CLI come as one runtime: one of them new marks both waiting, so a part whose
+ // waiting version is the one it runs has nothing new.
+ // The OS only for a newer release, never a later build of the one it runs.
+ final waiting = key == 'os'
+ ? _app.osNewRelease(_id)
+ : part?['available'] == true &&
+ (nextFull == null || nextFull != runningFull);
+ final next = shortVersion(nextFull);
+ return SettingsRow(
+ key: ValueKey('version-$key'),
+ title: title,
+ value: waiting ? null : running ?? '—',
+ // The dot: a new one waits.
+ trailing: waiting
+ ? Text(
+ '● ${next ?? 'new version'}',
+ style: tty.style(color: tty.green, size: TtySize.meta),
+ )
+ : null,
+ detail: waiting && running != null ? 'now $running' : null,
+ );
+ }
+
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: RefreshIndicator(
+ onRefresh: _refresh,
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom + 24,
+ ),
+ children: [
+ const TtyText(
+ 'Version',
+ size: TtySize.display,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ say('What $_name runs.'),
+ const SizedBox(height: 12),
+ if (_asking && _app.osStatus[_id] == null)
+ const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ else if (parts.isEmpty)
+ say(
+ available
+ ? 'A new version is ready.'
+ : 'Up to date. This version of $_name does not name each part.',
+ )
+ else
+ SettingsGroup(
+ children: [
+ row('os', 'Harness OS'),
+ row('hn', 'hn'),
+ row('cli', 'CLI'),
+ ],
+ ),
+ const SizedBox(height: 12),
+ if (restartRequired &&
+ _started.isEmpty &&
+ _finished.isEmpty)
+ say(
+ 'An update is in. $_name finishes it when it restarts.',
+ ),
+ if (_started.isNotEmpty)
+ Row(
+ children: [
+ const SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ _started,
+ key: const Key('version-started'),
+ style: tty.style(color: tty.text),
+ ),
+ ),
+ ],
+ ),
+ if (_finished.isNotEmpty)
+ Text(
+ _finished,
+ key: const Key('version-finished'),
+ style: tty.style(
+ color: _finishedWell ? tty.green : tty.red,
+ ),
+ ),
+ const SizedBox(height: 20),
+ // Restarted and locked, or offline: nothing to update until it is back. An
+ // encrypted one is unlocked from here.
+ if (online && _started.isEmpty)
+ TtyPrimaryButton(
+ key: const Key('version-update'),
+ label: restartRequired && !available
+ ? 'Restart to finish'
+ : _app.updateRestarts(_id)
+ ? 'Update and restart'
+ : available
+ ? 'Update'
+ : 'Up to date',
+ busy: _starting,
+ busyLabel: 'Starting…',
+ onPressed: available || restartRequired
+ ? () => unawaited(_update())
+ : null,
+ ),
+ if (!online &&
+ _started.isEmpty &&
+ computer != null &&
+ computer.encrypted)
+ TtyPrimaryButton(
+ key: const Key('version-unlock'),
+ label: 'Unlock…',
+ onPressed: () => unawaited(_unlock(computer.hotspot)),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/first_task_suggestion.dart b/mobile/lib/phone/first_task_suggestion.dart
new file mode 100644
index 000000000..fb2bb32ba
--- /dev/null
+++ b/mobile/lib/phone/first_task_suggestion.dart
@@ -0,0 +1,112 @@
+import 'package:flutter/material.dart';
+
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// The same first-task capsule in New Harness and the first session.
+class FirstTaskSuggestion extends StatelessWidget {
+ const FirstTaskSuggestion({
+ super.key,
+ required this.text,
+ required this.onTap,
+ });
+ final String text;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ enabled: onTap != null,
+ label: text,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Container(
+ constraints: const BoxConstraints(minHeight: 36),
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(18),
+ border: Border.all(color: tty.dim),
+ ),
+ child: TtyText(text, size: TtySize.meta, color: tty.text),
+ ),
+ ),
+ );
+ }
+}
+
+/// The first session's one suggestion: the task in a capsule with a visible Send beside it
+/// (owner, 2026-10-22). Send is disabled ([onSend] null) while the session takes no input.
+class FirstSessionSuggestion extends StatelessWidget {
+ const FirstSessionSuggestion({
+ super.key,
+ required this.text,
+ required this.onSend,
+ });
+
+ final String text;
+ final VoidCallback? onSend;
+
+ static const sendKey = ValueKey('first-session-send');
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final enabled = onSend != null;
+ return Container(
+ constraints: const BoxConstraints(minHeight: 44),
+ padding: const EdgeInsets.only(left: 14, top: 4, right: 4, bottom: 4),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(22),
+ border: Border.all(color: tty.dim),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Text(
+ text,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(size: TtySize.meta, color: tty.text),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Semantics(
+ button: true,
+ enabled: enabled,
+ label: 'Send',
+ excludeSemantics: true,
+ child: GestureDetector(
+ key: sendKey,
+ behavior: HitTestBehavior.opaque,
+ onTap: onSend,
+ child: Container(
+ constraints: const BoxConstraints(minHeight: 36, minWidth: 64),
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: enabled ? tty.green : tty.selected,
+ borderRadius: BorderRadius.circular(18),
+ ),
+ child: Text(
+ 'Send',
+ style: tty.style(
+ size: TtySize.meta,
+ weight: FontWeight.w600,
+ color: enabled ? tty.onFill(tty.theme.black) : tty.faint,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/machine_actions.dart b/mobile/lib/phone/machine_actions.dart
index 286694763..26b0007a2 100644
--- a/mobile/lib/phone/machine_actions.dart
+++ b/mobile/lib/phone/machine_actions.dart
@@ -8,6 +8,9 @@ import 'package:harness_mobile/widgets/rename_agent_dialog.dart'
show showMachineRenameDialog;
import 'change_wifi_page.dart';
+import 'computer_password_page.dart';
+import 'computer_ssh_page.dart';
+import 'computer_version_page.dart';
import 'link_page.dart';
import 'phone_navigation.dart';
import 'phone_sheet.dart';
@@ -15,6 +18,7 @@ import 'phone_status.dart';
import 'remove_machine.dart';
import 'tty.dart';
import 'unlink_machine.dart';
+import 'unlock_computer_page.dart';
/// The Wi-Fi a Harness OS computer is on, as it last said.
String? _ssidOf(AppNotifier notifier, String machineId) {
@@ -22,33 +26,42 @@ String? _ssidOf(AppNotifier notifier, String machineId) {
return wifi is Map ? wifi['ssid'] as String? : null;
}
-/// Update ▸ a Harness OS computer updates itself (`harness update`, the same as Super+u there). It
-/// restarts its daemon on the way, so it reads offline for a moment and comes back on the new version.
-Future<void> updateComputer(
+/// Sign out ▸ a Harness OS computer signed out of this account, for another one to set it up
+/// (CLI osDevice.ts `sign_out`, os/setup.py `sign_out`): it forgets its Wi-Fi and opens its own
+/// hotspot. Its harnesses, projects and files stay — the same computer, on whichever account signs
+/// it in next. Asked first: it is out of reach of this phone until it is set up again.
+Future<void> signOutComputer(
BuildContext context,
AppNotifier notifier,
String machineId,
) async {
- final messenger = ScaffoldMessenger.maybeOf(context);
final name =
notifier.stateOf(machineId)?.machine.displayName ?? 'The computer';
- final reply = await notifier.osDevice(machineId, {'action': 'update'});
- final String said;
- if (reply['started'] == true) {
- said =
- '$name is updating. It restarts by itself and comes back in a minute or two.';
- notifier.osStatus.remove(machineId);
- // Asked again once it is back on the new version.
- Timer(
- const Duration(minutes: 2),
- () => unawaited(notifier.refreshOsStatus(machineId, force: true)),
- );
- } else if (reply['error'] == 'BUSY') {
- said = '$name is already updating.';
- } else {
- said = 'Could not start the update. Try again.';
- }
- messenger?.showSnackBar(SnackBar(content: Text(said)));
+ final hotspot =
+ notifier.harnessOsComputers[machineId]?.hotspot ?? 'Harness-…';
+ final confirmed = await confirmPhoneAction(
+ context,
+ icon: LucideIcons.logOut300,
+ title: 'Sign out $name?',
+ message:
+ 'It signs out of this account and forgets its Wi-Fi, then opens its own Wi-Fi "$hotspot" '
+ 'to be set up again — with Set up a device, on this account or another. Its harnesses, '
+ 'projects and files stay on it.',
+ confirmLabel: 'Sign out',
+ );
+ if (!confirmed || !context.mounted) return;
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final reply = await notifier.osDevice(machineId, {'action': 'sign_out'});
+ if (reply['started'] == true) notifier.forgetHarnessOs(machineId);
+ messenger?.showSnackBar(
+ SnackBar(
+ content: Text(
+ reply['started'] == true
+ ? '$name is signing out. Set it up again from Set up a device, near it.'
+ : 'Could not reach $name. Try again.',
+ ),
+ ),
+ );
}
/// The sheet of what can be done TO a computer — Settings ▸ Computers.
@@ -96,11 +109,34 @@ void openMachineActions(
onTap: () => unawaited(confirmRemoveMachine(context, notifier, machineId)),
);
+ // An encrypted Harness OS computer reads offline after a restart: it waits for its password, on
+ // its own Wi-Fi, for a phone near it.
+ final harnessOs = notifier.harnessOsComputers[machineId];
final List<PhoneSheetAction> actions;
final List<PhoneSheetAction> destructive;
switch (status) {
case PhoneMachineStatus.offline:
- actions = [tryAgain, rename];
+ actions = [
+ if (harnessOs != null && harnessOs.encrypted)
+ PhoneSheetAction(
+ icon: LucideIcons.lockOpen300,
+ label: 'Unlock…',
+ value: harnessOs.hotspot,
+ chevron: true,
+ enabled: !removing,
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (_) => UnlockComputerPage(
+ notifier: notifier,
+ machineId: machineId,
+ hotspotName: harnessOs.hotspot,
+ ),
+ ),
+ ),
+ ),
+ tryAgain,
+ rename,
+ ];
destructive = [remove];
case PhoneMachineStatus.needsPassword:
actions = [
@@ -134,17 +170,23 @@ void openMachineActions(
if (notifier.runsHarnessOs(machineId)) ...[
PhoneSheetAction(
icon: LucideIcons.download300,
- label: 'Update',
- // The dot: a new version is waiting.
+ label: 'Version',
+ // The dot: a new version is waiting; its Update is on the page.
value: notifier.updateAvailable(machineId)
? '● new version'
: 'up to date',
valueColor: notifier.updateAvailable(machineId)
? Tty.of(context).green
: null,
- enabled: notifier.updateAvailable(machineId),
- onTap: () =>
- unawaited(updateComputer(context, notifier, machineId)),
+ chevron: true,
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (_) => ComputerVersionPage(
+ notifier: notifier,
+ machineId: machineId,
+ ),
+ ),
+ ),
),
PhoneSheetAction(
icon: LucideIcons.wifi300,
@@ -157,9 +199,45 @@ void openMachineActions(
),
),
),
+ if (notifier.osFeature(machineId, 'password'))
+ PhoneSheetAction(
+ icon: LucideIcons.keyRound300,
+ label: 'Change password…',
+ chevron: true,
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (_) => ComputerPasswordPage(
+ notifier: notifier,
+ machineId: machineId,
+ ),
+ ),
+ ),
+ ),
+ if (notifier.osFeature(machineId, 'ssh'))
+ PhoneSheetAction(
+ icon: LucideIcons.terminal300,
+ label: 'SSH',
+ chevron: true,
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (_) =>
+ ComputerSshPage(notifier: notifier, machineId: machineId),
+ ),
+ ),
+ ),
],
];
destructive = [
+ if (notifier.runsHarnessOs(machineId) &&
+ notifier.osFeature(machineId, 'sign_out'))
+ PhoneSheetAction(
+ icon: LucideIcons.logOut300,
+ label: 'Sign out…',
+ destructive: true,
+ enabled: !removing,
+ onTap: () =>
+ unawaited(signOutComputer(context, notifier, machineId)),
+ ),
// No confirmation, the same as before: this sheet is the step between the tap and the
// unlink. Removing from the account asks, because it reaches every device.
PhoneSheetAction(
diff --git a/mobile/lib/phone/new_agent_draft.dart b/mobile/lib/phone/new_agent_draft.dart
index 11e6a7ba7..d6b379ae0 100644
--- a/mobile/lib/phone/new_agent_draft.dart
+++ b/mobile/lib/phone/new_agent_draft.dart
@@ -22,6 +22,7 @@ class NewAgentDraft {
const NewAgentDraft({
required this.machineId,
required this.engine,
+ this.engineChosen = true,
required this.permissionMode,
this.folder,
this.exactFolder,
@@ -43,6 +44,9 @@ class NewAgentDraft {
final String machineId;
final String? engine;
+
+ /// Whether [engine] was picked on the form, not just the one it opened on.
+ final bool engineChosen;
final String permissionMode;
/// A folder that exists, or ([project]) one the machine is to make. Exactly one is ever set —
diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dart
index 3ca6ebedf..4ff70be34 100644
--- a/mobile/lib/phone/new_agent_page.dart
+++ b/mobile/lib/phone/new_agent_page.dart
@@ -5,6 +5,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/core/codex_profiles.dart';
import 'package:harness_mobile/core/first_task.dart';
+import 'package:harness_mobile/core/first_engine.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/core/permission_modes.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -18,6 +19,7 @@ import 'package:harness_mobile/widgets/remote_folder_picker.dart';
import '../demo/sample_mode.dart' show SampleMode;
import 'agent_index.dart';
+import 'first_task_suggestion.dart';
import 'branch_picker_sheet.dart';
import 'phone_navigation.dart';
import 'new_agent_attachments.dart';
@@ -98,8 +100,10 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// "New project", or the repository's name.
String? _projectLabel;
- /// Claude until somebody picks another — the engine most agents are started with.
- String? _engine = 'claude';
+ /// What the form opens on until somebody picks another: [_defaultEngine], read again whenever
+ /// this computer's engines arrive or the computer changes ([_adoptDefaultEngine]). OpenCode is the
+ /// answer before the computer has said anything.
+ String? _engine = 'opencode';
/// A plain shell is chosen rather than an agent — the desktop's `isTerminal`.
///
@@ -184,6 +188,12 @@ class _NewAgentPageState extends State<NewAgentPage> {
void initState() {
super.initState();
_restoreDraft();
+ if (!_engineChosen) _engine = _defaultEngine();
+ // The last agent started from this phone, the desktop's `agentPreference`: read from disk once,
+ // and [_engine] follows it if it lands before anybody has picked.
+ unawaited(
+ widget.notifier.agentPreference.load().then((_) => _adoptDefaultEngine()),
+ );
// After the first frame, not during it: `probeEngines` can notify synchronously, and a notify
// while this page is still being mounted marks the listeners above it dirty mid-build — the
// "setState() called during build" assertion.
@@ -197,23 +207,44 @@ class _NewAgentPageState extends State<NewAgentPage> {
if (mounted) setState(() {});
}),
);
- // The last agent started from this phone, the desktop's `agentPreference`. A draft being
- // restored keeps its own.
- if (newAgentDraft == null) {
- final preference = widget.notifier.agentPreference;
- unawaited(
- preference.load().then((_) {
- final remembered = preference.value;
- if (!mounted || remembered == null || _engineChosen) return;
- setState(() => _engine = remembered);
- }),
- );
- }
}
- /// Whether the engine was picked on this page — a remembered one arriving late must not undo it.
+ /// Whether the engine was picked on this page. A pick is never undone: not by a remembered agent
+ /// arriving late, nor by the computer's engines, nor by moving to another computer.
bool _engineChosen = false;
+ /// What the desktop's New Harness opens on: the agent last started from this phone while this
+ /// computer can still run it, otherwise [firstEngine] — Claude Code or Codex when installed and
+ /// signed in there, else OpenCode.
+ String _defaultEngine() {
+ final remembered = widget.notifier.agentPreference.value;
+ if (remembered != null && _rememberedUsable(remembered)) return remembered;
+ return firstEngine(_machine?.engines);
+ }
+
+ /// Whether this computer can run [id]: installed, and signed in where it reports that. A computer
+ /// that has not answered yet, or an older one that reports no sign-in at all (null), has not said
+ /// "no" — it is not treated as signed out.
+ bool _rememberedUsable(String id) {
+ if (isTerminalEngine(id)) return true;
+ final engines = _machine?.engines;
+ if (engines == null || !engines.loaded) return true;
+ final engine = engines[id];
+ return engine != null && engine.installed && engine.signedIn != false;
+ }
+
+ /// Opens on [_defaultEngine] while nothing was picked. Run when the computer's engines or the
+ /// remembered agent arrive and when the computer changes — never from [build].
+ void _adoptDefaultEngine() {
+ if (!mounted || _engineChosen) return;
+ final next = _defaultEngine();
+ if (next == _engine) return;
+ setState(() {
+ _permissionMode = kDefaultPermissionMode;
+ _engine = next;
+ });
+ }
+
@override
void dispose() {
_holdCheck?.cancel();
@@ -322,6 +353,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
}
_machineId = draft.machineId;
_engine = draft.engine;
+ _engineChosen = draft.engineChosen;
_permissionMode = draft.permissionMode;
_folder = draft.folder;
_exactFolder = draft.exactFolder;
@@ -354,6 +386,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
newAgentDraft = NewAgentDraft(
machineId: _machineId,
engine: _engine,
+ engineChosen: _engineChosen,
permissionMode: _permissionMode,
folder: _folder,
exactFolder: _exactFolder,
@@ -378,7 +411,9 @@ class _NewAgentPageState extends State<NewAgentPage> {
// Which engines this machine actually has. Best effort: an unanswered probe
// leaves the list to the engines its own agents are already running, and a
// machine with neither still gets the browse-and-create path.
- unawaited(widget.notifier.probeEngines(_machineId));
+ unawaited(
+ widget.notifier.probeEngines(_machineId).then((_) => _adoptDefaultEngine()),
+ );
unawaited(_loadCodexProfiles());
}
@@ -415,6 +450,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
_model = null;
_error = null;
});
+ _adoptDefaultEngine();
_askMachine();
}
@@ -1406,12 +1442,8 @@ class _NewAgentPageState extends State<NewAgentPage> {
spacing: 8,
runSpacing: 8,
children: [
- for (final idea in const [
- 'Explain this project to me',
- 'Find a bug and fix it',
- 'Run the tests',
- ])
- _Suggestion(
+ for (final idea in firstTaskIdeas)
+ FirstTaskSuggestion(
text: idea,
onTap: () => setState(() {
_task.value = TextEditingValue(
@@ -1735,15 +1767,16 @@ class _NewAgentPageState extends State<NewAgentPage> {
kTerminalEngine,
};
final ordered = [
+ ?_engine,
for (final id in recent)
- if (ids.contains(id)) id,
- ...(ids
- .where((id) => !recent.contains(id) && !isTerminalEngine(id))
- .toList()
- ..sort((a, b) => _engineName(a).compareTo(_engineName(b)))),
+ if (ids.contains(id) && id != _engine) id,
+ ...ids.where(
+ (id) => id != _engine && !recent.contains(id) && !isTerminalEngine(id),
+ ),
// After every agent, as the desktop lists it: a plain shell, for when none of them is wanted.
// Among the recents instead once it has been started here, as any agent is.
- if (!recent.contains(kTerminalEngine)) kTerminalEngine,
+ if (_engine != kTerminalEngine && !recent.contains(kTerminalEngine))
+ kTerminalEngine,
];
final picked = await showNewAgentChooser<String>(
context,
@@ -2199,34 +2232,3 @@ class _Silent implements Listenable {
@override
void removeListener(VoidCallback listener) {}
}
-
-/// A first task to tap — fills the task field.
-class _Suggestion extends StatelessWidget {
- const _Suggestion({required this.text, required this.onTap});
-
- final String text;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- final tty = Tty.of(context);
- return Semantics(
- button: true,
- label: text,
- excludeSemantics: true,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onTap,
- child: Container(
- constraints: const BoxConstraints(minHeight: 36),
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(18),
- border: Border.all(color: tty.dim),
- ),
- child: TtyText(text, size: TtySize.meta, color: tty.text),
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index fca65f398..17c2c9af7 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -22,6 +22,8 @@ import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/core/models.dart'
show Agent, AgentProject, ConnectionStatus;
+import 'package:harness_mobile/core/first_task.dart';
+import 'package:harness_mobile/terminal/terminal_prompt_zone.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -44,6 +46,8 @@ import 'package:harness_mobile/widgets/rename_agent_dialog.dart';
import 'package:harness_mobile/widgets/terminal_panel.dart';
import 'agent_model_sections.dart';
+import 'first_task_suggestion.dart';
+import 'welcome/onboarding_copy.dart';
import 'agent_model_sheet.dart';
import 'daemon_chip.dart';
import 'daemon_scope.dart';
@@ -158,6 +162,21 @@ bool _keyboardIsUp = false;
/// tracks the truth again as it always did.
bool _keyboardDismissing = false;
+/// The onboarding hand-over whose first session has had its keyboard raised — once, across every page
+/// a wrapping pager mounts for that agent: each would otherwise raise it again when swiped to.
+({String machineId, String agentId, String text})? _firstSessionRaisedFor;
+
+/// Desktop's starter as the first session's OpenCode box was first read, and the hand-over it was
+/// read under — see `_TerminalPageState._firstTask`.
+({String machineId, String agentId, String text})? _starterFor;
+String? _starter;
+
+/// A keyboard asked for again: whatever was putting one away is over, and the inset's ticks are the
+/// truth again. Asked for while the last one still slid down, the inset turns back before reaching
+/// zero, the hold-off of [dismissKeyboardForSwipe] never ended, and [_keyboardIsUp] read false
+/// under a keyboard that was up.
+void _keyboardWanted() => _keyboardDismissing = false;
+
/// Forgets what the keyboard did during the last run of terminal pages.
///
/// Called when a pager opens. A pager popped with the keyboard up is disposed
@@ -488,6 +507,7 @@ class _TerminalPageState extends State<TerminalPage>
// The keyboard has stopped moving, so whether it is up is now a fact: a
// question read while it moved is decided here. See [_raiseForQuestion].
_raiseForQuestion();
+ _raiseForFirstSession();
}
/// What the last build read from the notifier — the baseline [_onNotifier]
@@ -593,6 +613,7 @@ class _TerminalPageState extends State<TerminalPage>
});
if (_questionWatcher?.queued == null) _queueRaisedFor = null;
_raiseForQuestion();
+ _raiseForFirstSession();
}
/// The daemon on this phone, cached so a page going can take its report back
@@ -672,7 +693,8 @@ class _TerminalPageState extends State<TerminalPage>
_raiseKeyboardForQuestion();
}
- /// Open the keyboard because an agent is waiting on an answer.
+ /// Open the keyboard because an agent is waiting on an answer — or because the first session has
+ /// just opened over its task ([_raiseForFirstSession]).
///
/// ⚠️ **Not [_raiseKeyboard], and synchronous where that one is not.** That
/// one belongs to a TAP on the terminal, and awaits the mic's transcript to
@@ -696,6 +718,7 @@ class _TerminalPageState extends State<TerminalPage>
if (_keyboardRequested || _ownsInput) return;
// The controls somebody reaches for next are in the header.
_chrome.reveal();
+ _keyboardWanted();
setState(() {
_keyboardRequested = true;
// ⚠️ **The claim is asked for outright, not left to `focused` turning
@@ -786,7 +809,10 @@ class _TerminalPageState extends State<TerminalPage>
final accepts = facts.session?.acceptsInput ?? false;
if (accepts != _acceptedInput) {
_acceptedInput = accepts;
- if (accepts) _raiseForQuestion();
+ if (accepts) {
+ _raiseForQuestion();
+ _raiseForFirstSession();
+ }
}
if (facts == _facts) return;
if (kTypingTrace) typingCount('page.rebuild(facts)');
@@ -801,6 +827,10 @@ class _TerminalPageState extends State<TerminalPage>
_lifecycle =
WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;
widget.notifier.addListener(_onNotifier);
+ // A session already taking input when the page comes ticks nothing to raise from.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _raiseForFirstSession();
+ });
}
@override
@@ -836,6 +866,16 @@ class _TerminalPageState extends State<TerminalPage>
if (_keyboardSettling) setState(() => _keyboardSettling = false);
// Find belongs to the terminal being read: swiped away, it goes, keyboard and all.
if (_find != null) _closeFind(giveKeyboardBack: false, rebuild: false);
+ // A pretend take is this session's task: carried across the swipe, the next page's mic would
+ // send it there.
+ if (widget.voice.pretending && _firstSessionLine() != null) {
+ widget.voice.clear();
+ }
+ }
+ if (!oldWidget.isActive && widget.isActive) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _raiseForFirstSession();
+ });
}
}
@@ -848,6 +888,11 @@ class _TerminalPageState extends State<TerminalPage>
?.session;
if (session?.voiceDeliver == _deliverVoice) session?.voiceDeliver = null;
if (session?.onLineSent == _onLineSent) session?.onLineSent = null;
+ if (session?.voicePretend == _heardInFirstSession) {
+ session?.voicePretend = null;
+ }
+ _stopPromptWait();
+ _stopSentWait();
// Said once: leaving the session spends the onboarding's line too. Not the onboarding's first
// message: a line sent in any other session still answers it ([_onLineSent]), and a sign-out
// ends it cancelled.
@@ -1102,11 +1147,229 @@ class _TerminalPageState extends State<TerminalPage>
}
// The onboarding's one line, until the first send — see [AppNotifier.firstSessionLine].
if (_firstSessionLine() case final line?) {
+ final session = _facts?.session;
+ final task = session == null ? null : _firstTask(session);
+ if (session != null && task != null) {
+ // A take is on: the mic's own face speaks, and the suggestion waits with its line — a line
+ // left over an empty row would point at nothing. Both are back if the take is dropped.
+ if (VoiceLine.shows(widget.voice)) return null;
+ return _FirstSessionSuggestion(
+ line: line,
+ suggestion: task,
+ onSend: session.acceptsInput
+ ? () {
+ // Read at the tap, not at the last frame: a send that landed since has spent the
+ // line, and the button is still on screen until the next frame draws that. The
+ // task too: the prompt as it stands, with whatever was changed in it since.
+ if (_firstSessionLine() == null) return;
+ final now = _firstTask(session);
+ if (now == null) return;
+ unawaited(
+ widget.voice.submitText(
+ now,
+ (text) => _sendFirstTask(session, text),
+ ),
+ );
+ }
+ : null,
+ );
+ }
return _StatusLine(key: const ValueKey('first-session-line'), text: line);
}
return null;
}
+ /// Whether [session] is the first session handing its task over, on the page the onboarding
+ /// opened: a fresh Claude Code or Codex ("Say what to build, or send this:"), or OpenCode with
+ /// Desktop's starter ("Send it, or say anything."). The engines whose prompt the phone can clear
+ /// before it sends ([TerminalSession.sendFirstTask]).
+ bool _firstTaskSession(TerminalSession session) {
+ final line = _firstSessionLine();
+ return (line == OnboardingCopy.micSayWhat ||
+ line == OnboardingCopy.micSendIt) &&
+ const ['claude', 'codex', 'opencode'].contains(session.engineId);
+ }
+
+ /// The first session's task as it stands — what its Send sends, and what its mic is heard as
+ /// ([_heardInFirstSession]): what the prompt holds now — Desktop's starter in OpenCode's box, the
+ /// task [_raiseForFirstSession] typed into Claude Code or Codex, or whatever it was changed to —
+ /// and with an empty prompt the task it opened on. Null outside the first session, and for an
+ /// OpenCode box that has shown no starter.
+ String? _firstTask(TerminalSession session) {
+ if (!_firstTaskSession(session)) return null;
+ final line = widget.notifier.firstSessionLine;
+ final typed = typedPromptText(session.terminal.buffer, session.engineId);
+ if (_firstSessionLine() == OnboardingCopy.micSayWhat) {
+ return typed ?? firstTaskIdeas.first;
+ }
+ // OpenCode's box as first read is Desktop's starter: kept, so a box emptied on the keyboard
+ // still offers it, never a task the screen did not show.
+ if (typed != null && line != _starterFor) {
+ _starterFor = line;
+ _starter = typed;
+ }
+ return typed ?? (line == _starterFor ? _starter : null);
+ }
+
+ /// Sends the first session's task, replacing what its prompt holds — never joined to it
+ /// ([TerminalSession.sendFirstTask]). A prompt holding a paste marker ([holdsPasteMarker]) goes
+ /// by Return as it stands instead: what was pasted is only in the program, and read off the screen
+ /// and typed again it would be the marker, with the paste cleared away.
+ Future<bool> _sendFirstTask(TerminalSession session, String text) async {
+ if (!holdsPasteMarker(text)) return session.sendFirstTask(text);
+ if (!session.acceptsInput) return false;
+ session.terminal.keyInput(TerminalKey.enter);
+ return true;
+ }
+
+ /// What a take in the first session is heard as, read as it starts and as it ends: the task in
+ /// the prompt ([_firstTask]; empty when there is none to send, which is heard as nothing). Null —
+ /// an ordinary recording — once the first send has gone, or while a question is on screen that a
+ /// spoken answer is for ([_deliverVoice] answers it).
+ String? _heardInFirstSession() {
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ if (session == null || !_firstTaskSession(session)) return null;
+ if (_questionOnScreen(session)) return null;
+ return _firstTask(session) ?? '';
+ }
+
+ /// Whether [session]'s screen shows a question its engine asks — read off its terminal now, not
+ /// through [_questionWatcher], which follows a new terminal only on the next build and settles a
+ /// beat after it.
+ static bool _questionOnScreen(TerminalSession session) {
+ final engine = questionEngineOf(session.engineId);
+ return engine != null && readQuestionPane(session.terminal, engine) != null;
+ }
+
+ /// The first session's mic pretends (owner, 2026-10-23) — see [TerminalSession.voicePretend]. Set
+ /// while this page shows that session; [_heardInFirstSession] itself says when a take records after
+ /// all.
+ void _syncPretendVoice(TerminalSession? session) {
+ if (session == null) return;
+ if (_firstTaskSession(session)) {
+ session.voicePretend = _heardInFirstSession;
+ } else if (session.voicePretend == _heardInFirstSession) {
+ session.voicePretend = null;
+ }
+ }
+
+ /// The pane [_raiseForFirstSession] waits on for its prompt, and the listener it waits with.
+ TerminalSession? _promptWaitOn;
+ VoidCallback? _promptWait;
+
+ /// The first session opens with the keyboard up over its task (owner, 2026-10-23): Return sends it
+ /// as it stands, and the words are there to change. A fresh Claude Code or Codex gets the first
+ /// New Harness idea typed into its empty prompt, unsent; OpenCode's starter is Desktop's. Once per
+ /// hand-over ([_firstSessionRaisedFor]): put away, the keyboard stays away, and Send and the mic
+ /// send the same task.
+ ///
+ /// ⚠️ **Not before the cursor is in the prompt** ([cursorInPrompt]). A pane still starting has no
+ /// prompt to type into, and a dialog drawn first — Claude Code's trust prompt, its cursor on an
+ /// answer — is answered where it is drawn, under no keyboard. So the pane is watched until then,
+ /// each change read after it is written: [TerminalSession.outputTicks] moves before the write,
+ /// and a keyframe moves only the session.
+ ///
+ /// Asked as the page first draws, when its session starts taking input ([_onNotifier]), when it
+ /// becomes the page on screen ([didUpdateWidget]), when a question goes ([_onQuestionPane]) and
+ /// when the keyboard stops moving ([_endSettle]).
+ void _raiseForFirstSession() {
+ if (_firstSessionLine() == null || !widget.isActive) return;
+ if (widget.notifier.firstSessionLine == _firstSessionRaisedFor) return;
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ if (session == null || !_firstTaskSession(session)) return;
+ if (!identical(_promptWaitOn, session)) {
+ _stopPromptWait();
+ void soon() => scheduleMicrotask(_tryRaiseForFirstSession);
+ _promptWaitOn = session;
+ _promptWait = soon;
+ session.outputTicks.addListener(soon);
+ session.addListener(soon);
+ }
+ _tryRaiseForFirstSession();
+ }
+
+ void _tryRaiseForFirstSession() {
+ final session = _promptWaitOn;
+ if (!mounted || session == null) return;
+ final line = widget.notifier.firstSessionLine;
+ if (_firstSessionLine() == null ||
+ line == _firstSessionRaisedFor ||
+ !_firstTaskSession(session)) {
+ _stopPromptWait();
+ return;
+ }
+ // Parked, reconnecting, or the keyboard still moving: wait on — the next change asks again.
+ if (!widget.isActive || !session.acceptsInput || _keyboardSettling) return;
+ final buffer = session.terminal.buffer;
+ if (!cursorInPrompt(buffer, session.engineId)) return;
+ _stopPromptWait();
+ _firstSessionRaisedFor = line;
+ if (_firstSessionLine() == OnboardingCopy.micSayWhat &&
+ const ['claude', 'codex'].contains(session.engineId) &&
+ emptyPromptAtCursor(buffer)) {
+ session.terminal.textInput(firstTaskIdeas.first);
+ session.resetInputBuffer();
+ }
+ _raiseKeyboardForQuestion();
+ }
+
+ void _stopPromptWait() {
+ final session = _promptWaitOn;
+ final wait = _promptWait;
+ if (session != null && wait != null) {
+ session.outputTicks.removeListener(wait);
+ session.removeListener(wait);
+ }
+ _promptWaitOn = null;
+ _promptWait = null;
+ }
+
+ /// The pane [_dismissOnceSent] watches, its listener, and how long it watches.
+ TerminalSession? _sentWaitOn;
+ VoidCallback? _sentWait;
+ Timer? _sentDeadline;
+ static const _sentWatch = Duration(seconds: 3);
+
+ /// The first session's task went: the keyboard goes once the prompt has emptied — the task is
+ /// with the harness, and what it does with it is on screen (owner, 2026-10-23). A Return that sent
+ /// nothing — a file picked after `@`, a line broken with `\` — leaves the prompt holding its text
+ /// and the keyboard up. Watched as [_raiseForFirstSession] watches, for [_sentWatch].
+ void _dismissOnceSent(TerminalSession session) {
+ _stopSentWait();
+ void check() {
+ if (!mounted) return _stopSentWait();
+ if (typedPromptText(session.terminal.buffer, session.engineId) != null) {
+ return;
+ }
+ _stopSentWait();
+ _dismissInput();
+ }
+
+ void soon() => scheduleMicrotask(check);
+ _sentWaitOn = session;
+ _sentWait = soon;
+ session.outputTicks.addListener(soon);
+ session.addListener(soon);
+ _sentDeadline = Timer(_sentWatch, _stopSentWait);
+ }
+
+ void _stopSentWait() {
+ final session = _sentWaitOn;
+ final wait = _sentWait;
+ if (session != null && wait != null) {
+ session.outputTicks.removeListener(wait);
+ session.removeListener(wait);
+ }
+ _sentDeadline?.cancel();
+ _sentDeadline = null;
+ _sentWaitOn = null;
+ _sentWait = null;
+ }
+
/// The onboarding's line by the mic, when this page is the session it opened on: "Send it, or say
/// anything." Null on every other page, and once spent.
String? _firstSessionLine() {
@@ -1123,6 +1386,16 @@ class _TerminalPageState extends State<TerminalPage>
bool _spendFirstSessionLine() {
if (_firstSessionLine() == null) return false;
widget.notifier.firstSessionLine = null;
+ // Kept for this hand-over only: a later one for the same agent reads the same.
+ _firstSessionRaisedFor = null;
+ _starterFor = null;
+ _starter = null;
+ // From here a take is a recording again — see [_syncPretendVoice].
+ widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session
+ ?.voicePretend =
+ null;
return true;
}
@@ -1145,7 +1418,12 @@ class _TerminalPageState extends State<TerminalPage>
// only the one it opened: a person signing in again may go straight to a session of their own,
// which read as no first message (1 in 3 on 2026-10-19). Nothing once it has ended.
onboarding.end(ProductFlow.firstMessage, ProductOutcome.ok);
+ final session = _readFacts().session;
+ final firstTask = session != null && _firstTaskSession(session);
if (!_spendFirstSessionLine()) return;
+ // The first session's task is on its way: the keyboard goes once it has gone (owner,
+ // 2026-10-23). Only this once — Return in a session at work keeps it up.
+ if (firstTask) _dismissOnceSent(session);
setState(() {});
}
@@ -1327,7 +1605,10 @@ class _TerminalPageState extends State<TerminalPage>
final session = await _sessionForInput();
if (session == null) return false;
if (_questionWatcher?.view != null) return _answerByVoice(session, text);
- final sent = await session.sendComposerText(text);
+ // The first session's task replaces what its prompt holds, as Send does: never joined to it.
+ final sent = _firstTaskSession(session)
+ ? await _sendFirstTask(session, text)
+ : await session.sendComposerText(text);
// After the send is acknowledged, never before: a tap felt first would be a promise.
if (sent && mounted) HapticFeedback.lightImpact();
return sent;
@@ -1620,6 +1901,7 @@ class _TerminalPageState extends State<TerminalPage>
_find = null;
if (!rebuild) return;
if (back) {
+ _keyboardWanted();
_keyboardRequested = true;
_focusRequest++;
} else {
@@ -1798,6 +2080,7 @@ class _TerminalPageState extends State<TerminalPage>
// would be a keyboard that does nothing. See [_raiseKeyboardForQuestion].
final session = _readFacts().session;
if (session == null || !session.acceptsInput) return;
+ _keyboardWanted();
setState(() {
_keyboardRequested = true;
_focusRequest++;
@@ -1856,6 +2139,7 @@ class _TerminalPageState extends State<TerminalPage>
if (heard.isNotEmpty && session.acceptsInput) {
session.terminal.textInput(heard);
}
+ _keyboardWanted();
setState(() => _keyboardRequested = true);
// The keyboard is on its way and the key bar opens with it. Held from here
// rather than from the first metrics tick, which is a frame too late: see
@@ -1865,8 +2149,13 @@ class _TerminalPageState extends State<TerminalPage>
/// Puts the keyboard away without leaving the page — the `⌄` key on
/// [TerminalKeyBar]. Dropping focus is what closes the input connection.
+ ///
+ /// ⚠️ **Through [dismissKeyboardForSwipe], not a bare `unfocus()`.** The inset is still falling
+ /// for ~250ms after it, [_keyboardIsUp] stays true, and [_shouldFocus] with it: a keyframe that
+ /// lands meanwhile — the harness answering the very line that put the keyboard away — had the
+ /// panel claim it straight back, and the keyboard never went.
void _dismissInput() {
- FocusManager.instance.primaryFocus?.unfocus();
+ dismissKeyboardForSwipe();
if (_keyboardRequested) setState(() => _keyboardRequested = false);
// The same move as [_raiseKeyboard], run backwards. See [_armSettle].
_armSettle();
@@ -2205,6 +2494,7 @@ class _TerminalPageState extends State<TerminalPage>
// While the agent's question is open, a voice take answers it — never a paste and a blind
// Return into the dialog. See [_answerByVoice].
session?.voiceDeliver = _deliverVoice;
+ _syncPretendVoice(session);
// What this page sends: the first send on the phone asks for notifications, and answers the
// onboarding's line by the mic. See [_onLineSent].
session?.onLineSent = _onLineSent;
@@ -2692,16 +2982,22 @@ class _TerminalPageState extends State<TerminalPage>
left: 0,
right: 0,
bottom: _statusBottom - _StatusLine.below,
- child: IgnorePointer(
- child: ListenableBuilder(
- listenable: Listenable.merge([
- widget.voice,
- _barMessage,
- _scrollback,
- ]),
- builder: (context, _) =>
- _statusLine() ?? const SizedBox.shrink(),
- ),
+ child: ListenableBuilder(
+ listenable: Listenable.merge([
+ widget.voice,
+ _barMessage,
+ _scrollback,
+ ?session,
+ ]),
+ builder: (context, _) {
+ final line = _statusLine();
+ if (line == null) return const SizedBox.shrink();
+ // Only the first session's suggestion takes taps; every other line
+ // lies over the terminal and lets them through.
+ return line is _FirstSessionSuggestion
+ ? line
+ : IgnorePointer(child: line);
+ },
),
),
// How loud the take is: a glow behind the mic that swells with the voice.
@@ -4487,6 +4783,43 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
);
}
+/// The first session's line with one suggestion and its Send under it (owner, 2026-10-22). The only
+/// status line that takes taps: [TerminalPage] lets the others through to the terminal.
+class _FirstSessionSuggestion extends StatelessWidget {
+ const _FirstSessionSuggestion({
+ required this.line,
+ required this.suggestion,
+ required this.onSend,
+ });
+
+ final String line;
+ final String suggestion;
+
+ /// Null while the terminal is not taking input: Send shows disabled, and waits.
+ final VoidCallback? onSend;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return ColoredBox(
+ color: tty.ground,
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: _StatusLine.below),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _StatusLine(key: const ValueKey('first-session-line'), text: line),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: FirstSessionSuggestion(text: suggestion, onSend: onSend),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
/// The line above the mic, centred over it with an opaque ground.
/// Its fixed yellow dot uses the same asking colour as Find.
///
diff --git a/mobile/lib/phone/unlock_computer_page.dart b/mobile/lib/phone/unlock_computer_page.dart
new file mode 100644
index 000000000..19c8f123d
--- /dev/null
+++ b/mobile/lib/phone/unlock_computer_page.dart
@@ -0,0 +1,552 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'add_device/add_device_page.dart';
+import 'add_device/setup_hotspot.dart';
+import 'phone_navigation.dart';
+import 'settings_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Computers ▸ an encrypted Harness OS computer that was switched off and on ▸ Unlock: as it starts
+/// it waits for its password and opens its own Wi-Fi, `Harness-XXXX` (os/root/usr/lib/harness-os/
+/// unlock). This phone joins it, checks the password there, and opens the disk:
+///
+/// Unlock — the password alone; it goes back on the Wi-Fi it knows, signed in as it was.
+/// Unlock and change Wi-Fi — its startup's list, a password, sent with the unlock (os/setup.py
+/// `set_up_as_unlocked`, no sign-in: it is signed in already).
+///
+/// Then it shows up online in the account, where this page waits for it.
+class UnlockComputerPage extends StatefulWidget {
+ const UnlockComputerPage({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ required this.hotspotName,
+ this.hotspot,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+
+ /// The Wi-Fi it opens while locked, as its last status said.
+ final String hotspotName;
+ final SetupHotspot? hotspot;
+
+ @override
+ State<UnlockComputerPage> createState() => _UnlockComputerPageState();
+}
+
+enum _Step {
+ start,
+ finding,
+ password,
+ choice,
+ networks,
+ wifiPassword,
+ starting,
+ done,
+}
+
+class _UnlockComputerPageState extends State<UnlockComputerPage> {
+ late final SetupHotspot _hotspot = widget.hotspot ?? SetupHotspot();
+ final _secret = TextEditingController();
+ final _password = TextEditingController();
+
+ _Step _step = _Step.start;
+ bool _busy = false;
+ bool _reveal = false;
+ String _error = '';
+ Timer? _poll;
+
+ /// The computer's password once its startup said it is the right one, for the unlock that follows.
+ String? _checked;
+ List<SetupNetwork> _networks = const [];
+ SetupNetwork? _chosen;
+
+ /// The Wi-Fi sent with the unlock, or null for the one it knows.
+ String? _newWifi;
+
+ /// How long it gets to start, join its Wi-Fi and show up online in the account.
+ static const _comeOnline = Duration(minutes: 3);
+
+ AppNotifier get _app => widget.notifier;
+ String get _name =>
+ _app.stateOf(widget.machineId)?.machine.displayName ?? 'The computer';
+
+ @override
+ void dispose() {
+ _poll?.cancel();
+ unawaited(_hotspot.leave());
+ _secret.dispose();
+ _password.dispose();
+ super.dispose();
+ }
+
+ void _show(_Step step, {String error = ''}) {
+ if (!mounted) return;
+ setState(() {
+ _step = step;
+ _error = error;
+ _busy = false;
+ });
+ }
+
+ // -- onto its hotspot --
+
+ Future<void> _find() async {
+ _show(_Step.finding);
+ setState(() => _busy = true);
+ if (SetupHotspot.joinsByItself) {
+ final joined = await _hotspot.join(name: widget.hotspotName);
+ if (!mounted) return;
+ if (joined.state == 'unavailable') {
+ _show(
+ _Step.start,
+ error:
+ '"${widget.hotspotName}" was not found. Check $_name is on and nearby, '
+ 'and give it a minute to start.',
+ );
+ return;
+ }
+ }
+ // Joined by Android, or by the person in Settings: wait for its page to answer.
+ final deadline = DateTime.now().add(const Duration(minutes: 2));
+ _poll?.cancel();
+ var asking = false;
+ _poll = Timer.periodic(const Duration(seconds: 2), (_) async {
+ if (asking || !mounted || _step != _Step.finding) return;
+ asking = true;
+ try {
+ final info = await _hotspot.info();
+ if (!mounted || _step != _Step.finding) return;
+ if (info == null) {
+ if (DateTime.now().isAfter(deadline)) {
+ _poll?.cancel();
+ _show(
+ _Step.start,
+ error: SetupHotspot.joinsByItself
+ ? 'Could not reach $_name on its Wi-Fi. Try again.'
+ : 'Join "${widget.hotspotName}" in Settings ▸ Wi-Fi, then come back here.',
+ );
+ }
+ return;
+ }
+ _poll?.cancel();
+ if (info['locked'] != true) {
+ // Its own setup page: started already, not waiting for a password.
+ unawaited(_hotspot.leave());
+ _show(
+ _Step.start,
+ error: '$_name is not locked: it is starting or unlocked already.',
+ );
+ return;
+ }
+ _secret.clear();
+ _show(_Step.password);
+ } finally {
+ asking = false;
+ }
+ });
+ }
+
+ // -- its password, checked; nothing opens yet --
+
+ Future<void> _check() async {
+ final secret = _secret.text;
+ if (secret.isEmpty) {
+ _show(_Step.password, error: 'Enter the computer\'s password.');
+ return;
+ }
+ setState(() => _busy = true);
+ final String? why;
+ try {
+ why = await _hotspot.check(secret);
+ } on SetupException catch (e) {
+ _show(_Step.password, error: e.message);
+ return;
+ }
+ if (why != null) {
+ _show(_Step.password, error: why);
+ return;
+ }
+ _checked = secret;
+ _secret.clear();
+ _show(_Step.choice);
+ }
+
+ // -- another Wi-Fi, from its startup's list --
+
+ Future<void> _listNetworks({bool rescan = false}) async {
+ _show(_Step.networks);
+ setState(() => _busy = true);
+ try {
+ final networks = await _hotspot.networks(rescan: rescan);
+ if (!mounted) return;
+ setState(() {
+ _networks = networks;
+ _busy = false;
+ });
+ } on SetupException catch (e) {
+ _show(_Step.networks, error: e.message);
+ }
+ }
+
+ void _choose(SetupNetwork network) {
+ _chosen = network;
+ _password.clear();
+ if (!network.secure) {
+ unawaited(_unlock(wifi: network));
+ return;
+ }
+ _show(_Step.wifiPassword);
+ }
+
+ // -- the unlock --
+
+ Future<void> _unlock({SetupNetwork? wifi}) async {
+ final secret = _checked;
+ if (secret == null) {
+ _show(_Step.password);
+ return;
+ }
+ final password = _password.text;
+ if (wifi != null &&
+ wifi.secure &&
+ (password.length < 8 || password.length > 63)) {
+ _show(
+ _Step.wifiPassword,
+ error: 'A Wi-Fi password has 8 to 63 characters.',
+ );
+ return;
+ }
+ final failedAt = wifi == null ? _Step.choice : _Step.wifiPassword;
+ setState(() => _busy = true);
+ final String? why;
+ try {
+ why = await _hotspot.unlock(
+ secret,
+ setup: wifi == null
+ ? null
+ : {
+ 'ssid': wifi.ssid,
+ if (wifi.secure) 'password': password,
+ 'security': wifi.security,
+ },
+ );
+ } on SetupException catch (e) {
+ _show(failedAt, error: e.message);
+ return;
+ }
+ if (why != null) {
+ _show(failedAt, error: why);
+ return;
+ }
+ _checked = null;
+ _newWifi = wifi?.ssid;
+ await _hotspot.leave();
+ _waitOnline();
+ }
+
+ /// Back on the phone's own Wi-Fi: the computer starts, joins its Wi-Fi and comes online.
+ void _waitOnline() {
+ _show(_Step.starting);
+ final deadline = DateTime.now().add(_comeOnline);
+ var asking = false;
+ _poll?.cancel();
+ _poll = Timer.periodic(const Duration(seconds: 4), (_) async {
+ if (asking || !mounted || _step != _Step.starting) return;
+ asking = true;
+ try {
+ await _app.refreshMachines();
+ } catch (_) {
+ // The phone may still be finding its way back to its own Wi-Fi.
+ } finally {
+ asking = false;
+ }
+ if (!mounted || _step != _Step.starting) return;
+ final machine = _app.machines
+ .where((m) => m.machineId == widget.machineId)
+ .firstOrNull;
+ if (machine?.status == 'running') {
+ _poll?.cancel();
+ unawaited(_app.refreshOsStatus(widget.machineId, force: true));
+ // Nothing left to do here: back where the person came from, told it is online. The page
+ // that opened this one goes on from there (Version finishes its update).
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text('$_name is online.')));
+ Navigator.of(context).maybePop();
+ return;
+ }
+ if (DateTime.now().isAfter(deadline)) {
+ _poll?.cancel();
+ _show(
+ _Step.starting,
+ // Unlocked and still not online: signed out (a sign-out keeps it on the account's list,
+ // offline), or off its Wi-Fi. Either way its hotspot is back for Set up a device.
+ error:
+ '$_name is unlocked but has not come online'
+ '${_newWifi == null ? '' : ' on "$_newWifi"'}. If it was signed out, or its Wi-Fi is '
+ 'wrong, it is waiting on "${widget.hotspotName}" to be set up: use Set up a device.',
+ );
+ }
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Scaffold(
+ backgroundColor: tty.ground,
+ resizeToAvoidBottomInset: false,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom +
+ MediaQuery.viewInsetsOf(context).bottom +
+ 24,
+ ),
+ children: [
+ TtyText(
+ 'Unlock $_name',
+ size: TtySize.display,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 8),
+ if (_error.isNotEmpty) ...[
+ Text(
+ _error,
+ key: const Key('unlock-error'),
+ style: tty.style(color: tty.red),
+ ),
+ const SizedBox(height: 12),
+ ],
+ ..._body(tty),
+ const SizedBox(height: 20),
+ ..._actions(),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _body(Tty tty) {
+ Text say(String text) => Text(text, style: tty.style(color: tty.dim));
+ switch (_step) {
+ case _Step.start:
+ return [
+ say(
+ 'After a restart $_name waits for its password and opens a Wi-Fi named '
+ '"${widget.hotspotName}". Stay near it: this phone joins that Wi-Fi to unlock it.',
+ ),
+ ];
+ case _Step.finding:
+ return [
+ say(
+ SetupHotspot.joinsByItself
+ ? 'Looking for "${widget.hotspotName}"…'
+ : 'Join "${widget.hotspotName}" in Settings ▸ Wi-Fi, then come back here.',
+ ),
+ const SizedBox(height: 16),
+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ ];
+ case _Step.password:
+ return [
+ say('$_name\'s password, the one set when it was installed.'),
+ const SizedBox(height: 8),
+ TtyField(
+ key: const Key('unlock-password'),
+ controller: _secret,
+ hint: 'Computer password',
+ autofocus: true,
+ keyboardType: TextInputType.visiblePassword,
+ obscure: !_reveal,
+ onSubmitted: _busy ? null : () => unawaited(_check()),
+ trailing: [_eye(tty)],
+ ),
+ ];
+ case _Step.choice:
+ return [
+ say(
+ 'That is its password. Unlock it on the Wi-Fi it knows, or give it another Wi-Fi now.',
+ ),
+ ];
+ case _Step.networks:
+ return [
+ say('The Wi-Fi $_name sees.'),
+ const SizedBox(height: 12),
+ if (_busy)
+ const Center(child: CircularProgressIndicator(strokeWidth: 2))
+ else
+ SettingsGroup(
+ children: [
+ for (final network in _networks)
+ SettingsRow(
+ key: ValueKey('unlock-wifi-${network.ssid}'),
+ title: network.ssid,
+ value: network.secure ? 'Locked' : 'Open',
+ detail: network.signal >= 70
+ ? 'Strong signal'
+ : network.signal >= 40
+ ? 'Good signal'
+ : 'Weak signal',
+ onTap: () => _choose(network),
+ ),
+ ],
+ ),
+ ];
+ case _Step.wifiPassword:
+ return [
+ say('The password for "${_chosen?.ssid}". It is case-sensitive.'),
+ const SizedBox(height: 8),
+ TtyField(
+ key: const Key('unlock-wifi-password'),
+ controller: _password,
+ hint: 'Wi-Fi password',
+ autofocus: true,
+ keyboardType: TextInputType.visiblePassword,
+ obscure: !_reveal,
+ maxLength: 63,
+ onSubmitted: _busy ? null : () => unawaited(_unlock(wifi: _chosen)),
+ trailing: [_eye(tty)],
+ ),
+ ];
+ case _Step.starting:
+ return [
+ if (_error.isEmpty) ...[
+ say(
+ _newWifi == null
+ ? 'Unlocked. $_name is starting and going back on its Wi-Fi.'
+ : 'Unlocked. $_name is starting and joining "$_newWifi".',
+ ),
+ const SizedBox(height: 16),
+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),
+ ],
+ ];
+ case _Step.done:
+ return [say('$_name is online.')];
+ }
+ }
+
+ Widget _eye(Tty tty) => AppIconButton(
+ icon: _reveal ? LucideIcons.eyeOff300 : LucideIcons.eye300,
+ size: 20,
+ tooltip: _reveal ? 'Hide password' : 'Show password',
+ color: tty.dim,
+ onPressed: () => setState(() => _reveal = !_reveal),
+ );
+
+ List<Widget> _actions() {
+ switch (_step) {
+ case _Step.start:
+ return [
+ TtyPrimaryButton(
+ key: const Key('unlock-find'),
+ label: 'Find ${widget.hotspotName}',
+ onPressed: () => unawaited(_find()),
+ ),
+ ];
+ case _Step.finding:
+ return const [];
+ case _Step.password:
+ return [
+ TtyPrimaryButton(
+ key: const Key('unlock-check'),
+ label: 'Continue',
+ busy: _busy,
+ busyLabel: 'Checking…',
+ onPressed: () => unawaited(_check()),
+ ),
+ ];
+ case _Step.choice:
+ return [
+ TtyPrimaryButton(
+ key: const Key('unlock-go'),
+ label: 'Unlock',
+ busy: _busy,
+ busyLabel: 'Unlocking…',
+ onPressed: () => unawaited(_unlock()),
+ ),
+ TtyTextButton(
+ key: const Key('unlock-change-wifi'),
+ label: 'Unlock and change Wi-Fi…',
+ onPressed: _busy ? null : () => unawaited(_listNetworks()),
+ ),
+ ];
+ case _Step.networks:
+ return [
+ TtyTextButton(
+ key: const Key('unlock-look-again'),
+ label: 'Look again',
+ onPressed: _busy
+ ? null
+ : () => unawaited(_listNetworks(rescan: true)),
+ ),
+ TtyTextButton(
+ label: 'Keep its Wi-Fi',
+ onPressed: _busy ? null : () => _show(_Step.choice),
+ ),
+ ];
+ case _Step.wifiPassword:
+ return [
+ TtyPrimaryButton(
+ key: const Key('unlock-with-wifi'),
+ label: 'Unlock',
+ busy: _busy,
+ busyLabel: 'Unlocking…',
+ onPressed: () => unawaited(_unlock(wifi: _chosen)),
+ ),
+ TtyTextButton(
+ label: 'Choose another Wi-Fi',
+ onPressed: _busy ? null : () => _show(_Step.networks),
+ ),
+ ];
+ case _Step.starting:
+ return [
+ if (_error.isNotEmpty) ...[
+ TtyPrimaryButton(
+ key: const Key('unlock-set-up'),
+ label: 'Set up a device',
+ onPressed: () => Navigator.of(context).pushReplacement(
+ phoneRoute((_) => AddDevicePage(notifier: _app)),
+ ),
+ ),
+ TtyTextButton(
+ label: 'Unlock again',
+ onPressed: () => _show(_Step.start),
+ ),
+ ],
+ ];
+ case _Step.done:
+ return [
+ TtyPrimaryButton(
+ key: const Key('unlock-done'),
+ label: 'Done',
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ];
+ }
+ }
+}
diff --git a/mobile/lib/phone/voice_input_controller.dart b/mobile/lib/phone/voice_input_controller.dart
index 0464ad4a1..18361bfd9 100644
--- a/mobile/lib/phone/voice_input_controller.dart
+++ b/mobile/lib/phone/voice_input_controller.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:math';
import 'package:flutter/foundation.dart';
@@ -111,6 +112,16 @@ class VoiceInputController extends ChangeNotifier {
/// [clear], where words arriving late would bring back what was dropped.
int _take = 0;
+ /// The take in progress is a pretend one ([startListening]'s `pretend`), and this is what it will
+ /// be heard as.
+ String? Function()? _pretending;
+ final ValueNotifier<double> _pretendLevel = ValueNotifier(0);
+ Timer? _pretendMeter;
+ final Random _pretendRandom = Random(7);
+
+ /// Whether the take in progress is a pretend one: listening, with no microphone open.
+ bool get pretending => _pretending != null;
+
bool get isSending => _isSending;
VoiceInputStatus get status => _status;
String get transcript => _heard;
@@ -119,10 +130,18 @@ class VoiceInputController extends ChangeNotifier {
/// How loud the microphone is right now, 0…1 — what the waveform beside the
/// mic draws while a take is recorded. Silence from a recorder that has no
/// meter (see [VoiceLevelMeter]).
- ValueListenable<double> get level => switch (_recorder) {
- final VoiceLevelMeter meter => meter.level,
- _ => _silence,
- };
+ ///
+ /// ⚠️ **One object for the controller's life.** A widget adds its listener here as it mounts and
+ /// takes it off as it goes, and the take may have changed from recorded to pretend in between:
+ /// handing out whichever meter was live left the listener on the other.
+ late final ValueListenable<double> level = _TakeLevel(
+ recorded: switch (_recorder) {
+ final VoiceLevelMeter meter => meter.level,
+ _ => _silence,
+ },
+ pretended: _pretendLevel,
+ pretending: () => _pretending != null,
+ );
static final ValueListenable<double> _silence = ValueNotifier(0);
@@ -153,13 +172,25 @@ class VoiceInputController extends ChangeNotifier {
_setStatus(VoiceInputStatus.idle);
}
- Future<void> startListening() async {
+ /// Starts a take.
+ ///
+ /// With [pretend], and while it has something to say, the take opens no microphone and asks for no
+ /// permission: it shows as listening, its meter moving as if somebody spoke, and when it ends it is
+ /// heard as what [pretend] says then. The first session's mic (owner, 2026-10-23): speaking there
+ /// sends the task in the prompt, whatever was said — a microphone permission prompt in the middle
+ /// of the onboarding costs it more than the words are worth. [pretend] saying null — the first
+ /// send has gone, or a question is open — makes it an ordinary recording.
+ Future<void> startListening({String? Function()? pretend}) async {
if (_isSending || _disposed) return;
if (_status != VoiceInputStatus.idle &&
_status != VoiceInputStatus.unavailable) {
return;
}
final take = ++_take;
+ if (pretend != null && pretend() != null) {
+ _startPretending(pretend);
+ return;
+ }
_setStatus(VoiceInputStatus.starting);
if (!await _micAllowed()) {
if (take != _take) return;
@@ -210,9 +241,12 @@ class VoiceInputController extends ChangeNotifier {
/// So the hold is a fact of its own, held here, and the release is applied to
/// whatever state the start has reached by then — including a start that has
/// not finished yet, which [_holdReleased] makes it check for itself.
- Future<void> startHold(Future<bool> Function(String text) deliver) async {
+ Future<void> startHold(
+ Future<bool> Function(String text) deliver, {
+ String? Function()? pretend,
+ }) async {
_holdReleased = false;
- await startListening();
+ await startListening(pretend: pretend);
// Let go while the microphone was still opening: the take that just became
// live has no thumb on it, so it is ended and sent from here — the release
// could not do it itself, because at that moment there was no take to end.
@@ -251,6 +285,21 @@ class VoiceInputController extends ChangeNotifier {
/// its way to `listening`. See [startHold].
bool _holdReleased = false;
+ /// A first-task chip takes the same send and feedback path as spoken words.
+ /// Never replaces an unfinished voice take.
+ Future<void> submitText(
+ String text,
+ Future<bool> Function(String) deliver,
+ ) async {
+ if (_isSending ||
+ _status != VoiceInputStatus.idle ||
+ transcript.isNotEmpty) {
+ return;
+ }
+ _heard = text;
+ await submit(deliver);
+ }
+
/// Sends everything heard, and empties the transcript once it is sent — kept
/// when delivery fails, so nothing said has to be said twice.
///
@@ -296,8 +345,15 @@ class VoiceInputController extends ChangeNotifier {
///
/// Nothing while a send is on its way: those words are already the message,
/// and handing them to the keyboard too would put them in the prompt twice.
+ ///
+ /// Nothing for a pretend take either: nothing was said in it, and what it stands for is the
+ /// prompt's own text, already there.
Future<String> takeTranscript() async {
if (_isSending) return '';
+ if (_pretending != null) {
+ clear();
+ return '';
+ }
if (_status == VoiceInputStatus.listening) await _transcribeTake();
final text = transcript;
clear();
@@ -308,6 +364,7 @@ class VoiceInputController extends ChangeNotifier {
void dispose() {
_abandonTake();
_noticeLimit?.cancel();
+ _pretendLevel.dispose();
_disposed = true;
unawaited(_recorder.dispose());
super.dispose();
@@ -318,6 +375,30 @@ class VoiceInputController extends ChangeNotifier {
final take = _take;
_takeLimit?.cancel();
_takeClock?.stop();
+ if (_pretending case final heard?) {
+ final length = _takeClock?.elapsed ?? Duration.zero;
+ _stopPretending();
+ // A brushed button, as with a recording: nothing to send.
+ if (length < minTake) {
+ _setStatus(VoiceInputStatus.idle);
+ return _Take.tap;
+ }
+ String words;
+ try {
+ words = (heard() ?? '').trim();
+ } catch (error) {
+ appLog.warn('voice', 'pretend take unread', error: error);
+ words = '';
+ }
+ // The prompt as it stands, and nothing held from an earlier send that failed: that was the same
+ // task, and joined it would be sent twice.
+ _heard = words;
+ _setStatus(
+ VoiceInputStatus.idle,
+ notice: words.isEmpty ? VoiceNotice.nothingHeard : null,
+ );
+ return words.isEmpty ? _Take.failed : _Take.heard;
+ }
_setStatus(VoiceInputStatus.transcribing);
try {
final recording = await _recorder.stop();
@@ -371,10 +452,37 @@ class VoiceInputController extends ChangeNotifier {
}
}
+ /// A pretend take: listening at once, with no microphone to open, and a meter shaped like speech —
+ /// a syllable's rise and fall, with some breath in it.
+ void _startPretending(String? Function() heard) {
+ _pretending = heard;
+ var beats = 0;
+ _pretendMeter = Timer.periodic(const Duration(milliseconds: 90), (_) {
+ beats++;
+ final syllable = (sin(beats * 0.9) + 1) / 2;
+ _pretendLevel.value =
+ 0.15 + 0.6 * syllable * (0.6 + 0.4 * _pretendRandom.nextDouble());
+ });
+ _takeLimit = Timer(maxTake, () => unawaited(stopListening()));
+ _takeClock = Stopwatch()..start();
+ _setStatus(VoiceInputStatus.listening);
+ }
+
+ void _stopPretending() {
+ _pretending = null;
+ _pretendMeter?.cancel();
+ _pretendMeter = null;
+ _pretendLevel.value = 0;
+ }
+
void _abandonTake() {
_take++;
_takeLimit?.cancel();
_takeClock?.stop();
+ if (_pretending != null) {
+ _stopPretending();
+ return;
+ }
if (_status == VoiceInputStatus.starting ||
_status == VoiceInputStatus.listening) {
unawaited(_recorder.cancel());
@@ -422,6 +530,35 @@ class VoiceInputController extends ChangeNotifier {
}
}
+/// [VoiceInputController.level]: the recorder's meter, or the pretend one while a pretend take is on —
+/// one listenable whichever it is, so a listener added and taken off lands on the same two.
+class _TakeLevel implements ValueListenable<double> {
+ _TakeLevel({
+ required this.recorded,
+ required this.pretended,
+ required this.pretending,
+ });
+
+ final ValueListenable<double> recorded;
+ final ValueListenable<double> pretended;
+ final bool Function() pretending;
+
+ @override
+ double get value => pretending() ? pretended.value : recorded.value;
+
+ @override
+ void addListener(VoidCallback listener) {
+ recorded.addListener(listener);
+ pretended.addListener(listener);
+ }
+
+ @override
+ void removeListener(VoidCallback listener) {
+ recorded.removeListener(listener);
+ pretended.removeListener(listener);
+ }
+}
+
String _joinWords(String first, String second) =>
[first.trim(), second.trim()].where((part) => part.isNotEmpty).join(' ');
diff --git a/mobile/lib/phone/voice_mic_action.dart b/mobile/lib/phone/voice_mic_action.dart
index 6c127bc17..21e186306 100644
--- a/mobile/lib/phone/voice_mic_action.dart
+++ b/mobile/lib/phone/voice_mic_action.dart
@@ -68,11 +68,14 @@ VoiceMicAction _tapAction(VoiceInputController voice, TerminalSession session) {
),
VoiceInputStatus.unavailable => _face(
VoiceMicFace.off,
- onPressed: () => unawaited(voice.startListening()),
+ onPressed: () =>
+ unawaited(voice.startListening(pretend: session.voicePretend)),
),
VoiceInputStatus.idle => _face(
VoiceMicFace.talk,
- onPressed: canSend ? () => unawaited(voice.startListening()) : null,
+ onPressed: canSend
+ ? () => unawaited(voice.startListening(pretend: session.voicePretend))
+ : null,
),
};
}
@@ -133,7 +136,10 @@ VoiceMicAction _holdAction(
onPressed: live ? _live : null,
onHoldStart: live
? () => unawaited(
- voice.startHold(session.voiceDeliver ?? session.sendComposerText),
+ voice.startHold(
+ session.voiceDeliver ?? session.sendComposerText,
+ pretend: session.voicePretend,
+ ),
)
: null,
onHoldFinish: live ? _release(voice, session) : null,
diff --git a/mobile/lib/phone/welcome/onboarding_copy.dart b/mobile/lib/phone/welcome/onboarding_copy.dart
index 6c30bb3df..365f06d5b 100644
--- a/mobile/lib/phone/welcome/onboarding_copy.dart
+++ b/mobile/lib/phone/welcome/onboarding_copy.dart
@@ -25,6 +25,13 @@
/// account to sign in with, and where Add Phone is (owner, 2026-10-12, after trying it):
/// until the phone adds the computer itself, the computer signs in on its own, and that is where
/// people stood stuck.
+/// Exception approved by the owner, Tony, 2026-10-22: one suggestion with a Send button above the
+/// mic in the first session, once — Desktop's pre-typed starter when the pane has one, otherwise the
+/// first of the New Harness first-task ideas. It goes after Send or a spoken message; no cycling and
+/// no other additions were approved.
+/// Owner, 2026-10-23: that session (OpenCode, Claude Code, Codex) opens with the keyboard up over the
+/// task typed into the prompt — Claude Code's and Codex's typed by the phone — and its mic pretends:
+/// no microphone and no permission prompt, a second tap sends the prompt as it stands.
abstract final class OnboardingCopy {
/// ① The welcome's headline: everything lit, the promise.
static const welcome =
@@ -79,6 +86,6 @@ abstract final class OnboardingCopy {
/// What the phone says by the mic the first time it opens a session — one line, once.
static const micSendIt = 'Send it, or say anything.';
static const micPickUp = 'Pick up where you left off.';
- static const micSayWhat = 'Say what to build.';
+ static const micSayWhat = 'Say what to build, or send this:';
static const micTalk = 'Talk to it.';
}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index c3ed10fd5..5ef712c6c 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1,4 +1,5 @@
import '../core/app_version.dart';
+import '../core/client_build.dart';
import '../core/install_source.dart';
import '../core/test_run.dart';
import '../measurement/launch_measurement.dart';
@@ -9,6 +10,7 @@ import '../measurement/product_resumes.dart';
import '../measurement/setup_transport.dart';
import 'dart:async';
+import 'dart:convert' show jsonDecode, jsonEncode;
import 'dart:math' show Random;
import 'package:dio/dio.dart';
@@ -1409,6 +1411,18 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// The app went to the background with dials or a launch still open. Every dial ends `cancelled` —
+ /// `remote_connect`'s ([_cancelMeasurementConnections]) and `connect_user`/`connect_auto`'s
+ /// ([ProductConnections.cancelOpen]) — and the launch, if no computer has answered, `unknown`
+ /// ([LaunchMeasurement.foreground]), as it does when the app is hidden. Only the background ends them: a
+ /// system sheet or the app switcher (`inactive`) is not leaving, and a dial after the app is back is a
+ /// new count.
+ void _endOpenMeasurementsForBackground() {
+ _cancelMeasurementConnections();
+ productConnections.cancelOpen();
+ launchMeasurement?.foreground(false);
+ }
+
/// Ends every dial still going as `cancelled`: the person left the screen before it had an answer,
/// which is neither a success nor a failure of the socket. Each count is dropped from
/// [_measurementConnections] as it ends, so the socket's own answer later finds none to end again
@@ -1783,6 +1797,7 @@ class AppNotifier extends ChangeNotifier {
// Which computer's tabs to show (Settings ▸ Profile). Queued behind the record above on
// purpose, and not awaited: nothing picks a tab before the desk's network read lands.
unawaited(_loadMachineProfile());
+ unawaited(_loadHarnessOsComputers());
// No screen from the last run: the agent that record names is drawn as the skeleton until its
// keyframe lands — see [KeptScreenStore]. What an earlier build kept of it on disk goes. Only in
// the app, on the store's terms: a test never reaches the real cache directory.
@@ -2542,6 +2557,9 @@ class AppNotifier extends ChangeNotifier {
wsBaseUrl: config.wsBaseUrl,
autonomousEnv: _autonomousEnv,
accessTokenProvider: _socketToken,
+ // Which release, and whether a debug or simulator build, goes in the socket's query. A test dials
+ // as itself, with a fake channel, and says neither.
+ clientBuild: kIsWeb || kUnderTest ? null : runningClientBuild,
relayCodecs: viewer.relayCodecs,
transportPlugins: viewer.transportPlugins,
onAuthFailure: _signedOutAtRuntime,
@@ -6141,9 +6159,122 @@ class AppNotifier extends ChangeNotifier {
bool runsHarnessOs(String machineId) =>
osStatus[machineId]?['harnessOs'] == true;
+ /// What a Harness OS computer's daemon does for a phone beyond its update and Wi-Fi, as its status
+ /// says (CLI osDevice.ts `features`): `sign_out`, `password`, `ssh`. An older one says none.
+ bool osFeature(String machineId, String feature) {
+ final features = osStatus[machineId]?['features'];
+ return features is List && features.contains(feature);
+ }
+
bool updateAvailable(String machineId) {
final update = osStatus[machineId]?['update'];
- return update is Map && update['available'] == true;
+ if (update is! Map || update['available'] != true) return false;
+ final parts = osParts(machineId);
+ // Named part by part: only what changes. A computer that does not name its parts says it whole.
+ if (parts.isEmpty) return true;
+ return osNewRelease(machineId) ||
+ parts['hn']?['available'] == true ||
+ parts['cli']?['available'] == true;
+ }
+
+ /// A Harness OS release newer than the one running — 0.1.9 after 0.1.8, not a later build of
+ /// 0.1.8, which a computer on 0.1.8 still offers (os/release_update.py compared whole packages).
+ bool osNewRelease(String machineId) {
+ final os = osParts(machineId)['os'];
+ if (os?['available'] != true) return false;
+ final next = os?['next'] as String?, running = os?['running'] as String?;
+ return next == null ||
+ running == null ||
+ releaseOf(next) != releaseOf(running);
+ }
+
+ /// A package version as its release: `0.1.8.r1792577066.g8df82cc2bc-1` is `0.1.8`.
+ static String releaseOf(String version) =>
+ RegExp(r'^\d+\.\d+\.\d+').firstMatch(version)?.group(0) ?? version;
+
+ /// Each part of a Harness OS computer, as its last status said (CLI osDevice.ts `update.parts`):
+ /// `os`, `hn`, `cli`, each `{running, available, next}`. Empty from a computer that does not say.
+ Map<String, Map<String, dynamic>> osParts(String machineId) {
+ final update = osStatus[machineId]?['update'];
+ final parts = update is Map ? update['parts'] : null;
+ if (parts is! Map) return const {};
+ return {
+ for (final entry in parts.entries)
+ if (entry.key is String && entry.value is Map)
+ entry.key as String: Map<String, dynamic>.from(entry.value as Map),
+ };
+ }
+
+ /// The update waiting needs the computer restarted: a new OS package, or one applied already that
+ /// is waiting for its restart. hn and the CLI alone do not.
+ bool updateRestarts(String machineId) {
+ final update = osStatus[machineId]?['update'];
+ if (update is! Map) return false;
+ if (update['restartRequired'] == true) return true;
+ return osNewRelease(machineId);
+ }
+
+ static const _harnessOsKey = 'harness_os_computers';
+
+ /// The Harness OS computers this phone has seen, kept between launches: the hotspot each opens and
+ /// whether its disk is encrypted. A computer switched off and on again is offline to the account,
+ /// waiting at its password; this is how the phone still knows to offer Unlock there.
+ final Map<String, ({String hotspot, bool encrypted})> harnessOsComputers = {};
+
+ Future<void> _loadHarnessOsComputers() async {
+ try {
+ final stored = await _paneLayout?.storage.read(_harnessOsKey);
+ if (stored == null || _disposed) return;
+ final decoded = jsonDecode(stored);
+ if (decoded is! Map) return;
+ for (final entry in decoded.entries) {
+ final value = entry.value;
+ if (entry.key is! String ||
+ value is! Map ||
+ value['hotspot'] is! String) {
+ continue;
+ }
+ harnessOsComputers[entry.key as String] = (
+ hotspot: value['hotspot'] as String,
+ encrypted: value['encrypted'] == true,
+ );
+ }
+ notifyListeners();
+ } catch (_) {
+ // Unreadable: learned again from each computer's next status.
+ }
+ }
+
+ void _rememberHarnessOs(String machineId, Map<String, dynamic> status) {
+ final hotspot = status['hotspot'];
+ if (status['harnessOs'] != true || hotspot is! String || hotspot.isEmpty) {
+ return;
+ }
+ final next = (hotspot: hotspot, encrypted: status['encrypted'] == true);
+ if (harnessOsComputers[machineId] == next) return;
+ harnessOsComputers[machineId] = next;
+ _saveHarnessOs();
+ }
+
+ /// Signed out from here: no Unlock for it any more. Its unlock would open the disk of a computer
+ /// that is set up again — with a sign-in, Set up a device — before it is online anywhere.
+ void forgetHarnessOs(String machineId) {
+ if (harnessOsComputers.remove(machineId) == null) return;
+ _saveHarnessOs();
+ notifyListeners();
+ }
+
+ void _saveHarnessOs() {
+ final json = jsonEncode({
+ for (final entry in harnessOsComputers.entries)
+ entry.key: {
+ 'hotspot': entry.value.hotspot,
+ 'encrypted': entry.value.encrypted,
+ },
+ });
+ unawaited(
+ _paneLayout?.storage.write(_harnessOsKey, json).catchError((_) {}),
+ );
}
/// Asks [machineId] what it is and whether it has an update, unless asked lately ([force] asks now).
@@ -6162,6 +6293,7 @@ class AppNotifier extends ChangeNotifier {
return;
}
osStatus[machineId] = status;
+ _rememberHarnessOs(machineId, status);
notifyListeners();
}
@@ -10639,9 +10771,9 @@ class AppNotifier extends ChangeNotifier {
/// And write the machine cache now ([_keepMachineCache]): this is the last moment the app is sure
/// to run, since closing it from the app switcher starts by sending it here.
///
- /// A dial still going ends `cancelled` ([_cancelMeasurementConnections]) before the counts are
- /// sent: an app the OS suspends in its first seconds away never hears the socket's answer, and
- /// the dial would stay without an outcome.
+ /// What the phone was still waiting on has no one to wait for it now, and ends before the counts are
+ /// sent ([_endOpenMeasurementsForBackground]): an app the OS suspends in its first seconds away never
+ /// hears the socket's answer, and the dial or launch would stay without an outcome.
void handleAppPaused() {
// The first pause of this time away: a second without a resume between (the OS repeating
// itself) does not move the moment the phone actually left.
@@ -10656,7 +10788,7 @@ class AppNotifier extends ChangeNotifier {
}
// The agents this run learned between lists, for the next launch — see [_keepMachineCache].
_keepMachineCache();
- _cancelMeasurementConnections();
+ _endOpenMeasurementsForBackground();
_sendMeasurementBeforeBackground();
}
diff --git a/mobile/lib/terminal/terminal_prompt_zone.dart b/mobile/lib/terminal/terminal_prompt_zone.dart
index f56f18c12..7f77f529b 100644
--- a/mobile/lib/terminal/terminal_prompt_zone.dart
+++ b/mobile/lib/terminal/terminal_prompt_zone.dart
@@ -104,6 +104,93 @@ bool _isTyped(BufferLine line) {
/// How many rows a prompt's typed text can run to — a long paste included.
const _maxInputRows = 200;
+/// OpenCode's boxed composer, read at its cursor, before its blank row and
+/// model footer. A cursor at the start means the grey placeholder is not text.
+/// The first-arrival starter is a sentence; the TUI wraps it at word boundaries.
+String? openCodePromptText(Buffer buffer) {
+ final cursor = buffer.absoluteCursorY;
+ if (cursor < 0 || cursor >= buffer.lines.length) return null;
+ final current = buffer.lines[cursor].getText();
+ final side = current.indexOf('┃');
+ if (side < 0 || buffer.cursorX <= side + 3) return null;
+ String? row(int y) {
+ if (y < 0 || y >= buffer.lines.length) return null;
+ final text = buffer.lines[y].getText();
+ if (text.indexOf('┃') != side || text.length <= side + 3) return null;
+ final content = text.substring(side + 3).trimRight();
+ return content.isEmpty ? null : content;
+ }
+
+ var top = cursor;
+ while (top > 0 && cursor - top < _maxInputRows && row(top - 1) != null) {
+ top--;
+ }
+ final parts = <String>[];
+ for (var y = top; y < buffer.lines.length && y - top < _maxInputRows; y++) {
+ final content = row(y);
+ if (content == null) break;
+ parts.add(content);
+ }
+ return parts.isEmpty ? null : parts.join(' ');
+}
+
+/// What is typed into [engine]'s prompt, on one line: OpenCode's box ([openCodePromptText]), or
+/// the `❯`/`›` prompt Claude Code and Codex draw ([promptInputRange]), its wrapped rows joined.
+/// Null when nothing is typed, only the placeholder shows, or the prompt cannot be read.
+String? typedPromptText(Buffer buffer, String? engine) {
+ if (engine == 'opencode') return openCodePromptText(buffer);
+ final range = promptInputRange(buffer);
+ if (range == null) return null;
+ final text = buffer.getText(range).replaceAll(_spaces, ' ').trim();
+ return text.isEmpty ? null : text;
+}
+
+final _spaces = RegExp(r'\s+');
+
+/// Whether [text] read off a prompt holds what a TUI drew in place of something pasted — Claude
+/// Code's `[Pasted text #1 +12 lines]` and `[Image #1]`, Codex's `[Pasted Content 1200 chars]`. What
+/// was pasted is only in the program: typed again from the screen, it would be the marker.
+bool holdsPasteMarker(String text) => _pasteMarker.hasMatch(text);
+
+final _pasteMarker = RegExp(
+ r'\[(?:Pasted text #\d+|Image #\d+|Pasted Content \d+)',
+);
+
+/// Whether the cursor is in [engine]'s prompt: on Claude Code's or Codex's `❯`/`›` line or a row
+/// its text wrapped onto, or inside OpenCode's box — where all three keep the terminal's own cursor,
+/// shown, at the end of what is typed (measured in tmux on 2026-10-23: Claude Code 2.1.309, Codex
+/// 0.163.0, OpenCode 1.19.0). False for any other engine.
+bool cursorInPrompt(Buffer buffer, String? engine) {
+ final cursor = buffer.absoluteCursorY;
+ if (cursor < 0 || cursor >= buffer.lines.length) return false;
+ if (engine == 'opencode') {
+ final side = buffer.lines[cursor].getText().indexOf('┃');
+ return side >= 0 && buffer.cursorX > side;
+ }
+ if (engine != 'claude' && engine != 'codex') return false;
+ final line = buffer.lines[cursor];
+ if (_promptGlyphColumn(line) case final glyph?) {
+ // A question's answer the cursor sits on (`❯ 1. Yes`) is a dialog, not the prompt.
+ return !_answerRow.hasMatch(line.getText(glyph + 1).trimLeft());
+ }
+ // A row the typed text wrapped onto.
+ return promptInputRange(buffer) != null;
+}
+
+/// Whether the cursor sits on a Claude Code or Codex prompt with nothing typed in it — its glyph
+/// alone, or its grey placeholder: the TUI is drawn and waiting for its first words.
+///
+/// Not a question's answer the cursor sits on (`❯ 1. Yes, proceed`): that is a dialog.
+bool emptyPromptAtCursor(Buffer buffer) {
+ final cursor = buffer.absoluteCursorY;
+ if (cursor < 0 || cursor >= buffer.lines.length) return false;
+ final line = buffer.lines[cursor];
+ final glyph = _promptGlyphColumn(line);
+ return glyph != null &&
+ !_answerRow.hasMatch(line.getText(glyph + 1).trimLeft()) &&
+ promptInputRange(buffer) == null;
+}
+
/// What an agent's prompt starts with, in column 0 or just inside a box's side: Claude Code's `❯`
/// (`>` in older builds), its `!` shell mode and `#` memory mode, and Codex's `›`. A shell themed
/// with a `❯` prompt reads the same way, and rightly: what follows it is what was typed.
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 962f6cfca..21a9e5763 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -470,6 +470,11 @@ class TerminalSession extends ChangeNotifier {
/// — but when it did not (seen 2026-10-06), the cursor stayed at the bottom row, under the status
/// lines and against the key bar, until the first key typed made Claude Code draw again. So the
/// cursor is not shown until the program's next output, whichever of the two that is.
+ ///
+ /// ⚠️ **Not when the screen the shrink is answered with has the cursor in the prompt** (owner,
+ /// 2026-10-23: a keyboard up over a prompt shows the caret blinking in it). There it is where the
+ /// program keeps it ([cursorInPrompt]), and hiding it waited on output that had already come:
+ /// a redraw that landed before this keyframe left the prompt with no caret until a key was typed.
bool _cursorAwaitsProgram = false;
/// The pane height whose shrinking cut rows drawn under the cursor ([_noteCutUnderCursor]), spent
@@ -1387,7 +1392,9 @@ class TerminalSession extends ChangeNotifier {
// The answer to the shrink that cut rows under the cursor. A keyframe at the old size, sent
// before the resize landed, leaves it for the one that is.
_cutUnderCursorFrom = null;
- if (!replacement.isUsingAltBuffer && !_cursorAwaitsProgram) {
+ if (!replacement.isUsingAltBuffer &&
+ !_cursorAwaitsProgram &&
+ !cursorInPrompt(replacement.buffer, engineId)) {
_cursorAwaitsProgram = true;
if (kTypingTrace) {
typingEvent(
@@ -1583,6 +1590,13 @@ class TerminalSession extends ChangeNotifier {
/// blind. Set and cleared by the page; null the rest of the time.
Future<bool> Function(String text)? voiceDeliver;
+ /// While this pane is the onboarding's first session, its mic's takes pretend: no microphone, no
+ /// permission prompt, each heard as what this says when it ends — the task in the prompt
+ /// (`VoiceInputController.startListening`). Null from it means an ordinary recording: the first send
+ /// has gone, or a question is open that a spoken answer is for. Set and cleared by the page; read
+ /// only by this pane's own mic (`voice_mic_action.dart`), never by Find's or New's.
+ String? Function()? voicePretend;
+
/// Called each time this pane sends a line on the person's behalf: a Return typed or pressed —
/// it crosses [_onTerminalOutput] — or a composed message that went ([sendComposerText]). Set by
/// the page showing the pane, which asks for notifications after the phone's first send
@@ -1602,6 +1616,22 @@ class TerminalSession extends ChangeNotifier {
return sent;
}
+ /// First-task suggestions replace the prompt rather than appending to it.
+ /// Wait for the clear's ordered input queue before the separate message frame:
+ /// otherwise a fast message could arrive before its clear. These are the
+ /// engines whose clear-prompt keys we support; never guess for another TUI.
+ Future<bool> sendFirstTask(String text) async {
+ if (!acceptsInput ||
+ !const ['claude', 'codex', 'opencode'].contains(engineId)) {
+ return false;
+ }
+ clearPrompt();
+ await _flushInput();
+ await _inputSendTail;
+ if (!acceptsInput) return false;
+ return sendComposerText(text);
+ }
+
/// A clipboard paste made directly into this pane, delivered as one atomic unit instead of going
/// through the same chunked pipeline as ordinary typing ([_onTerminalOutput]/[_flushInput]).
///
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 14f193fea..d93f1c5f3 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -10,6 +10,7 @@ import '../logging/app_log.dart';
import '../logging/redact.dart';
import '../logging/startup_trace.dart';
import '../logging/typing_trace.dart';
+import '../core/client_build.dart';
import '../core/models.dart';
import '../core/test_run.dart';
import 'relay_codec.dart';
@@ -113,6 +114,11 @@ class WsConn {
/// local transport, the dev fixture — means every frame rides the socket.
final TerminalTransportPluginFactory? transportPlugins;
+ /// What this build says of itself in the socket's query ([ClientBuild]): its release, and whether it is a
+ /// debug or simulator build, so the backend's count of the phone's opens can tell them apart. Asked at
+ /// every dial, with the credential; null: nothing is said, as an older app.
+ final Future<ClientBuild> Function()? clientBuild;
+
Future<Map<String, dynamic>> Function(
String type,
Map<String, dynamic> payload,
@@ -246,8 +252,20 @@ class WsConn {
required this.onStatus,
this.relayCodecs,
this.transportPlugins,
+ this.clientBuild,
});
+ /// [clientBuild], bounded and never failing: a dial does not wait on its own bookkeeping.
+ Future<ClientBuild?> _clientBuild() async {
+ final ask = clientBuild;
+ if (ask == null) return null;
+ try {
+ return await ask().timeout(const Duration(milliseconds: 500));
+ } catch (_) {
+ return null;
+ }
+ }
+
Future<void> connect() async {
if (_closing || _connecting) return;
_connecting = true;
@@ -308,10 +326,14 @@ class WsConn {
// What the codec said while the credential was being fetched, if it has said it yet.
({RelayCodec? codec, Object? error})? codecAnswered;
unawaited(pendingCodec?.then((result) => codecAnswered = result));
+ // Asked with the credential and the codec, so it adds no wait of its own: once the app has read
+ // its version (at launch) the answer is already there. Never a reason not to dial.
+ final pendingBuild = _clientBuild();
final token = await pendingToken;
if (token.isEmpty) {
throw StateError('WebSocket credential is missing');
}
+ final build = await pendingBuild;
if (_closing) return;
// The codec's "no link" comes from links held in memory, a handful of microtasks behind its
// start — and the credential, also from memory, often lands in the same turn, just ahead of
@@ -345,6 +367,8 @@ class WsConn {
'autonomousEnv': autonomousEnv,
// Counts this person as on the mobile app today (backend user_daily_client_presence).
'client': 'mobile',
+ // And which release, and whether a debug or simulator build (backend relay_mobile_opens).
+ ...?build?.query,
},
);
// ⚠️ **Dialled BEFORE the codec is awaited (owner, 2026-10-01).** The socket needs only the
diff --git a/mobile/lib/ws/ws_pool.dart b/mobile/lib/ws/ws_pool.dart
index 9bd8953ba..610b94f67 100644
--- a/mobile/lib/ws/ws_pool.dart
+++ b/mobile/lib/ws/ws_pool.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'relay_codec.dart';
import 'terminal_transport_plugin.dart';
+import '../core/client_build.dart';
import '../core/models.dart';
import '../logging/app_log.dart';
import 'ws_conn.dart';
@@ -20,6 +21,9 @@ class WsPool {
/// wire to the machine (see [TerminalTransportPlugin]).
final TerminalTransportPluginFactory? transportPlugins;
final AccessTokenProvider accessTokenProvider;
+
+ /// Handed to every relay connection: what the build says of itself in the socket's query.
+ final Future<ClientBuild> Function()? clientBuild;
final void Function(String message) onAuthFailure;
final void Function(String machineId, int code, String reason)?
onLocalFailure;
@@ -36,6 +40,7 @@ class WsPool {
this.relayCodecs,
this.transportPlugins,
required this.accessTokenProvider,
+ this.clientBuild,
required this.onAuthFailure,
this.onLocalFailure,
required this.onEvent,
@@ -78,6 +83,7 @@ class WsPool {
autonomousEnv: autonomousEnv,
relayCodecs: relayCodecs,
transportPlugins: transportPlugins,
+ clientBuild: clientBuild,
machineId: machineId,
accessTokenProvider: accessTokenProvider,
onAuthFailure: (message) {
diff --git a/mobile/test/app_state_flow_measurement_test.dart b/mobile/test/app_state_flow_measurement_test.dart
index e3a07a40a..710a3d4a3 100644
--- a/mobile/test/app_state_flow_measurement_test.dart
+++ b/mobile/test/app_state_flow_measurement_test.dart
@@ -1,10 +1,12 @@
import 'dart:async';
+import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/measurement/launch_measurement.dart';
import 'package:harness_mobile/measurement/onboarding_measurement.dart';
import 'package:harness_mobile/measurement/product_measurement.dart';
+import 'package:harness_mobile/state/app_state.dart';
import 'viewer_app_fixture.dart';
import 'voice_fakes.dart' show MemoryKeyValueStore;
@@ -53,6 +55,25 @@ void main() {
return total;
}
+ /// A launch that came back signed in, its computers [machines], counted as the app counts one.
+ /// [observeLifecycle]: the launch listens to the app's own lifecycle, as in the shipped app.
+ Future<ViewerRig> launching(
+ Future<List<Machine>> Function() machines, {
+ bool observeLifecycle = false,
+ }) async {
+ final rig = viewerApp(productMeasurement: usage);
+ addTearDown(rig.app.dispose);
+ rig.app.launchMeasurement = LaunchMeasurement(
+ usage,
+ observeLifecycle: observeLifecycle,
+ sinceLaunch: () => const Duration(seconds: 3),
+ );
+ rig.api.onMachines = machines;
+ await rig.app.bootstrap();
+ await settle();
+ return rig;
+ }
+
group('leaving the screen', () {
// iOS suspends an app within seconds and may end it unannounced; counts still in RAM go with
// it. The once-a-minute report is not waited for.
@@ -210,6 +231,206 @@ void main() {
});
});
+ /// The [flow]'s started and ended counts, apart from its duration buckets and (for a launch) its waits.
+ Future<Map<String, int>> outcomes(ViewerRig rig, String flow) async {
+ final all = await sent(rig, flow);
+ return {
+ for (final outcome in const [
+ 'started',
+ 'ok',
+ 'failed',
+ 'cancelled',
+ 'unknown',
+ ])
+ if (all.containsKey('ui_phone_${flow}_$outcome'))
+ outcome: all['ui_phone_${flow}_$outcome']!,
+ };
+ }
+
+ group(
+ 'connect_auto and connect_user when the app goes to the background',
+ () {
+ // The same dials as remote_connect's, counted by ProductConnections: the app's own, and the
+ // person's ("Try again").
+
+ test('the app\'s own dial still going is cancelled, once', () async {
+ final rig = await sharing({'m': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+
+ rig.app.handleAppPaused();
+ rig.app.handleAppPaused();
+
+ expect(await outcomes(rig, 'connect_auto'), {
+ 'started': 1,
+ 'cancelled': 1,
+ });
+ expect(await outcomes(rig, 'connect_user'), isEmpty);
+ });
+
+ test('a dial the person asked for is cancelled, not failed', () async {
+ final rig = await sharing({'m': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.disconnected);
+ final retry = rig.app.retryMachine('m');
+ await settle();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+
+ rig.app.handleAppPaused();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await retry;
+
+ expect(await outcomes(rig, 'connect_user'), {
+ 'started': 1,
+ 'cancelled': 1,
+ });
+ expect(await outcomes(rig, 'connect_auto'), isEmpty);
+ });
+
+ test('is no second outcome when the socket answers after all', () async {
+ final rig = await sharing({'m': [], 'n': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('n', ConnectionStatus.reconnecting);
+ rig.app.handleAppPaused();
+
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ rig.app.connectionStatusForTest('n', ConnectionStatus.disconnected);
+
+ expect(await outcomes(rig, 'connect_auto'), {
+ 'started': 2,
+ 'cancelled': 2,
+ });
+ });
+
+ test('that had finished before keeps its outcome', () async {
+ final rig = await sharing({'m': [], 'n': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ rig.app.connectionStatusForTest('n', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('n', ConnectionStatus.disconnected);
+
+ rig.app.handleAppPaused();
+
+ expect(await outcomes(rig, 'connect_auto'), {
+ 'started': 2,
+ 'ok': 1,
+ 'unknown': 1,
+ });
+ });
+
+ test(
+ 'is followed by a new count when the app dials after resuming',
+ () async {
+ final rig = await sharing({'m': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.handleAppPaused();
+ rig.app.handleAppResumed();
+ await settle();
+
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+
+ expect(await outcomes(rig, 'connect_auto'), {
+ 'started': 2,
+ 'cancelled': 1,
+ 'ok': 1,
+ });
+ },
+ );
+
+ test('is not ended by losing the foreground for a moment', () async {
+ final rig = await sharing({'m': []});
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+
+ rig.app.handleAppInactive();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+
+ expect(await outcomes(rig, 'connect_auto'), {'started': 1, 'ok': 1});
+ });
+ },
+ );
+
+ group('app_start when the app goes to the background', () {
+ // A launch whose computers have not answered when the phone leaves is `unknown`: whatever the
+ // wait took from there was not the launch's.
+
+ test('a launch still open is unknown, once', () async {
+ final rig = await launching(() async => [remoteMachine('m')]);
+ expect(await outcomes(rig, 'app_start'), {'started': 1});
+
+ rig.app.handleAppPaused();
+ rig.app.handleAppPaused();
+
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+ });
+
+ test('is no second outcome when a computer answers after all', () async {
+ final rig = await launching(() async => [remoteMachine('m')]);
+ rig.app.handleAppPaused();
+
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+ });
+
+ test('a launch a computer had answered stays ok, and only ok', () async {
+ final rig = await launching(() async => [remoteMachine('m')]);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+
+ rig.app.handleAppPaused();
+
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'ok': 1});
+ });
+
+ test('is not ended by losing the foreground for a moment', () async {
+ final rig = await launching(() async => [remoteMachine('m')]);
+
+ rig.app.handleAppInactive();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'ok': 1});
+ });
+
+ test('a pause after the launch was counted unknown adds nothing', () async {
+ // The shipped app also ends the launch by its own lifecycle listener, when the app is hidden.
+ final rig = await launching(() async => [remoteMachine('m')]);
+ rig.app.launchMeasurement!.foreground(false);
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+
+ rig.app.handleAppPaused();
+
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+ });
+
+ test('in the shipped app, the lifecycle alone has ended the launch before the pause', () async {
+ final binding = TestWidgetsFlutterBinding.ensureInitialized();
+ // The launch listens to the app's lifecycle itself and the shell calls the notifier on
+ // `inactive` and `paused`; the framework passes through `hidden` between the two.
+ final rig = await launching(
+ () async => [remoteMachine('m')],
+ observeLifecycle: true,
+ );
+ final shell = _ShellLifecycle(rig.app);
+ WidgetsBinding.instance.addObserver(shell);
+ addTearDown(() => WidgetsBinding.instance.removeObserver(shell));
+ addTearDown(
+ () => binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed),
+ );
+ binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ expect(await outcomes(rig, 'app_start'), {'started': 1});
+
+ binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ expect(await outcomes(rig, 'app_start'), {'started': 1});
+
+ binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+
+ binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
+ expect(await outcomes(rig, 'app_start'), {'started': 1, 'unknown': 1});
+ });
+ });
+
group('dials', () {
test('a socket coming back by itself is the app\'s own', () async {
final rig = await sharing({'m': []});
@@ -471,23 +692,6 @@ void main() {
});
group('what a launch back to work waited on', () {
- /// A launch that came back signed in, its computers [machines], counted as the app counts one.
- Future<ViewerRig> launching(
- Future<List<Machine>> Function() machines,
- ) async {
- final rig = viewerApp(productMeasurement: usage);
- addTearDown(rig.app.dispose);
- rig.app.launchMeasurement = LaunchMeasurement(
- usage,
- observeLifecycle: false,
- sinceLaunch: () => const Duration(seconds: 3),
- );
- rig.api.onMachines = machines;
- await rig.app.bootstrap();
- await settle();
- return rig;
- }
-
Future<Set<String>> waits(ViewerRig rig) async => {
for (final metric in (await sent(rig, 'app_start')).keys)
for (final why in LaunchWait.values)
@@ -570,3 +774,24 @@ void main() {
);
});
}
+
+/// What `PhoneShell` does with the app's lifecycle (`lib/phone/phone_shell.dart`).
+class _ShellLifecycle with WidgetsBindingObserver {
+ _ShellLifecycle(this.app);
+ final AppNotifier app;
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ switch (state) {
+ case AppLifecycleState.inactive:
+ app.handleAppInactive();
+ case AppLifecycleState.paused:
+ app.handleAppPaused();
+ case AppLifecycleState.resumed:
+ app.handleAppResumed();
+ case AppLifecycleState.hidden:
+ case AppLifecycleState.detached:
+ break;
+ }
+ }
+}
diff --git a/mobile/test/core/client_build_test.dart b/mobile/test/core/client_build_test.dart
new file mode 100644
index 000000000..a636040e7
--- /dev/null
+++ b/mobile/test/core/client_build_test.dart
@@ -0,0 +1,93 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/client_build.dart';
+
+void main() {
+ ClientBuild build({
+ String? version = '1.0.9',
+ bool releaseMode = true,
+ TargetPlatform platform = TargetPlatform.iOS,
+ Map<String, String> environment = const {},
+ }) => clientBuildOf(
+ version: version,
+ releaseMode: releaseMode,
+ platform: platform,
+ environment: environment,
+ );
+
+ group('what the socket says of the build', () {
+ test('a release build says its release and nothing else', () {
+ expect(build().release, '1.0.9');
+ expect(build().debug, isFalse);
+ expect(build().query, {'release': '1.0.9'});
+ expect(build(platform: TargetPlatform.android).query, {
+ 'release': '1.0.9',
+ });
+ });
+
+ test('a debug or profile build says so', () {
+ final debug = build(releaseMode: false);
+ expect(debug.debug, isTrue);
+ expect(debug.query, {'release': '1.0.9', 'debug': '1'});
+ expect(
+ build(releaseMode: false, platform: TargetPlatform.android).debug,
+ isTrue,
+ );
+ });
+
+ test('the iOS Simulator says so, whatever the build', () {
+ final simulator = build(environment: {'SIMULATOR_DEVICE_NAME': 'iPhone'});
+ expect(simulator.debug, isTrue);
+ expect(simulator.query, {'release': '1.0.9', 'debug': '1'});
+ });
+
+ test(
+ 'that environment means nothing off iOS, and its absence nothing on it',
+ () {
+ expect(
+ build(
+ platform: TargetPlatform.android,
+ environment: {'SIMULATOR_DEVICE_NAME': 'x'},
+ ).debug,
+ isFalse,
+ );
+ expect(build(environment: {'HOME': '/private'}).debug, isFalse);
+ },
+ );
+
+ test('a version that is not a plain x.y.z is no release', () {
+ for (final version in [
+ null,
+ '',
+ '1.0',
+ '1.0.9+72',
+ '1.0.9-beta',
+ '1.0.9.1',
+ '01.0.9',
+ '1000.0.0',
+ 'PRIVATE',
+ ]) {
+ expect(build(version: version).release, isNull, reason: '$version');
+ expect(build(version: version).query, isEmpty, reason: '$version');
+ }
+ });
+
+ test('says nothing that tells one phone from another', () {
+ final query = build(
+ releaseMode: false,
+ environment: {'SIMULATOR_DEVICE_NAME': 'PRIVATE_NAME', 'USER': 'pat'},
+ ).query;
+ expect(query.keys, ['release', 'debug']);
+ expect(query.values.join(), isNot(contains('PRIVATE')));
+ });
+ });
+
+ test('the running build is read once and never fails', () async {
+ final first = runningClientBuild();
+ expect(runningClientBuild(), same(first));
+ // Under test the platform has no package info: no release, and not a release build.
+ final read = await first;
+ expect(read.release, isNull);
+ expect(read.debug, isTrue);
+ });
+}
diff --git a/mobile/test/first_engine_test.dart b/mobile/test/first_engine_test.dart
new file mode 100644
index 000000000..4bdf910e6
--- /dev/null
+++ b/mobile/test/first_engine_test.dart
@@ -0,0 +1,70 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/engine_availability.dart';
+import 'package:harness_mobile/core/first_engine.dart';
+
+void main() {
+ test(
+ 'only reported installed, signed-in accounts qualify; most recent wins',
+ () {
+ final engines = MachineEngines();
+ expect(firstEngine(engines), 'opencode');
+ void report(List<Map<String, Object?>> entries) => engines.replace(
+ entries
+ .map(EngineAvailability.fromJson)
+ .whereType<EngineAvailability>(),
+ );
+ report([
+ {'engine': 'claude', 'installed': true, 'signedIn': false},
+ ]);
+ expect(firstEngine(engines), 'opencode');
+ report([
+ {'engine': 'claude', 'installed': true},
+ ]);
+ expect(engines['claude']!.signedIn, isNull);
+ expect(firstEngine(engines), 'opencode');
+ report([
+ {'engine': 'claude', 'installed': true, 'signedIn': true},
+ ]);
+ expect(firstEngine(engines), 'claude');
+ report([
+ {'engine': 'codex', 'installed': true, 'signedIn': true},
+ ]);
+ expect(firstEngine(engines), 'codex');
+ report([
+ {
+ 'engine': 'claude',
+ 'installed': true,
+ 'signedIn': true,
+ 'lastUsedAt': 100,
+ },
+ {
+ 'engine': 'codex',
+ 'installed': true,
+ 'signedIn': true,
+ 'lastUsedAt': 200,
+ },
+ ]);
+ expect(engines['codex']!.lastUsedAt, 200);
+ expect(firstEngine(engines), 'codex');
+ report([
+ {
+ 'engine': 'claude',
+ 'installed': true,
+ 'signedIn': true,
+ 'lastUsedAt': 300,
+ },
+ {
+ 'engine': 'codex',
+ 'installed': true,
+ 'signedIn': true,
+ 'lastUsedAt': 200,
+ },
+ ]);
+ expect(firstEngine(engines), 'claude');
+ report([
+ {'engine': 'codex', 'installed': false, 'signedIn': true},
+ ]);
+ expect(firstEngine(engines), 'opencode');
+ },
+ );
+}
diff --git a/mobile/test/open_code_starter_test.dart b/mobile/test/open_code_starter_test.dart
new file mode 100644
index 000000000..5e8b5fb3d
--- /dev/null
+++ b/mobile/test/open_code_starter_test.dart
@@ -0,0 +1,30 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/xterm.dart';
+import 'package:harness_mobile/terminal/terminal_prompt_zone.dart';
+
+void main() {
+ test(
+ 'reads the real OpenCode starter at phone width, without its model footer',
+ () {
+ // Captured in OpenCode 1.19.0 on macOS, 42 columns, 2026-10-22.
+ final terminal = Terminal()..resize(42, 32);
+ terminal.write(
+ ' ┃\r\n ┃ make a small web page that shows\r\n'
+ " ┃ today's date\r\n ┃\r\n ┃ Build ·Claude Opus 5.5 Anthropic\r\n"
+ ' ┃\r\n ╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\x1b[3;17H',
+ );
+ expect(
+ openCodePromptText(terminal.buffer),
+ "make a small web page that shows today's date",
+ );
+ terminal.write(
+ '\x1b[2J\x1b[H ┃\r\n ┃ Ask anything… "Fix broken tests"\r\n ┃\x1b[2;6H',
+ );
+ expect(
+ openCodePromptText(terminal.buffer),
+ isNull,
+ reason: 'a placeholder is not a task',
+ );
+ },
+ );
+}
diff --git a/mobile/test/phone/computer_version_short_test.dart b/mobile/test/phone/computer_version_short_test.dart
new file mode 100644
index 000000000..91e9801e7
--- /dev/null
+++ b/mobile/test/phone/computer_version_short_test.dart
@@ -0,0 +1,17 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/phone/computer_version_page.dart';
+
+void main() {
+ test(
+ 'a version reads as its release, without the build pacman names it by',
+ () {
+ expect(shortVersion('0.1.8.r1792577066.g8df82cc2bc-1'), '0.1.8');
+ expect(shortVersion('0.1.7.r1792566394.ga1fceef1bf-1'), '0.1.7');
+ expect(shortVersion('0.4.39'), '0.4.39');
+ expect(shortVersion('0.1.8.simulated-1'), '0.1.8');
+ expect(shortVersion('preview'), 'preview');
+ expect(shortVersion(null), isNull);
+ },
+ );
+}
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index 979d71a77..369ed59ac 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -15,6 +15,7 @@ import 'package:harness_mobile/phone/phone_shell_scope.dart';
import 'package:harness_mobile/phone/terminal_file_send.dart';
import 'package:harness_mobile/phone/terminal_find_bar.dart';
import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/widgets/terminal_panel.dart';
import 'package:harness_mobile/phone/terminal_search.dart';
import 'package:harness_mobile/phone/settings_page.dart';
import 'package:harness_mobile/phone/voice_input_controller.dart';
@@ -113,6 +114,29 @@ void main() {
await focus.close();
});
+ testWidgets('a keyboard asked for again while ⌄ still slides it down is '
+ "the page's", (tester) async {
+ final focus = await _Focus.open(tester);
+ bool focused() =>
+ tester.widget<TerminalPanel>(find.byType(TerminalPanel)).focused;
+
+ await focus.tapPrompt();
+ raiseKeyboard(tester);
+ await frames(tester);
+ expect(focused(), isTrue);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-key-Hide keyboard')));
+ // Halfway down when the prompt is tapped again: the inset turns back without reaching zero.
+ tester.view.viewInsets = const FakeViewPadding(bottom: 300);
+ await tester.pump(const Duration(milliseconds: 16));
+ await focus.tapPrompt();
+ raiseKeyboard(tester);
+ await frames(tester);
+
+ expect(focused(), isTrue, reason: 'the keyboard up is read as up');
+ await focus.close();
+ });
+
testWidgets('the machine goes offline under the agent on screen, and back', (
tester,
) async {
diff --git a/mobile/test/phone_edge/new_behavior_test.dart b/mobile/test/phone_edge/new_behavior_test.dart
index 7e498713d..105101e93 100644
--- a/mobile/test/phone_edge/new_behavior_test.dart
+++ b/mobile/test/phone_edge/new_behavior_test.dart
@@ -21,8 +21,13 @@ void main() {
const answers = {
'engines_probe': {
'engines': [
- {'engine': 'claude', 'installed': true},
- {'engine': 'codex', 'installed': true, 'supportsCodexHome': true},
+ {'engine': 'claude', 'installed': true, 'signedIn': true},
+ {
+ 'engine': 'codex',
+ 'installed': true,
+ 'signedIn': true,
+ 'supportsCodexHome': true,
+ },
{'engine': 'opencode', 'installed': false, 'installable': false},
],
},
@@ -455,7 +460,11 @@ void main() {
await close(tester, app);
});
- testWidgets('agents are offered in most recently used order', (tester) async {
+ // Desktop's order (new_harness.dart `_agentOptions`): the selected agent, then the most recently
+ // used, then the rest as the catalog lists them.
+ testWidgets('agents are offered selected first, then most recently used', (
+ tester,
+ ) async {
final (:app, conn: _) = await openNew(tester);
await app.agentPreference.select('claude');
await app.agentPreference.select('opencode');
@@ -466,7 +475,7 @@ void main() {
.widgetList<FindRow>(find.byType(FindRow))
.map((row) => row.title)
.toList();
- expect(titles.take(3), ['Codex', 'OpenCode', 'Claude Code']);
+ expect(titles.take(3), ['Claude Code', 'Codex', 'OpenCode']);
expect(find.text('more'), findsNothing);
await close(tester, app);
});
diff --git a/mobile/test/phone_engine_preselection_test.dart b/mobile/test/phone_engine_preselection_test.dart
new file mode 100644
index 000000000..e26c08b51
--- /dev/null
+++ b/mobile/test/phone_engine_preselection_test.dart
@@ -0,0 +1,211 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/new_agent_draft.dart';
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/phone/tty_controls.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'phone_edge/edge_fixture.dart';
+
+/// What a computer reports about an engine: installed, and — from a computer that says — signed in.
+Map<String, Object> _engine(
+ String id, {
+ bool installed = true,
+ bool? signedIn,
+ int? lastUsedAt,
+}) => {
+ 'engine': id,
+ 'installed': installed,
+ 'signedIn': ?signedIn,
+ 'lastUsedAt': ?lastUsedAt,
+};
+
+/// One computer's answer, the agent last started from the phone (if any), and what New Harness
+/// should open on.
+class _Case {
+ const _Case(this.name, this.engines, this.opensOn, {this.remembered});
+ final String name;
+ final List<Map<String, Object>> engines;
+ final String opensOn;
+ final String? remembered;
+}
+
+void main() {
+ tearDown(() => newAgentDraft = null);
+
+ Future<AppNotifier> openForm(
+ WidgetTester tester,
+ List<Map<String, Object>> engines, {
+ String? remembered,
+ }) async {
+ final app = edgeApp(
+ conn: EdgeConn({
+ 'engines_probe': {'engines': engines},
+ }, startsAgents),
+ );
+ addTearDown(app.dispose);
+ if (remembered != null) await app.agentPreference.select(remembered);
+ setPhone(tester, largePhone);
+ await tester.pumpWidget(
+ phoneApp(NewAgentPage(notifier: app, machineId: 'm')),
+ );
+ await frames(tester);
+ return app;
+ }
+
+ String agentRow(WidgetTester tester) => tester
+ .widget<TtyFormRow>(
+ find.byWidgetPredicate((w) => w is TtyFormRow && w.label == 'agent'),
+ )
+ .value;
+
+ Future<void> chooseAgent(WidgetTester tester, String title) async {
+ await tapInView(tester, find.text('agent'));
+ await frames(tester);
+ await tester.tap(find.text(title, findRichText: true).last);
+ await frames(tester);
+ }
+
+ for (final scenario in <_Case>[
+ const _Case('nothing signed in', [], 'OpenCode'),
+ _Case('Claude only', [_engine('claude', signedIn: true)], 'Claude Code'),
+ _Case('Codex only', [_engine('codex', signedIn: true)], 'Codex'),
+ _Case('both, Claude last', [
+ _engine('claude', signedIn: true, lastUsedAt: 200),
+ _engine('codex', signedIn: true, lastUsedAt: 100),
+ ], 'Claude Code'),
+ _Case('both, Codex last', [
+ _engine('claude', signedIn: true, lastUsedAt: 100),
+ _engine('codex', signedIn: true, lastUsedAt: 200),
+ ], 'Codex'),
+ _Case('installed but signed out', [
+ _engine('claude', signedIn: false),
+ _engine('codex', signedIn: false),
+ ], 'OpenCode'),
+ _Case('old computer does not report sign-in', [
+ _engine('claude'),
+ ], 'OpenCode'),
+ _Case('credential without installed engine', [
+ _engine('codex', installed: false, signedIn: true),
+ ], 'OpenCode'),
+ // The agent last started from this phone, as the desktop's `agentPreference`: kept while the
+ // computer can still run it, else the computer's own answer.
+ _Case(
+ 'remembered Codex is usable: it wins over Claude used last',
+ [
+ _engine('claude', signedIn: true, lastUsedAt: 200),
+ _engine('codex', signedIn: true, lastUsedAt: 100),
+ ],
+ 'Codex',
+ remembered: 'codex',
+ ),
+ _Case(
+ 'remembered Codex is signed out here: the computer chooses',
+ [_engine('claude', signedIn: true), _engine('codex', signedIn: false)],
+ 'Claude Code',
+ remembered: 'codex',
+ ),
+ _Case(
+ 'remembered Codex is not installed here: the computer chooses',
+ [
+ _engine('claude', signedIn: true),
+ _engine('codex', installed: false, signedIn: true),
+ ],
+ 'Claude Code',
+ remembered: 'codex',
+ ),
+ _Case(
+ 'remembered Claude on an older computer that reports no sign-in',
+ [_engine('claude')],
+ 'Claude Code',
+ remembered: 'claude',
+ ),
+ _Case(
+ 'remembered Claude that the computer says nothing about',
+ [],
+ 'OpenCode',
+ remembered: 'claude',
+ ),
+ _Case(
+ 'remembered OpenCode is kept over a signed-in Claude',
+ [_engine('claude', signedIn: true), _engine('opencode')],
+ 'OpenCode',
+ remembered: 'opencode',
+ ),
+ ]) {
+ testWidgets('computer chooses ${scenario.name}', (tester) async {
+ await openForm(tester, scenario.engines, remembered: scenario.remembered);
+ expect(agentRow(tester), scenario.opensOn);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ // A pick is never undone: not by the computer's engines arriving, nor by a later probe.
+ for (final scenario in <_Case>[
+ _Case('signed out here', [
+ _engine('claude', signedIn: false),
+ _engine('codex', signedIn: true),
+ ], 'Codex'),
+ _Case('an older computer that reports no sign-in', [
+ _engine('claude'),
+ ], 'OpenCode'),
+ ]) {
+ testWidgets('a picked Claude Code is kept on ${scenario.name}', (
+ tester,
+ ) async {
+ final app = await openForm(tester, scenario.engines);
+ expect(agentRow(tester), scenario.opensOn);
+ await chooseAgent(tester, 'Claude Code');
+ expect(agentRow(tester), 'Claude Code');
+ await app.probeEngines('m', force: true);
+ await frames(tester);
+ expect(agentRow(tester), 'Claude Code');
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets(
+ 'agent chooser retains Desktop catalog order after the selected agent',
+ (tester) async {
+ final source = File('../desktop/lib/widgets/engine_identity.dart')
+ .readAsStringSync();
+ final desktop = RegExp(r"^ '([^']+)': EngineIdentity", multiLine: true)
+ .allMatches(source)
+ .map((m) => m[1]!)
+ .where((id) => allEngines.any((e) => e.id == id))
+ .toList();
+ expect(allEngines.map((e) => e.id).toList(), desktop);
+ final app = edgeApp(
+ conn: EdgeConn({
+ 'engines_probe': {'engines': []},
+ }, startsAgents),
+ );
+ addTearDown(app.dispose);
+ setPhone(tester, largePhone);
+ await tester.pumpWidget(
+ phoneApp(NewAgentPage(notifier: app, machineId: 'm')),
+ );
+ await frames(tester);
+ await tester.tap(find.text('agent'));
+ await frames(tester);
+ // Desktop puts the selected agent first, then recents, then declaration order.
+ expect(
+ tester.getTopLeft(find.text('OpenCode', findRichText: true).last).dy,
+ lessThan(
+ tester
+ .getTopLeft(find.text('Claude Code', findRichText: true).last)
+ .dy,
+ ),
+ );
+ expect(
+ tester.getTopLeft(find.text('Cursor', findRichText: true).last).dy,
+ lessThan(
+ tester.getTopLeft(find.text('Amp', findRichText: true).last).dy,
+ ),
+ );
+ },
+ );
+}
diff --git a/mobile/test/phone_first_task_suggestion_test.dart b/mobile/test/phone_first_task_suggestion_test.dart
new file mode 100644
index 000000000..d1d7cc3d5
--- /dev/null
+++ b/mobile/test/phone_first_task_suggestion_test.dart
@@ -0,0 +1,818 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/xterm.dart' show TerminalKey, TerminalView;
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/first_task_suggestion.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/phone/voice_mic_button.dart';
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+import 'package:harness_mobile/phone/welcome/onboarding_copy.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+import 'voice_fakes.dart';
+
+void main() {
+ late AppNotifier app;
+ late TerminalSession session;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+ late FakeTranscriber transcriber;
+ late FakeVoiceRecorder recorder;
+ late List<(String, Object)> sent;
+
+ setUp(() {
+ sent = [];
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'opencode',
+ send: (type, payload) async {
+ sent.add((type, payload));
+ return true;
+ },
+ sendBinary: (frame) async {
+ sent.add(('keys', String.fromCharCodes(frame.bytes)));
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream';
+ app.adoptSessionForTest(session);
+ language = ValueNotifier('en');
+ transcriber = FakeTranscriber();
+ recorder = FakeVoiceRecorder();
+ voice = VoiceInputController(
+ transcriber: transcriber.call,
+ recorder: recorder,
+ language: language,
+ );
+ });
+ tearDown(() {
+ voice.dispose();
+ language.dispose();
+ app.dispose();
+ });
+
+ Future<void> open(
+ WidgetTester tester, {
+ String? line,
+ String agent = 'a',
+ String page = 'a',
+ }) async {
+ if (line != null) {
+ app.firstSessionLine = (machineId: 'm', agentId: agent, text: line);
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: app,
+ machineId: 'm',
+ agentId: page,
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ /// Takes the page away and lets the pane settle: the first session raises the keyboard, and the
+ /// key bar rising resizes the terminal behind a short debounce.
+ Future<void> leave(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ final keyBar = find.byKey(const ValueKey('terminal-key-esc'));
+
+ const typed = "make a small web page that shows today's date";
+ const ideas = [
+ 'Explain this project to me',
+ 'Find a bug and fix it',
+ 'Run the tests',
+ ];
+ final sendButton = find.byKey(FirstSessionSuggestion.sendKey);
+
+ List<Object?> messages() => [
+ for (final (type, payload) in sent)
+ if (type == 'message') (payload as Map)['content'],
+ ];
+
+ /// Lets the send's awaited steps (clear, flush, message frame) run.
+ Future<void> settleSend(WidgetTester tester) async {
+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));
+ await tester.pump();
+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));
+ await tester.pump();
+ }
+
+ /// Lets the send finish without drawing a frame.
+ Future<void> settleSendWithoutFrame(WidgetTester tester) async {
+ for (var i = 0; i < 4; i++) {
+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));
+ }
+ }
+
+ /// OpenCode's box with the starter Desktop typed into it, at phone width.
+ void typeStarter() {
+ session.terminal.resize(88, 30);
+ session.terminal.write(
+ ' ┃\r\n ┃ $typed\r\n ┃\r\n ┃ Build · Claude\x1b[2;54H',
+ );
+ }
+
+ /// OpenCode answering a send: its box emptied, the cursor where the placeholder starts — written
+ /// after the tick, as the session writes output.
+ void emptyBox() {
+ session.outputTicks.value++;
+ session.terminal.write('\x1b[2;1H\x1b[2K ┃ \x1b[2;11H');
+ }
+
+ /// A spoken message through the real mic button and controller; only the recognizer is a fake.
+ Future<void> speak(WidgetTester tester, String words) async {
+ transcriber.replies.add(words);
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ expect(voice.status, VoiceInputStatus.listening);
+ await tester.tap(find.byType(VoiceMicButton));
+ for (var i = 0; i < 4; i++) {
+ await settleSend(tester);
+ }
+ }
+
+ testWidgets(
+ 'the first session offers one suggestion with a Send, not three chips',
+ (tester) async {
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ expect(find.text('Say what to build, or send this:'), findsOneWidget);
+ expect(find.text(ideas.first), findsOneWidget);
+ expect(sendButton, findsOneWidget);
+ expect(find.text('Send'), findsOneWidget);
+ for (final other in ideas.skip(1)) {
+ expect(find.text(other), findsNothing);
+ }
+ // The mic stays as the other way in.
+ expect(find.byType(VoiceMicButton), findsOneWidget);
+ expect(
+ tester
+ .widget<FirstSessionSuggestion>(find.byType(FirstSessionSuggestion))
+ .onSend,
+ isNotNull,
+ );
+ },
+ );
+
+ testWidgets(
+ 'Send sends exactly the suggestion once, then the suggestion goes',
+ (tester) async {
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ // A second tap while the first is on its way sends nothing more.
+ await tester.tap(sendButton);
+ await tester.tap(sendButton, warnIfMissed: false);
+ await settleSend(tester);
+ expect(messages(), [ideas.first]);
+ expect(app.firstSessionLine, isNull);
+ expect(sendButton, findsNothing);
+ expect(find.text(ideas.first), findsNothing);
+ expect(
+ tester.widget<VoiceMicButton>(find.byType(VoiceMicButton)).face,
+ VoiceMicFace.sent,
+ );
+ await tester.pump(const Duration(seconds: 1));
+ // Said once: coming back to the session shows nothing.
+ await tester.pumpWidget(const SizedBox());
+ await open(tester);
+ expect(find.text(ideas.first), findsNothing);
+ expect(sendButton, findsNothing);
+ expect(messages(), [ideas.first]);
+ },
+ );
+
+ testWidgets(
+ 'a second tap in the frame after the send landed sends nothing more',
+ (tester) async {
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ await tester.tap(sendButton);
+ // The send is over and the line spent, but the page has not drawn that yet: the button is still
+ // there under the finger. (Seen on the iPhone: the transport answered inside one frame.)
+ await settleSendWithoutFrame(tester);
+ expect(app.firstSessionLine, isNull);
+ await tester.tap(sendButton, warnIfMissed: false);
+ await settleSendWithoutFrame(tester);
+ expect(messages(), [ideas.first]);
+ await tester.pump(const Duration(seconds: 1));
+ await leave(tester);
+ },
+ );
+
+ testWidgets(
+ 'Send is disabled while the session does not take input, and wakes with it',
+ (tester) async {
+ session.status = TerminalSessionStatus.opening;
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ expect(sendButton, findsOneWidget);
+ expect(
+ tester
+ .widget<FirstSessionSuggestion>(find.byType(FirstSessionSuggestion))
+ .onSend,
+ isNull,
+ );
+ await tester.tap(sendButton, warnIfMissed: false);
+ await settleSend(tester);
+ expect(messages(), isEmpty);
+ expect(app.firstSessionLine, isNotNull);
+ session.status = TerminalSessionStatus.controlling;
+ session.notifyListeners();
+ await tester.pump();
+ expect(
+ tester
+ .widget<FirstSessionSuggestion>(find.byType(FirstSessionSuggestion))
+ .onSend,
+ isNotNull,
+ );
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ expect(messages(), [ideas.first]);
+ },
+ );
+
+ for (final line in [null, OnboardingCopy.micTalk, OnboardingCopy.micPickUp]) {
+ testWidgets('no suggestion outside the fresh hand-over: $line', (
+ tester,
+ ) async {
+ await open(tester, line: line);
+ expect(sendButton, findsNothing);
+ expect(find.text(ideas.first), findsNothing);
+ });
+ }
+
+ testWidgets('another session does not inherit the suggestion', (
+ tester,
+ ) async {
+ await open(tester, line: OnboardingCopy.micSayWhat, agent: 'other');
+ expect(sendButton, findsNothing);
+ });
+
+ testWidgets('a pane of an engine that cannot be cleared offers no Send', (
+ tester,
+ ) async {
+ final other =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'g',
+ agentName: 'Agent',
+ engineId: 'gemini',
+ send: (type, payload) async => true,
+ sendBinary: (frame) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream';
+ app.adoptSessionForTest(other);
+ app.firstSessionLine = (
+ machineId: 'm',
+ agentId: 'g',
+ text: OnboardingCopy.micSayWhat,
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: app,
+ machineId: 'm',
+ agentId: 'g',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(sendButton, findsNothing);
+ expect(find.text('Say what to build, or send this:'), findsOneWidget);
+ });
+
+ group('a starter Desktop typed into OpenCode', () {
+ testWidgets(
+ 'is the one suggestion, and Send clears the box before sending it',
+ (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ expect(find.text(typed), findsOneWidget);
+ expect(find.text(ideas.first), findsNothing);
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ final message = sent.indexWhere((e) => e.$1 == 'message');
+ expect(message, greaterThan(0));
+ expect(
+ sent
+ .take(message)
+ .where((e) => e.$1 == 'keys')
+ .map((e) => e.$2)
+ .join(),
+ contains('\x15'),
+ );
+ expect(messages(), [typed]);
+ expect(app.firstSessionLine, isNull);
+ expect(sendButton, findsNothing);
+ await tester.pump(const Duration(seconds: 1));
+ await leave(tester);
+ },
+ );
+
+ testWidgets('a box emptied on the keyboard still sends Desktop\'s starter, '
+ 'never a task the screen did not show', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ session.terminal.write('\x1b[2;1H\x1b[2K ┃ \x1b[2;11H');
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ expect(messages(), [typed]);
+ await leave(tester);
+ });
+
+ testWidgets(
+ 'a paste the box shows as a marker goes by Return as it stands',
+ (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ session.terminal.write(
+ '\x1b[2;1H\x1b[2K ┃ read [Pasted text #1 +12 lines]\x1b[2;43H',
+ );
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ expect(messages(), isEmpty);
+ final keys = sent.where((e) => e.$1 == 'keys').map((e) => e.$2).join();
+ expect(keys, contains('\r'));
+ expect(
+ keys,
+ isNot(contains('\x15')),
+ reason: 'the paste is not cleared',
+ );
+ await leave(tester);
+ },
+ );
+
+ testWidgets('a pretend take does not follow a swipe to another page', (
+ tester,
+ ) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ expect(voice.pretending, isTrue);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: app,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ isActive: false,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(voice.pretending, isFalse);
+ expect(voice.isIdle, isTrue);
+ await leave(tester);
+ });
+
+ testWidgets('Send sends the box as it was last changed', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ // Changed on the keyboard since the suggestion was drawn.
+ session.terminal.write(
+ '\x1b[2;1H\x1b[2K ┃ make a clock\x1b[2;23H',
+ );
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ expect(messages(), ['make a clock']);
+ await leave(tester);
+ });
+
+ testWidgets('a take over it records nothing, and sends the box as it '
+ 'stands, replacing it', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await speak(tester, 'add a login page');
+ final message = sent.indexWhere((e) => e.$1 == 'message');
+ expect(message, greaterThan(0));
+ expect(
+ sent.take(message).where((e) => e.$1 == 'keys').map((e) => e.$2).join(),
+ contains('\x15'),
+ );
+ expect(messages(), [typed]);
+ expect(recorder.starts, 0, reason: 'no microphone is opened');
+ expect(transcriber.calls, isEmpty);
+ expect(sendButton, findsNothing);
+ await tester.pump(const Duration(seconds: 1));
+ await leave(tester);
+ });
+
+ testWidgets('a take is heard as the box when it ends, changes included', (
+ tester,
+ ) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ expect(voice.status, VoiceInputStatus.listening);
+ session.terminal.write(
+ '\x1b[2;1H\x1b[2K ┃ make a clock\x1b[2;23H',
+ );
+ await tester.tap(find.byType(VoiceMicButton));
+ for (var i = 0; i < 4; i++) {
+ await settleSend(tester);
+ }
+ expect(messages(), ['make a clock']);
+ await leave(tester);
+ });
+ });
+
+ group('the keyboard', () {
+ testWidgets('is up as the first session opens over its task, and put '
+ 'away, stays away', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.pump();
+ expect(tester.testTextInput.isVisible, isTrue);
+ // The keyboard arrives: its key bar comes with it.
+ tester.view.viewInsets = const FakeViewPadding(bottom: 900);
+ addTearDown(tester.view.resetViewInsets);
+ await tester.pump(const Duration(seconds: 1));
+ expect(keyBar, findsOneWidget);
+
+ await tester.tap(
+ find.byKey(const ValueKey('terminal-key-Hide keyboard')),
+ );
+ tester.view.viewInsets = FakeViewPadding.zero;
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pump(const Duration(seconds: 1));
+ expect(tester.testTextInput.isVisible, isFalse);
+ expect(keyBar, findsNothing);
+ // Send and the mic are there instead.
+ expect(sendButton, findsOneWidget);
+ expect(find.byType(VoiceMicButton), findsOneWidget);
+ await leave(tester);
+ });
+
+ testWidgets('goes once Return sends the task, and stays up for the next '
+ 'Return', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.pump();
+ expect(tester.testTextInput.isVisible, isTrue);
+
+ session.terminal.keyInput(TerminalKey.enter);
+ await settleSend(tester);
+ expect(app.firstSessionLine, isNull);
+ // Up until the harness has taken the task: its box empties.
+ expect(tester.testTextInput.isVisible, isTrue);
+ emptyBox();
+ await settleSend(tester);
+ await tester.pump(const Duration(seconds: 1));
+ expect(tester.testTextInput.isVisible, isFalse);
+
+ // Raised again by hand, a tap on the prompt: Return in a session at work keeps it up.
+ final terminal = tester.getRect(find.byType(TerminalView));
+ final screen =
+ tester.view.physicalSize.height / tester.view.devicePixelRatio;
+ final bottom = terminal.bottom < screen ? terminal.bottom : screen - 40;
+ await tester.tapAt(Offset(terminal.left + 30, bottom - 8));
+ await settleSend(tester);
+ await tester.pump(const Duration(seconds: 1));
+ expect(tester.testTextInput.isVisible, isTrue);
+ session.terminal.keyInput(TerminalKey.enter);
+ await settleSend(tester);
+ await tester.pump(const Duration(seconds: 1));
+ expect(tester.testTextInput.isVisible, isTrue);
+ await leave(tester);
+ });
+
+ testWidgets('stays down while it slides away, through a keyframe that '
+ 'lands meanwhile', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.pump();
+ tester.view.viewInsets = const FakeViewPadding(bottom: 900);
+ addTearDown(tester.view.resetViewInsets);
+ await tester.pump(const Duration(seconds: 1));
+ expect(tester.testTextInput.isVisible, isTrue);
+
+ session.terminal.keyInput(TerminalKey.enter);
+ await settleSend(tester);
+ // Still sliding down — the inset is not gone yet — when the harness redraws in a keyframe.
+ tester.view.viewInsets = const FakeViewPadding(bottom: 500);
+ await tester.pump(const Duration(milliseconds: 50));
+ unawaited(
+ session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: 'stream',
+ seq: 0,
+ bytes: Uint8List.fromList(
+ utf8.encode(' ┃\r\n ┃ \r\n ┃\x1b[2;11H'),
+ ),
+ compressed: false,
+ cols: 88,
+ rows: 30,
+ ),
+ ),
+ );
+ await settleSend(tester);
+ await tester.pump(const Duration(milliseconds: 50));
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(session.terminal.buffer.lines[1].getText(), contains('┃'));
+ expect(tester.testTextInput.isVisible, isFalse);
+
+ tester.view.viewInsets = FakeViewPadding.zero;
+ // Past the wait the keyframe started for the pane's own resize.
+ await tester.pump(const Duration(seconds: 2));
+ expect(tester.testTextInput.isVisible, isFalse);
+ await leave(tester);
+ });
+
+ testWidgets('goes once Send sends the task', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.pump();
+ expect(tester.testTextInput.isVisible, isTrue);
+
+ await tester.tap(sendButton);
+ await settleSend(tester);
+ emptyBox();
+ await settleSend(tester);
+ await tester.pump(const Duration(seconds: 1));
+ expect(messages(), [typed]);
+ expect(tester.testTextInput.isVisible, isFalse);
+ await leave(tester);
+ });
+
+ testWidgets('stays up after a Return that sent nothing: the prompt still '
+ 'holds its text', (tester) async {
+ typeStarter();
+ await open(tester, line: OnboardingCopy.micSendIt);
+ await tester.pump();
+
+ // A file picked from a menu, say: the box redraws with its text still in it.
+ session.terminal.keyInput(TerminalKey.enter);
+ await settleSend(tester);
+ session.outputTicks.value++;
+ session.terminal.write('\x1b[2;1H\x1b[2K ┃ $typed\x1b[2;54H');
+ await settleSend(tester);
+ await tester.pump(const Duration(seconds: 4));
+ expect(tester.testTextInput.isVisible, isTrue);
+ await leave(tester);
+ });
+
+ for (final line in [
+ null,
+ OnboardingCopy.micTalk,
+ OnboardingCopy.micPickUp,
+ ]) {
+ testWidgets('is not raised outside the fresh hand-over: $line', (
+ tester,
+ ) async {
+ await open(tester, line: line);
+ await tester.pump();
+ expect(tester.testTextInput.isVisible, isFalse);
+ await leave(tester);
+ });
+ }
+ });
+
+ group('a fresh Claude Code', () {
+ late TerminalSession claude;
+
+ setUp(() {
+ claude =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'c',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, payload) async {
+ sent.add((type, payload));
+ return true;
+ },
+ sendBinary: (frame) async {
+ sent.add(('keys', String.fromCharCodes(frame.bytes)));
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream';
+ app.adoptSessionForTest(claude);
+ });
+
+ String keys() => sent.where((e) => e.$1 == 'keys').map((e) => e.$2).join();
+
+ /// Claude Code's prompt between its rules, with [typed] in it and the cursor after it — written
+ /// as the session writes output: the tick first, then the text.
+ void drawPrompt([String typed = '']) {
+ claude.terminal.resize(60, 20);
+ claude.outputTicks.value++;
+ claude.terminal.write(
+ '\x1b[H\x1b[2J${'─' * 60}\r\n❯ $typed\r\n${'─' * 60}'
+ '\x1b[2;${3 + typed.length}H',
+ );
+ }
+
+ /// Claude Code asking first, its cursor on the answer: a dialog where the prompt will be.
+ void drawQuestion() {
+ claude.terminal.resize(60, 20);
+ claude.outputTicks.value++;
+ claude.terminal.write(
+ '\x1b[H\x1b[2J${'─' * 60}\r\n Do you want to proceed?\r\n'
+ '❯ 1. Yes\r\n 2. No\r\n\r\n Esc to cancel · Enter to select'
+ '\x1b[3;3H',
+ );
+ }
+
+ testWidgets('a prompt that arrives in a keyframe gets the idea too', (
+ tester,
+ ) async {
+ await open(
+ tester,
+ line: OnboardingCopy.micSayWhat,
+ agent: 'c',
+ page: 'c',
+ );
+ await settleSend(tester);
+ expect(keys(), isNot(contains(ideas.first)));
+
+ // A keyframe swaps the screen and notifies the session; no output tick.
+ claude.terminal.resize(60, 20);
+ claude.terminal.write('${'─' * 60}\r\n❯ \r\n${'─' * 60}\x1b[2;3H');
+ claude.notifyListeners();
+ await settleSend(tester);
+ expect(keys(), contains(ideas.first));
+ expect(tester.testTextInput.isVisible, isTrue);
+ await leave(tester);
+ });
+
+ testWidgets('a question first: no keyboard over it, the mic records an '
+ 'answer, and the prompt after it gets the idea', (tester) async {
+ drawQuestion();
+ await open(
+ tester,
+ line: OnboardingCopy.micSayWhat,
+ agent: 'c',
+ page: 'c',
+ );
+ await settleSend(tester);
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(tester.testTextInput.isVisible, isFalse);
+ expect(keys(), isNot(contains(ideas.first)));
+
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ expect(voice.status, VoiceInputStatus.listening);
+ expect(recorder.starts, 1, reason: 'an answer is spoken, not pretended');
+ voice.clear();
+ await settleSend(tester);
+
+ // Answered on the computer: the prompt is drawn.
+ drawPrompt();
+ await settleSend(tester);
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(keys(), contains(ideas.first));
+ expect(tester.testTextInput.isVisible, isTrue);
+ await leave(tester);
+ });
+
+ testWidgets('gets the first idea typed into its prompt, unsent, once the '
+ 'prompt is drawn', (tester) async {
+ await open(
+ tester,
+ line: OnboardingCopy.micSayWhat,
+ agent: 'c',
+ page: 'c',
+ );
+ await settleSend(tester);
+ expect(keys(), isNot(contains(ideas.first)), reason: 'nothing drawn yet');
+
+ drawPrompt();
+ await settleSend(tester);
+ expect(keys(), contains(ideas.first));
+ expect(keys(), isNot(contains('\r')));
+ expect(messages(), isEmpty);
+ expect(tester.testTextInput.isVisible, isTrue);
+ await leave(tester);
+ });
+
+ testWidgets('a prompt somebody typed into first is left alone', (
+ tester,
+ ) async {
+ drawPrompt('my own words');
+ await open(
+ tester,
+ line: OnboardingCopy.micSayWhat,
+ agent: 'c',
+ page: 'c',
+ );
+ await settleSend(tester);
+ expect(keys(), isNot(contains(ideas.first)));
+ await leave(tester);
+ });
+
+ testWidgets('Send and the mic send its prompt as last changed', (
+ tester,
+ ) async {
+ drawPrompt();
+ await open(
+ tester,
+ line: OnboardingCopy.micSayWhat,
+ agent: 'c',
+ page: 'c',
+ );
+ await settleSend(tester);
+ // Claude Code echoes the idea, and it is changed on the keyboard.
+ drawPrompt('Explain this repo');
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ await tester.tap(find.byType(VoiceMicButton));
+ for (var i = 0; i < 4; i++) {
+ await settleSend(tester);
+ }
+ expect(messages(), ['Explain this repo']);
+ expect(recorder.starts, 0);
+ await leave(tester);
+ });
+ });
+
+ group('the mic stays the other way in', () {
+ testWidgets(
+ 'a take sends the task, asks for no microphone, and the suggestion goes',
+ (tester) async {
+ recorder.permitted = false;
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ await speak(tester, 'add a login page');
+ expect(messages(), [ideas.first]);
+ expect(recorder.starts, 0);
+ expect(transcriber.calls, isEmpty);
+ expect(app.firstSessionLine, isNull);
+ expect(sendButton, findsNothing);
+ expect(find.text(ideas.first), findsNothing);
+ await tester.pump(const Duration(seconds: 1));
+ await leave(tester);
+ },
+ );
+
+ testWidgets('after the first send, a take is a recording again', (
+ tester,
+ ) async {
+ await open(tester, line: OnboardingCopy.micSayWhat);
+ await speak(tester, 'add a login page');
+ expect(messages(), [ideas.first]);
+ await tester.pump(const Duration(seconds: 3));
+ transcriber.replies.clear();
+
+ await speak(tester, 'now add a test');
+ expect(recorder.starts, 1);
+ expect(messages(), [ideas.first, 'now add a test']);
+ await tester.pump(const Duration(seconds: 1));
+ await leave(tester);
+ });
+
+ for (final starter in [false, true]) {
+ testWidgets('while a take is on, the suggestion and its line step aside, and are back when the take is dropped'
+ '${starter ? ' (a starter Desktop typed)' : ''}', (tester) async {
+ final line = starter
+ ? OnboardingCopy.micSendIt
+ : OnboardingCopy.micSayWhat;
+ if (starter) typeStarter();
+ await open(tester, line: line);
+ expect(find.text(line), findsOneWidget);
+ expect(sendButton, findsOneWidget);
+ await tester.tap(find.byType(VoiceMicButton));
+ await settleSend(tester);
+ expect(voice.status, VoiceInputStatus.listening);
+ // The line is not left standing over an empty row.
+ expect(sendButton, findsNothing);
+ expect(find.text(line), findsNothing);
+ expect(find.byKey(const ValueKey('first-session-line')), findsNothing);
+ // The take is thrown away, nothing was said: both are the way to start again.
+ voice.clear();
+ await tester.pump(const Duration(seconds: 3));
+ await settleSend(tester);
+ expect(sendButton, findsOneWidget);
+ expect(find.text(line), findsOneWidget);
+ expect(app.firstSessionLine, isNotNull);
+ await leave(tester);
+ });
+ }
+ });
+}
diff --git a/mobile/test/product_connections_test.dart b/mobile/test/product_connections_test.dart
index c53654277..de74b23dc 100644
--- a/mobile/test/product_connections_test.dart
+++ b/mobile/test/product_connections_test.dart
@@ -170,6 +170,96 @@ void main() {
},
);
+ group('the app going to the background', () {
+ /// How many dials of [flow] started and ended each way, apart from the duration buckets.
+ Future<Map<String, int>> outcomes(String flow) async {
+ final all = await sent();
+ return {
+ for (final outcome in const [
+ 'started',
+ 'ok',
+ 'failed',
+ 'cancelled',
+ 'unknown',
+ ])
+ if (all.containsKey('ui_phone_${flow}_$outcome'))
+ outcome: all['ui_phone_${flow}_$outcome']!,
+ };
+ }
+
+ test(
+ 'ends the app\'s own dial and the person\'s as cancelled, once each',
+ () async {
+ await signIn();
+ dial('own');
+ connections.manual('asked');
+ dial('asked');
+
+ connections.cancelOpen();
+ connections.cancelOpen();
+
+ expect(await outcomes('connect_auto'), {'started': 1, 'cancelled': 1});
+ expect(await outcomes('connect_user'), {'started': 1, 'cancelled': 1});
+ },
+ );
+
+ test('leaves nothing for the socket\'s answer, or the asked-for deadline, to count', () async {
+ await signIn();
+ dial('own');
+ connections.manual('asked');
+ connections.cancelOpen();
+
+ dial('own', up: true);
+ dial('asked', down: true);
+ dial('asked', up: true);
+ // Past the 1 ms deadline the dial would otherwise have been failed at.
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+
+ expect(await outcomes('connect_auto'), {'started': 1, 'cancelled': 1});
+ expect(await outcomes('connect_user'), {'started': 1, 'cancelled': 1});
+ });
+
+ test('keeps the outcome of a dial that had finished', () async {
+ await signIn();
+ dial('up');
+ dial('up', up: true);
+ dial('locked');
+ dial('locked', down: true, failed: true);
+ connections.manual('answered', connected: true);
+
+ connections.cancelOpen();
+
+ expect(await outcomes('connect_auto'), {
+ 'started': 2,
+ 'ok': 1,
+ 'failed': 1,
+ });
+ expect(await outcomes('connect_user'), {'started': 1, 'ok': 1});
+ });
+
+ test('is followed by a new count when the app dials again', () async {
+ await signIn();
+ dial('m');
+ connections.cancelOpen();
+
+ dial('m');
+ dial('m', up: true);
+
+ expect(await outcomes('connect_auto'), {
+ 'started': 2,
+ 'cancelled': 1,
+ 'ok': 1,
+ });
+ });
+
+ test('with nothing open counts nothing', () async {
+ await signIn();
+ connections.cancelOpen();
+ expect(await outcomes('connect_auto'), isEmpty);
+ expect(await outcomes('connect_user'), isEmpty);
+ });
+ });
+
test('no connection key ever reaches a report', () async {
await signIn();
dial('PRIVATE_MACHINE');
diff --git a/mobile/test/terminal_paste_test.dart b/mobile/test/terminal_paste_test.dart
index de56f82c4..c353633f2 100644
--- a/mobile/test/terminal_paste_test.dart
+++ b/mobile/test/terminal_paste_test.dart
@@ -67,6 +67,14 @@ void main() {
report: reports.add,
);
+ /// Real time passing until [done], in small steps: the image transcode decodes and encodes on
+ /// the engine's own threads, which an event-queue pump does not wait for.
+ Future<void> until(bool Function() done) async {
+ for (var i = 0; i < 500 && !done(); i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ }
+ }
+
setUp(() {
frames = [];
reports = [];
@@ -190,7 +198,7 @@ void main() {
// Nothing answers the upload's begin here, so only that it was asked for is checked.
unawaited(paste());
- await pumpEventQueue();
+ await until(() => sentTypes.isNotEmpty || reports.isNotEmpty);
expect(sentTypes, contains('terminal_chunked_upload_begin'));
expect(reports, isEmpty);
diff --git a/mobile/test/terminal_prompt_zone_test.dart b/mobile/test/terminal_prompt_zone_test.dart
index 9def6190b..e60770ba3 100644
--- a/mobile/test/terminal_prompt_zone_test.dart
+++ b/mobile/test/terminal_prompt_zone_test.dart
@@ -26,6 +26,11 @@ List<int> _promptRows(Terminal terminal) => [
if (isPromptTap(terminal.buffer, row)) row,
];
+/// A 42×12 screen with [text] written to it as a program would write it.
+Terminal _raw(String text) => Terminal()
+ ..resize(42, 12)
+ ..write(text);
+
void main() {
test('Codex: the prompt, a row of slack, and the footer under it', () {
// As captured from a live Codex pane: the cursor sits on `› `.
@@ -155,4 +160,133 @@ void main() {
expect(isPromptTap(terminal.buffer, 1), isFalse);
});
});
+
+ group('typedPromptText', () {
+ test("reads Claude Code's prompt, its wrapped rows joined", () {
+ final terminal = _raw(
+ '─' * 42 +
+ '\r\n❯ make a small web page that shows the date\r\n'
+ ' and the time\r\n${'─' * 42}\r\n ? for shortcuts\x1b[3;15H',
+ );
+ expect(
+ typedPromptText(terminal.buffer, 'claude'),
+ 'make a small web page that shows the date and the time',
+ );
+ });
+
+ test("reads Codex's prompt", () {
+ final terminal = _raw('\r\n› Explain this project to me\r\n\x1b[2;29H');
+ expect(
+ typedPromptText(terminal.buffer, 'codex'),
+ 'Explain this project to me',
+ );
+ });
+
+ test("reads OpenCode's box", () {
+ final terminal = _raw(
+ ' ┃\r\n ┃ Run the tests\r\n ┃\r\n ┃ Build · Claude\x1b[2;19H',
+ );
+ expect(typedPromptText(terminal.buffer, 'opencode'), 'Run the tests');
+ });
+
+ test('nothing for an empty prompt or a placeholder', () {
+ expect(typedPromptText(_raw('❯ \x1b[1;3H').buffer, 'claude'), isNull);
+ final placeholder = _raw(
+ '❯ \x1b[2mTry "fix lint errors"\x1b[0m\x1b[1;3H',
+ );
+ expect(typedPromptText(placeholder.buffer, 'claude'), isNull);
+ });
+ });
+
+ group('emptyPromptAtCursor', () {
+ test(
+ 'true on an empty prompt, and on one showing only its placeholder',
+ () {
+ expect(emptyPromptAtCursor(_raw('❯ \x1b[1;3H').buffer), isTrue);
+ expect(
+ emptyPromptAtCursor(
+ _raw('› \x1b[2mAsk Codex to do anything\x1b[0m\x1b[1;3H').buffer,
+ ),
+ isTrue,
+ );
+ },
+ );
+
+ test('false once something is typed', () {
+ expect(emptyPromptAtCursor(_raw('❯ hi\x1b[1;5H').buffer), isFalse);
+ });
+
+ test('false before the prompt is drawn, or with the cursor off it', () {
+ expect(emptyPromptAtCursor(_raw('').buffer), isFalse);
+ expect(
+ emptyPromptAtCursor(_raw('Starting Claude Code…\r\n').buffer),
+ isFalse,
+ );
+ });
+ });
+
+ group('cursorInPrompt', () {
+ test("on Claude Code's and Codex's prompt, typed in or empty", () {
+ expect(
+ cursorInPrompt(_raw('❯ hello world\x1b[1;14H').buffer, 'claude'),
+ isTrue,
+ );
+ expect(cursorInPrompt(_raw('❯ \x1b[1;3H').buffer, 'claude'), isTrue);
+ expect(
+ cursorInPrompt(_raw('› hello world\x1b[1;14H').buffer, 'codex'),
+ isTrue,
+ );
+ });
+
+ test('on a row the typed text wrapped onto', () {
+ final terminal = _raw('❯ a long line that\r\n wrapped\x1b[2;10H');
+ expect(cursorInPrompt(terminal.buffer, 'claude'), isTrue);
+ });
+
+ test("inside OpenCode's box, and not left of its side", () {
+ final box = ' ┃\r\n ┃ hello world\r\n ┃';
+ expect(cursorInPrompt(_raw('$box\x1b[2;17H').buffer, 'opencode'), isTrue);
+ expect(cursorInPrompt(_raw('$box\x1b[2;1H').buffer, 'opencode'), isFalse);
+ });
+
+ test('not on a status line under the prompt', () {
+ final terminal = _raw(
+ '${'─' * 42}\r\n❯ hi\r\n${'─' * 42}\r\n ? for shortcuts\x1b[4;18H',
+ );
+ expect(cursorInPrompt(terminal.buffer, 'claude'), isFalse);
+ });
+
+ test('never for another engine', () {
+ expect(cursorInPrompt(_raw('❯ hi\x1b[1;5H').buffer, 'gemini'), isFalse);
+ expect(cursorInPrompt(_raw('❯ hi\x1b[1;5H').buffer, null), isFalse);
+ });
+ });
+
+ group('a dialog where the prompt was', () {
+ test(
+ "a question's answer the cursor sits on is no prompt, empty or not",
+ () {
+ final dialog = _raw(
+ ' Do you trust the files in this folder?\r\n\r\n'
+ '❯ 1. Yes, proceed\r\n 2. No, exit\x1b[3;3H',
+ );
+ expect(emptyPromptAtCursor(dialog.buffer), isFalse);
+ expect(cursorInPrompt(dialog.buffer, 'claude'), isFalse);
+ expect(typedPromptText(dialog.buffer, 'claude'), isNull);
+ },
+ );
+ });
+
+ group('holdsPasteMarker', () {
+ test("Claude Code's and Codex's paste markers", () {
+ expect(holdsPasteMarker('fix [Pasted text #1 +12 lines]'), isTrue);
+ expect(holdsPasteMarker('what is in [Image #2]'), isTrue);
+ expect(holdsPasteMarker('[Pasted Content 1200 chars] read this'), isTrue);
+ });
+
+ test('nothing else', () {
+ expect(holdsPasteMarker('make a small web page'), isFalse);
+ expect(holdsPasteMarker('see [the docs] #1'), isFalse);
+ });
+ });
}
diff --git a/mobile/test/terminal_session_protocol_test.dart b/mobile/test/terminal_session_protocol_test.dart
index 8f1cd4d83..5d9ad4b4d 100644
--- a/mobile/test/terminal_session_protocol_test.dart
+++ b/mobile/test/terminal_session_protocol_test.dart
@@ -1845,6 +1845,66 @@ void main() {
expect(viewport.scrolls, [(1, 10, 0)]);
});
+ group('a shrink that cuts rows under the cursor', () {
+ // Claude Code's screen at 80×24: its prompt between two rules, two status lines under it, and
+ // the cursor at the end of what is typed.
+ final claudeScreen =
+ '\x1b[?25h${'\r\n' * 18}${'─' * 79}\r\n❯ hello world\r\n${'─' * 79}'
+ '\r\n ? for shortcuts\r\n auto mode on\x1b[20;14H';
+
+ TerminalBinaryFrame answer(String streamId, String text) =>
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 1,
+ bytes: Uint8List.fromList(utf8.encode(text)),
+ compressed: false,
+ cols: 80,
+ rows: 18,
+ );
+
+ Future<(TerminalSession, String)> shrunk() async {
+ final (s, streamId) = await live(screen: claudeScreen);
+ expect(s.terminal.cursorVisibleMode, isTrue);
+ // The keyboard comes up: tmux drops the rows under the prompt.
+ s.resize(80, 18);
+ await Future<void>.delayed(const Duration(milliseconds: 60));
+ expect(wire.of('terminal_resize'), isNotEmpty);
+ return (s, streamId);
+ }
+
+ test('keeps the cursor shown when the answer has it in the prompt', () async {
+ final (s, streamId) = await shrunk();
+
+ await s.handleBinary(
+ answer(
+ streamId,
+ '\x1b[?25h${'\r\n' * 12}${'─' * 79}\r\n❯ hello world\r\n${'─' * 79}'
+ '\r\n ? for shortcuts\r\n auto mode on\x1b[14;14H',
+ ),
+ );
+
+ expect(s.terminal.cursorVisibleMode, isTrue);
+ });
+
+ test('hides a cursor left under the status lines until the program '
+ 'draws again', () async {
+ final (s, streamId) = await shrunk();
+
+ await s.handleBinary(
+ answer(
+ streamId,
+ '\x1b[?25h${'\r\n' * 12}${'─' * 79}\r\n❯ hello world\r\n${'─' * 79}'
+ '\r\n ? for shortcuts\r\n auto mode on\x1b[18;1H',
+ ),
+ );
+ expect(s.terminal.cursorVisibleMode, isFalse);
+
+ await s.handleBinary(_output(streamId, 2, '\x1b[14;14H'));
+ expect(s.terminal.cursorVisibleMode, isTrue);
+ });
+ });
+
test('the cursor blinks locally, never into the stream', () async {
final (s, _) = await live();
diff --git a/mobile/test/voice_input_controller_test.dart b/mobile/test/voice_input_controller_test.dart
index 64ee996ed..27e2b9055 100644
--- a/mobile/test/voice_input_controller_test.dart
+++ b/mobile/test/voice_input_controller_test.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/phone/voice_input_controller.dart';
@@ -290,4 +291,180 @@ void main() {
expect(backend.calls.single.lang, 'vi');
});
+
+ group('a pretend take', () {
+ test('listens without asking for the microphone or opening it', () async {
+ recorder.permitted = false;
+
+ await voice.startListening(pretend: () => 'make a page');
+
+ expect(voice.status, VoiceInputStatus.listening);
+ expect(voice.pretending, isTrue);
+ expect(recorder.starts, 0);
+ expect(recorder.recording, isFalse);
+ });
+
+ test('is heard as what pretend says when it ends, and nothing is uploaded '
+ 'or recorded', () async {
+ var prompt = 'make a page';
+ await voice.startListening(pretend: () => prompt);
+ // Changed while the take was on: the take is heard as the prompt at its end.
+ prompt = 'make a page with a clock';
+ final sent = <String>[];
+
+ await voice.submit((text) async {
+ sent.add(text);
+ return true;
+ });
+
+ expect(sent, ['make a page with a clock']);
+ expect(backend.calls, isEmpty);
+ expect(recorder.stops, 0);
+ expect(voice.isIdle, isTrue);
+ expect(voice.pretending, isFalse);
+ });
+
+ test('pretend saying null makes an ordinary recording', () async {
+ backend.replies.add('yes');
+
+ await voice.startListening(pretend: () => null);
+ await voice.stopListening();
+
+ expect(recorder.starts, 1);
+ expect(voice.transcript, 'yes');
+ });
+
+ test(
+ 'a take that pretend stops speaking for mid-way is heard as nothing',
+ () async {
+ String? prompt = 'make a page';
+ await voice.startListening(pretend: () => prompt);
+ prompt = null;
+ var sends = 0;
+
+ await voice.submit((_) async {
+ sends++;
+ return true;
+ });
+
+ expect(sends, 0);
+ expect(voice.notice, VoiceNotice.nothingHeard);
+ expect(recorder.starts, 0);
+ },
+ );
+
+ test(
+ 'replaces words held from a send that failed, never joins them',
+ () async {
+ await voice.startListening(pretend: () => 'make a page');
+ await voice.submit((_) async => false);
+ expect(voice.transcript, 'make a page');
+
+ await voice.startListening(pretend: () => 'make a page');
+ final sent = <String>[];
+ await voice.submit((text) async {
+ sent.add(text);
+ return true;
+ });
+
+ expect(sent, ['make a page']);
+ },
+ );
+
+ test('a prompt that cannot be read ends the take as nothing heard, not a '
+ 'mic stuck listening', () async {
+ await voice.startListening(
+ pretend: () {
+ if (voice.status == VoiceInputStatus.listening) throw StateError('x');
+ return 'make a page';
+ },
+ );
+ var sends = 0;
+
+ await voice.submit((_) async {
+ sends++;
+ return true;
+ });
+
+ expect(sends, 0);
+ expect(voice.status, VoiceInputStatus.idle);
+ });
+
+ test('moves its meter while it listens, and rests it after', () {
+ fakeAsync((async) {
+ unawaited(voice.startListening(pretend: () => 'make a page'));
+ async.flushMicrotasks();
+ final levels = <double>{};
+ for (var i = 0; i < 10; i++) {
+ async.elapse(const Duration(milliseconds: 90));
+ levels.add(voice.level.value);
+ }
+ expect(levels.length, greaterThan(1));
+ expect(levels.every((level) => level > 0), isTrue);
+
+ voice.clear();
+ async.elapse(const Duration(milliseconds: 200));
+ expect(voice.level.value, 0);
+ expect(voice.status, VoiceInputStatus.idle);
+ });
+ });
+
+ test('the level is one listenable: a listener added during a pretend take '
+ 'comes off after it', () {
+ fakeAsync((async) {
+ expect(identical(voice.level, voice.level), isTrue);
+ unawaited(voice.startListening(pretend: () => 'make a page'));
+ async.flushMicrotasks();
+ var heard = 0;
+ void listener() => heard++;
+ voice.level.addListener(listener);
+ async.elapse(const Duration(milliseconds: 200));
+ expect(heard, greaterThan(0));
+
+ voice.clear();
+ voice.level.removeListener(listener);
+ heard = 0;
+ unawaited(voice.startListening(pretend: () => 'make a page'));
+ async.flushMicrotasks();
+ async.elapse(const Duration(milliseconds: 500));
+ expect(heard, 0, reason: 'nothing left on the pretend meter');
+ voice.clear();
+ });
+ });
+
+ test(
+ 'hands the keyboard nothing: what it stands for is in the prompt',
+ () async {
+ await voice.startListening(pretend: () => 'make a page');
+
+ expect(await voice.takeTranscript(), isEmpty);
+ expect(voice.isIdle, isTrue);
+ },
+ );
+
+ test('an empty prompt is heard as nothing, and nothing is sent', () async {
+ await voice.startListening(pretend: () => ' ');
+ var sends = 0;
+
+ await voice.submit((_) async {
+ sends++;
+ return true;
+ });
+
+ expect(sends, 0);
+ expect(voice.notice, VoiceNotice.nothingHeard);
+ });
+
+ test('a take with no pretend records, whatever the last one was', () async {
+ await voice.startListening(pretend: () => 'make a page');
+ await voice.submit((_) async => true);
+ backend.replies.add('add a test');
+
+ await voice.startListening();
+ await voice.stopListening();
+
+ expect(recorder.starts, 1);
+ expect(voice.transcript, 'add a test');
+ });
+ });
}
diff --git a/mobile/test/ws/ws_conn_relay_test.dart b/mobile/test/ws/ws_conn_relay_test.dart
index 35be22642..02e74c4db 100644
--- a/mobile/test/ws/ws_conn_relay_test.dart
+++ b/mobile/test/ws/ws_conn_relay_test.dart
@@ -5,6 +5,7 @@ import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/client_build.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/e2ee/bytes.dart';
import 'package:harness_mobile/e2ee/keys.dart';
@@ -52,6 +53,7 @@ void main() {
AccessTokenProvider? tokens,
RelayCodecFactory? relayCodecs,
bool noCodecs = false,
+ Future<ClientBuild> Function()? clientBuild,
}) {
statuses = [];
signOuts = [];
@@ -68,6 +70,7 @@ void main() {
onEvent: events.add,
onStatus: statuses.add,
relayCodecs: noCodecs ? null : (relayCodecs ?? codecs()),
+ clientBuild: clientBuild,
);
addTearDown(conn.close);
return conn;
@@ -120,6 +123,67 @@ void main() {
},
);
+ group('which build dials', () {
+ Future<Map<String, String>> dialled(
+ Future<ClientBuild> Function()? clientBuild,
+ ) async {
+ final conn = newConn(clientBuild: clientBuild);
+ final session = relay.nextSession();
+ unawaited(conn.connect());
+ await session.timeout(const Duration(seconds: 5));
+ return relay.dialledUris.single.queryParameters;
+ }
+
+ test('a release build carries its release', () async {
+ expect(await dialled(() async => const ClientBuild(release: '1.0.9')), {
+ 'autonomousEnv': 'test',
+ 'client': 'mobile',
+ 'release': '1.0.9',
+ });
+ });
+
+ test('a debug or simulator build carries the flag as well', () async {
+ expect(
+ await dialled(
+ () async => const ClientBuild(release: '1.0.9', debug: true),
+ ),
+ {
+ 'autonomousEnv': 'test',
+ 'client': 'mobile',
+ 'release': '1.0.9',
+ 'debug': '1',
+ },
+ );
+ });
+
+ test(
+ 'a build with no release says only that it is a debug one',
+ () async {
+ expect(await dialled(() async => const ClientBuild(debug: true)), {
+ 'autonomousEnv': 'test',
+ 'client': 'mobile',
+ 'debug': '1',
+ });
+ },
+ );
+
+ test(
+ 'a build that cannot say, or is slow to, still dials without it',
+ () async {
+ final unchanged = {'autonomousEnv': 'test', 'client': 'mobile'};
+ expect(
+ await dialled(() async => throw StateError('no version')),
+ unchanged,
+ );
+ relay.dialledUris.clear();
+ expect(
+ await dialled(() => Completer<ClientBuild>().future),
+ unchanged,
+ );
+ },
+ );
+ });
+
test(
'what was asked before it was ready goes once it is, sealed',
() async {
diff --git a/mobile/test/ws/ws_pool_test.dart b/mobile/test/ws/ws_pool_test.dart
index 0ad9c09cb..fb7d8aa9e 100644
--- a/mobile/test/ws/ws_pool_test.dart
+++ b/mobile/test/ws/ws_pool_test.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/client_build.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/ws/ws_pool.dart';
@@ -46,6 +47,23 @@ void main() {
expect(conn.endpointKey, 'cloud:ws://fixture.invalid:test');
});
+ test('every connection is given the build to tell the relay about', () {
+ Future<ClientBuild> build() async => const ClientBuild(release: '1.0.9');
+ final tagged = WsPool(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ accessTokenProvider: (_, _) => Completer<String>().future,
+ clientBuild: build,
+ onAuthFailure: (_) {},
+ onStatus: (_, _) {},
+ onEvent: (_, _) {},
+ );
+ addTearDown(tagged.closeAll);
+ expect(tagged.connFor('a').clientBuild, same(build));
+ expect(tagged.connFor('b').clientBuild, same(build));
+ expect(pool.connFor('a').clientBuild, isNull);
+ });
+
test('its callbacks carry the machine they are for', () async {
final conn = pool.connFor('m');
events.clear();
diff --git a/mobile/test_driver/first_task_driver.dart b/mobile/test_driver/first_task_driver.dart
new file mode 100644
index 000000000..b72b68271
--- /dev/null
+++ b/mobile/test_driver/first_task_driver.dart
@@ -0,0 +1,20 @@
+// A command-line driver; printing is its interface.
+// ignore_for_file: avoid_print
+
+import 'dart:io';
+
+import 'package:integration_test/integration_test_driver_extended.dart';
+
+/// Host side of `integration_test/first_task_test.dart`: writes each screenshot the app takes into
+/// `HARNESS_JOURNEY_OUT` (default `build/journey/`), named `<step>-<HARNESS_PHONE>.png`.
+Future<void> main() => integrationDriver(
+ onScreenshot: (name, bytes, [args]) async {
+ final root = Platform.environment['HARNESS_JOURNEY_OUT'] ?? 'build/journey';
+ final phone = Platform.environment['HARNESS_PHONE'] ?? 'phone';
+ final file = File('$root/$name-$phone.png');
+ await file.parent.create(recursive: true);
+ await file.writeAsBytes(bytes);
+ print('[journey] $name-$phone');
+ return true;
+ },
+);