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.

Phone app 10/10, Add Phone, scan to sign in (#387)

Dee244cfe717b28
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 3d278c2ba..2cd25dbfa 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -629,3 +629,27 @@ model Desk {
@@map("desks")
}
+
+/// A sign-in Harness issued ITSELF rather than through the Autonomous account service — today only
+/// to a phone that scanned a signed-in computer's Add Phone QR (lib/harnessSession.ts). The account
+/// service has no way for one signed-in device to sign in another, so the computer asks for a
+/// one-time handoff code, the QR carries it, and the phone trades it for this session.
+///
+/// Only a HASH of the refresh token is stored: a dump of this collection must not be a key store.
+/// The access token lives in Redis beside it, an hour at a time. Revoking is setting `revokedAt`;
+/// every request reads it, so it takes effect at once.
+model HarnessSession {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ userId String
+ refreshHash String @unique
+ /// What the device calls itself ("Dee's iPhone"), for a list of signed-in devices.
+ label String
+ createdAt DateTime @default(now())
+ lastUsedAt DateTime @default(now())
+ /// Slides forward on every refresh: a phone in use stays signed in, one left in a drawer does not.
+ expiresAt DateTime
+ revokedAt DateTime?
+
+ @@index([userId])
+ @@map("harness_sessions")
+}
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 860706800..0214888b6 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -169,7 +169,7 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
const countryCode = countryCodeFromHeaders(req.headers)
void (async () => {
let user
- try { user = await authenticateAccessToken(accessToken, autonomousEnv) } catch (err) {
+ try { user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: false }) } catch (err) {
if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {
try { socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }
socket.destroy()
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index f2e554eaa..1594fb851 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -339,7 +339,7 @@ export function handleDeviceUpgrade(req: IncomingMessage, socket: Duplex, head:
void (async () => {
let user
try {
- user = await authenticateAccessToken(accessToken, autonomousEnv)
+ user = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: false })
} catch (err) {
if (err instanceof SsoAuthError && (err.code === 'AUTONOMOUS_ENV_MISMATCH' || err.code === 'AUTONOMOUS_ENV_NOT_ALLOWED')) {
denyWith(403, 'Forbidden')
diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.ts
new file mode 100644
index 000000000..1c1d24c2d
--- /dev/null
+++ b/backend/src/lib/harnessSession.test.ts
@@ -0,0 +1,212 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import Fastify, { type FastifyInstance } from 'fastify'
+
+// In-memory stand-ins for Redis and the sessions collection, so the real handoff, refresh and
+// authentication code runs end to end — only the stores are fake.
+const fakes = vi.hoisted(() => {
+ const redis = new Map<string, string>()
+ const ttls = new Map<string, number>()
+ let failRedis = false
+ const sessions: Array<Record<string, unknown> & { id: string }> = []
+ const users = new Map<string, Record<string, unknown>>()
+ const pick = (where: Record<string, unknown>) =>
+ sessions.find((s) => Object.entries(where).every(([k, v]) => s[k] === v)) ?? null
+ const pub = {
+ set: vi.fn(async (key: string, value: string, _ex: string, ttl: number) => {
+ if (failRedis) throw new Error('redis down')
+ redis.set(key, value); ttls.set(key, ttl); return 'OK'
+ }),
+ get: vi.fn(async (key: string) => {
+ if (failRedis) throw new Error('redis down')
+ return redis.get(key) ?? null
+ }),
+ // GET then DEL, in one transaction — how a redeem spends a code.
+ multi: vi.fn(() => {
+ const ops: Array<() => unknown> = []
+ const chain = {
+ get: (key: string) => { ops.push(() => redis.get(key) ?? null); return chain },
+ del: (key: string) => { ops.push(() => (redis.delete(key) ? 1 : 0)); return chain },
+ exec: async () => ops.map((op) => [null, op()]),
+ }
+ return chain
+ }),
+ }
+ const harnessSession = {
+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
+ const row = { id: `s${sessions.length + 1}`, revokedAt: null, createdAt: new Date(), lastUsedAt: new Date(), ...data }
+ sessions.push(row); return row
+ }),
+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => pick(where)),
+ update: vi.fn(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
+ const row = pick(where)!; Object.assign(row, data); return row
+ }),
+ updateMany: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {
+ const rows = sessions.filter((s) => Object.entries(where).every(([k, v]) => s[k] === v))
+ rows.forEach((r) => Object.assign(r, data)); return { count: rows.length }
+ }),
+ }
+ return {
+ redis, ttls, sessions, users, pub, harnessSession,
+ setFailRedis: (v: boolean) => { failRedis = v },
+ get: vi.fn(async (id: string) => users.get(id) ?? null),
+ findByEmail: vi.fn(),
+ }
+})
+
+vi.mock('./bus.js', () => ({ pub: fakes.pub }))
+vi.mock('./prisma.js', () => ({ prisma: { harnessSession: fakes.harnessSession } }))
+vi.mock('../services/UserService.js', () => ({
+ userService: { get: fakes.get, findByEmail: fakes.findByEmail },
+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),
+ isProvisionalUserEmail: () => false,
+}))
+vi.mock('../services/index.js', () => ({ userService: { get: fakes.get, toPublic: (u: unknown) => u } }))
+
+import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'
+import { HANDOFF_TTL_SEC, redeemHandoff, startHandoff } from './harnessSession.js'
+import { authRoutes } from '../routes/auth.js'
+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'
+import { errorHandler } from '../middlewares/errorHandler.js'
+
+const USER = { id: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }
+
+beforeEach(() => {
+ fakes.redis.clear(); fakes.ttls.clear(); fakes.sessions.length = 0; fakes.users.clear()
+ fakes.users.set(USER.id, USER)
+ fakes.setFailRedis(false)
+ vi.clearAllMocks()
+})
+
+describe('scan to sign in — the handoff', () => {
+ it('signs the phone in as the account that minted the code, and never asks the account service', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch')
+ const { code, expiresIn } = await startHandoff(USER.id)
+ expect(code).toMatch(/^hnh_[A-Za-z0-9_-]{43}$/)
+ expect(expiresIn).toBe(HANDOFF_TTL_SEC)
+ // Only the hash is kept, and it dies on its own.
+ expect([...fakes.redis.keys()].some((k) => k.includes(code))).toBe(false)
+ expect([...fakes.ttls.values()]).toEqual([HANDOFF_TTL_SEC])
+
+ const tokens = await redeemHandoff(code, "Dee's iPhone")
+ expect(tokens).toMatchObject({ expiresIn: 3600, autonomousEnv: 'prod' })
+ expect(tokens!.token).toMatch(/^hna_/)
+ expect(tokens!.refreshToken).toMatch(/^hnr_/)
+ expect(fakes.sessions[0]).toMatchObject({ userId: USER.id, label: "Dee's iPhone" })
+ expect(fakes.sessions[0].refreshHash).not.toBe(tokens!.refreshToken)
+
+ await expect(authenticateAccessToken(tokens!.token)).resolves.toEqual({
+ sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod', harnessSessionId: 's1',
+ })
+ expect(fetchSpy).not.toHaveBeenCalled()
+ expect(fakes.findByEmail).not.toHaveBeenCalled()
+ fetchSpy.mockRestore()
+ })
+
+ it('works once: a second phone scanning the same QR gets nothing', async () => {
+ const { code } = await startHandoff(USER.id)
+ expect(await redeemHandoff(code, 'first')).not.toBeNull()
+ expect(await redeemHandoff(code, 'second')).toBeNull()
+ expect(fakes.sessions).toHaveLength(1)
+ })
+
+ it('refuses a code it never issued, or one that is not shaped like one', async () => {
+ expect(await redeemHandoff(`hnh_${'A'.repeat(43)}`, 'x')).toBeNull()
+ expect(await redeemHandoff('hnh_short', 'x')).toBeNull()
+ expect(fakes.pub.multi).toHaveBeenCalledTimes(1) // the malformed one never reached Redis
+ })
+
+ it('a phone session is a viewer: machine connections refuse it', async () => {
+ const { code } = await startHandoff(USER.id)
+ const { token } = (await redeemHandoff(code, 'phone'))!
+ await expect(authenticateAccessToken(token, 'prod', { allowHarnessSession: false }))
+ .rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ })
+
+ it('an outage is not a bad token: Redis down answers AUTH_SERVICE_UNAVAILABLE, not a sign-out', async () => {
+ const { code } = await startHandoff(USER.id)
+ const { token } = (await redeemHandoff(code, 'phone'))!
+ fakes.setFailRedis(true)
+ const err = await authenticateAccessToken(token).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(SsoAuthError)
+ expect(err).toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })
+ })
+
+ it('an access token nobody issued is simply invalid', async () => {
+ await expect(authenticateAccessToken(`hna_${'B'.repeat(43)}`)).rejects.toMatchObject({ code: 'INVALID_TOKEN' })
+ })
+})
+
+describe('scan to sign in — the routes', () => {
+ let app: FastifyInstance
+ const signedIn = { sub: USER.id, email: USER.email, role: 'user', autonomousEnv: 'prod' as const }
+
+ async function build(authenticate: typeof authenticateAccessToken): Promise<FastifyInstance> {
+ const server = Fastify()
+ server.setErrorHandler(errorHandler)
+ registerAuthMiddleware(server, authenticate)
+ await server.register(authRoutes)
+ await server.ready()
+ return server
+ }
+
+ beforeEach(async () => {
+ // The computer's Autonomous token is faked; a Harness token goes through the real check.
+ app = await build(async (token, env, opts) =>
+ token === 'sso-token' ? signedIn : authenticateAccessToken(token, env, opts))
+ })
+
+ it('the computer mints a code, the phone redeems it, refreshes, and signs out', async () => {
+ const minted = await app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization: 'Bearer sso-token' } })
+ expect(minted.statusCode).toBe(200)
+ const { code } = minted.json().data
+
+ // No bearer: the code is the credential.
+ const redeemed = await app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload: { code, label: "Dee's iPhone" } })
+ expect(redeemed.statusCode).toBe(200)
+ const { token, refreshToken } = redeemed.json().data
+
+ const me = await app.inject({ method: 'GET', url: '/api/auth/me', headers: { authorization: `Bearer ${token}` } })
+ expect(me.statusCode).toBe(200)
+ expect(me.json().data.user.email).toBe(USER.email)
+
+ const refreshed = await app.inject({ method: 'POST', url: '/api/auth/refresh', payload: { refreshToken } })
+ expect(refreshed.statusCode).toBe(200)
+ const renewed = refreshed.json().data
+ expect(renewed.token).toMatch(/^hna_/)
+ expect(renewed.token).not.toBe(token)
+ expect(renewed.refreshToken).toBeUndefined() // not rotated: the phone keeps the one it has
+
+ expect((await app.inject({ method: 'POST', url: '/api/auth/revoke', payload: { refreshToken } })).statusCode).toBe(200)
+ // Signed out at once: the refresh token and BOTH access tokens it was ever given.
+ const again = await app.inject({ method: 'POST', url: '/api/auth/refresh', payload: { refreshToken } })
+ expect(again.statusCode).toBe(401)
+ expect(again.json().error.code).toBe('REFRESH_TOKEN_INVALID')
+ for (const t of [token, renewed.token]) {
+ const res = await app.inject({ method: 'GET', url: '/api/auth/me', headers: { authorization: `Bearer ${t}` } })
+ expect(res.statusCode).toBe(401)
+ }
+ })
+
+ it('minting needs a signed-in computer', async () => {
+ const res = await app.inject({ method: 'POST', url: '/api/auth/handoff' })
+ expect(res.statusCode).toBe(401)
+ })
+
+ it('a phone signed in by a scan cannot mint codes of its own', async () => {
+ const { code } = await startHandoff(USER.id)
+ const { token } = (await redeemHandoff(code, 'phone'))!
+ const res = await app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization: `Bearer ${token}` } })
+ expect(res.statusCode).toBe(403)
+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')
+ })
+
+ it('a spent or unknown code is one answer, 401', async () => {
+ const { code } = await startHandoff(USER.id)
+ await app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload: { code } })
+ for (const c of [code, 'nonsense', '']) {
+ const res = await app.inject({ method: 'POST', url: '/api/auth/handoff/redeem', payload: { code: c } })
+ expect(res.statusCode).toBe(401)
+ expect(res.json().error.code).toBe('HANDOFF_INVALID')
+ }
+ })
+})
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
new file mode 100644
index 000000000..2a2453d1a
--- /dev/null
+++ b/backend/src/lib/harnessSession.ts
@@ -0,0 +1,178 @@
+import { pub } from './bus.js'
+import { prisma } from './prisma.js'
+import { userService } from '../services/UserService.js'
+import { storedAutonomousEnvironment, type AutonomousEnvironment } from './autonomousEnvironment.js'
+import { SsoAuthError, type AuthUser } from './ssoAuth.js'
+import {
+ HARNESS_ACCESS_PREFIX,
+ HARNESS_HANDOFF_PREFIX,
+ HARNESS_REFRESH_PREFIX,
+ harnessTokenHash,
+ isHarnessHandoffCode,
+ isHarnessRefreshToken,
+ newHarnessToken,
+} from './harnessTokenFormat.js'
+
+/**
+ * Sign-ins Harness issues itself — so a phone that scans a signed-in computer's Add Phone QR is
+ * signed in by the scan, with no emailed code.
+ *
+ * The Autonomous account service is the only thing that signs a person in, and it has no way for
+ * one signed-in device to sign in another (its grants are password, otp, refresh_token and
+ * social_token). So the computer, already signed in through it, asks here for a one-time HANDOFF
+ * code; the QR carries it; the phone trades it for a session of Harness's own. Everything that
+ * authenticates goes through `authenticateAccessToken` (lib/ssoAuth.ts), which sends a Harness
+ * token here and every other token to the account service as before.
+ *
+ * computer → POST /api/auth/handoff (signed in) → { code, expiresIn } → into the QR
+ * phone → POST /api/auth/handoff/redeem (no auth) → { token, refreshToken, expiresIn }
+ * phone → POST /api/auth/refresh (no auth) → { token, expiresIn }
+ *
+ * The handoff code is the whole credential, so it is 32 random bytes, lives [HANDOFF_TTL_SEC], and
+ * is spent by the first redeem. It rides in the QR link's fragment, which a browser never
+ * sends, so it reaches this server only in the redeem's body.
+ *
+ * Nothing here is the person's Autonomous credential, and nothing here reaches the account service:
+ * a route that forwards the caller's token there (billing, via lib/autonomousBff.ts) cannot be used
+ * from a Harness session. The phone uses none of them.
+ */
+
+/** How long a code in a QR stays good. The Add Phone dialog asks for a new one every minute. */
+export const HANDOFF_TTL_SEC = 90
+export const HARNESS_ACCESS_TTL_SEC = 60 * 60
+/** Idle lifetime: every refresh moves it on, so only a phone left unused this long is signed out. */
+const SESSION_IDLE_DAYS = 90
+
+const handoffKey = (hash: string): string => `hnauth:handoff:${hash}`
+const accessKey = (hash: string): string => `hnauth:access:${hash}`
+
+const sessionExpiry = (): Date => new Date(Date.now() + SESSION_IDLE_DAYS * 24 * 60 * 60 * 1000)
+
+export interface HarnessTokens {
+ token: string
+ /** Only on redeem: a refresh keeps the refresh token it was given. */
+ refreshToken?: string
+ expiresIn: number
+ autonomousEnv: AutonomousEnvironment
+}
+
+/** A one-time code a signed-in computer puts in its Add Phone QR. */
+export async function startHandoff(userId: string): Promise<{ code: string; expiresIn: number }> {
+ const code = newHarnessToken(HARNESS_HANDOFF_PREFIX)
+ await pub.set(handoffKey(harnessTokenHash(code)), userId, 'EX', HANDOFF_TTL_SEC)
+ return { code, expiresIn: HANDOFF_TTL_SEC }
+}
+
+/**
+ * Spend [code] and sign [label]'s device in as the account that minted it. Null for a code that is
+ * malformed, expired or already spent — one answer for all three, so a caller learns nothing.
+ */
+export async function redeemHandoff(code: string, label: string): Promise<HarnessTokens | null> {
+ if (!isHarnessHandoffCode(code)) return null
+ // Read and spend in ONE step: two phones racing the same QR must not both get in. MULTI rather
+ // than GETDEL, which a Redis older than 6.2 does not have.
+ const key = handoffKey(harnessTokenHash(code))
+ const [read] = (await pub.multi().get(key).del(key).exec()) ?? []
+ if (!read || read[0]) throw read?.[0] ?? new Error('handoff redeem: no reply from Redis')
+ const userId = read[1]
+ if (typeof userId !== 'string' || !userId) return null
+ const user = await userService.get(userId)
+ if (!user) return null
+ const refreshToken = newHarnessToken(HARNESS_REFRESH_PREFIX)
+ const session = await prisma.harnessSession.create({
+ data: {
+ userId,
+ refreshHash: harnessTokenHash(refreshToken),
+ label,
+ expiresAt: sessionExpiry(),
+ },
+ })
+ return {
+ token: await issueAccess(session.id, userId),
+ refreshToken,
+ expiresIn: HARNESS_ACCESS_TTL_SEC,
+ autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
+ }
+}
+
+/**
+ * A new access token for the session [refreshToken] belongs to, or null when that session is gone
+ * (unknown, revoked, idle past its lifetime, or its user deleted) — the caller's 401.
+ *
+ * The refresh token is not rotated. Rotation is only as good as its reuse detection, and a phone
+ * that loses the response to a refresh would then present the old token and be signed out for a
+ * dropped packet. The token is 256 bits, stored hashed, and revocable; that is the protection.
+ */
+export async function refreshHarnessSession(refreshToken: string): Promise<HarnessTokens | null> {
+ if (!isHarnessRefreshToken(refreshToken)) return null
+ const session = await prisma.harnessSession.findUnique({
+ where: { refreshHash: harnessTokenHash(refreshToken) },
+ })
+ if (!session || session.revokedAt || session.expiresAt <= new Date()) return null
+ const user = await userService.get(session.userId)
+ if (!user) return null
+ await prisma.harnessSession.update({
+ where: { id: session.id },
+ data: { lastUsedAt: new Date(), expiresAt: sessionExpiry() },
+ })
+ return {
+ token: await issueAccess(session.id, session.userId),
+ expiresIn: HARNESS_ACCESS_TTL_SEC,
+ autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
+ }
+}
+
+/** Sign out: the session's refresh token stops working, and so, at once, does its access token. */
+export async function revokeHarnessSession(refreshToken: string): Promise<void> {
+ if (!isHarnessRefreshToken(refreshToken)) return
+ await prisma.harnessSession.updateMany({
+ where: { refreshHash: harnessTokenHash(refreshToken), revokedAt: null },
+ data: { revokedAt: new Date() },
+ })
+}
+
+async function issueAccess(sessionId: string, userId: string): Promise<string> {
+ const token = newHarnessToken(HARNESS_ACCESS_PREFIX)
+ await pub.set(
+ accessKey(harnessTokenHash(token)),
+ JSON.stringify({ sessionId, userId }),
+ 'EX',
+ HARNESS_ACCESS_TTL_SEC,
+ )
+ return token
+}
+
+/**
+ * The account a Harness access token speaks for. The session is read on every call, so a revoked
+ * one stops at once rather than when its access token runs out.
+ *
+ * Only a token that is not good is `INVALID_TOKEN`. Redis or Mongo failing is
+ * `AUTH_SERVICE_UNAVAILABLE` — the caller's 503, not its 401 — because a 401 sends the phone to
+ * refresh and, failing that, to sign in again, over what is only an outage.
+ */
+export async function authenticateHarnessAccessToken(token: string): Promise<AuthUser> {
+ const invalid = (): SsoAuthError => new SsoAuthError('Invalid or expired access token', 'INVALID_TOKEN')
+ let user: Awaited<ReturnType<typeof userService.get>>
+ let sessionId: string
+ try {
+ const raw = await pub.get(accessKey(harnessTokenHash(token)))
+ if (!raw) throw invalid()
+ const held = JSON.parse(raw) as { sessionId?: unknown; userId?: unknown }
+ if (typeof held.sessionId !== 'string' || typeof held.userId !== 'string') throw invalid()
+ sessionId = held.sessionId
+ const session = await prisma.harnessSession.findUnique({ where: { id: sessionId } })
+ if (!session || session.revokedAt || session.userId !== held.userId) throw invalid()
+ user = await userService.get(held.userId)
+ } catch (err) {
+ if (err instanceof SsoAuthError) throw err
+ throw new SsoAuthError('Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE')
+ }
+ if (!user) throw invalid()
+ return {
+ sub: user.id,
+ email: user.email,
+ role: user.role,
+ autonomousEnv: storedAutonomousEnvironment(user.autonomousEnv),
+ harnessSessionId: sessionId,
+ }
+}
diff --git a/backend/src/lib/harnessTokenFormat.ts b/backend/src/lib/harnessTokenFormat.ts
new file mode 100644
index 000000000..059eb16b1
--- /dev/null
+++ b/backend/src/lib/harnessTokenFormat.ts
@@ -0,0 +1,31 @@
+import { createHash, randomBytes } from 'node:crypto'
+
+/**
+ * The shape of the tokens Harness issues itself (lib/harnessSession.ts), apart from the store behind
+ * them — so the auth path everything imports (lib/ssoAuth.ts) can tell one from an Autonomous token
+ * without importing Redis, which connects on import.
+ *
+ * A prefix, then 32 random bytes: an Autonomous access token is a JWT (`eyJ…`), so the two can never
+ * be mistaken for each other, and a token that turns up in a log says where it came from.
+ */
+export const HARNESS_ACCESS_PREFIX = 'hna_'
+export const HARNESS_REFRESH_PREFIX = 'hnr_'
+export const HARNESS_HANDOFF_PREFIX = 'hnh_'
+
+const BODY = /^[A-Za-z0-9_-]{43}$/
+
+const shaped = (token: unknown, prefix: string): token is string =>
+ typeof token === 'string' && token.startsWith(prefix) && BODY.test(token.slice(prefix.length))
+
+export const isHarnessAccessToken = (token: unknown): token is string => shaped(token, HARNESS_ACCESS_PREFIX)
+export const isHarnessRefreshToken = (token: unknown): token is string => shaped(token, HARNESS_REFRESH_PREFIX)
+export const isHarnessHandoffCode = (token: unknown): token is string => shaped(token, HARNESS_HANDOFF_PREFIX)
+
+export function newHarnessToken(prefix: string): string {
+ return prefix + randomBytes(32).toString('base64url')
+}
+
+/** Only this is ever stored: a dump of Redis or Mongo must not be a key store. */
+export function harnessTokenHash(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.ts
index 830afe267..9566ff32c 100644
--- a/backend/src/lib/ssoAuth.ts
+++ b/backend/src/lib/ssoAuth.ts
@@ -10,6 +10,7 @@ import {
type AutonomousEnvironment,
} from './autonomousEnvironment.js'
import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'
+import { isHarnessAccessToken } from './harnessTokenFormat.js'
/** Internal identity attached to authenticated backend requests and user WebSockets. */
export interface AuthUser {
@@ -17,6 +18,8 @@ export interface AuthUser {
email: string
role: string
autonomousEnv: AutonomousEnvironment
+ /** Set when the token is one Harness issued itself (lib/harnessSession.ts), not an Autonomous one. */
+ harnessSessionId?: string
}
export interface SsoProfile {
@@ -164,6 +167,9 @@ function accessTokenMetadata(token: string): { name?: string; roles?: string[] }
/** Validate the token, mirror the external identity, then return the app's internal user identity. */
/**
+ * @param allowHarnessSession Accept a Harness-issued token (lib/harnessSession.ts). FALSE where the
+ * caller connects AS a machine — a phone's session is a viewer's, never a daemon's.
+ *
* @param enforceEnv Gate the caller on the account plane their user row is stamped with. TRUE for the
* web, which can be pointed at either plane and must not let the two identities cross.
*
@@ -179,8 +185,16 @@ function accessTokenMetadata(token: string): { name?: string; roles?: string[] }
export async function authenticateAccessToken(
token: string,
autonomousEnv: AutonomousEnvironment = 'prod',
- { enforceEnv = true }: { enforceEnv?: boolean } = {},
+ { enforceEnv = true, allowHarnessSession = true }: { enforceEnv?: boolean; allowHarnessSession?: boolean } = {},
): Promise<AuthUser> {
+ // A sign-in Harness issued itself — a phone signed in by scanning a computer's QR. It names its
+ // user outright, so there is no account plane to choose and nothing to ask the account service.
+ // Loaded on first use: that module holds Redis, which connects on import (see the store above).
+ if (isHarnessAccessToken(token)) {
+ if (!allowHarnessSession) throw new SsoAuthError('This connection needs an Autonomous sign-in', 'INVALID_TOKEN')
+ const { authenticateHarnessAccessToken } = await import('./harnessSession.js')
+ return authenticateHarnessAccessToken(token)
+ }
const profile = await profileCache.resolve(token, autonomousEnv, () => fetchSsoProfile(token, autonomousEnv))
const metadata = accessTokenMetadata(token)
const email = normalizeUserEmail(profile.email)
diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.ts
index 93f4b2a07..86d9a809c 100644
--- a/backend/src/middlewares/authMiddleware.ts
+++ b/backend/src/middlewares/authMiddleware.ts
@@ -20,6 +20,11 @@ export function shouldSkipAuth(url: string): boolean {
path === '/api/auth/authorize-native' ||
path === '/api/auth/exchange' ||
path === '/api/auth/refresh' ||
+ // Scan to sign in: the phone has no token yet, and the one-time code it carries IS the credential
+ // (lib/harnessSession.ts). Revoke takes the refresh token, the same authority /refresh does.
+ // `/api/auth/handoff` itself is NOT listed: minting a code needs the computer's sign-in.
+ path === '/api/auth/handoff/redeem' ||
+ path === '/api/auth/revoke' ||
path === '/api/auth/logout-url' ||
// Public app-deploy registration — agent-key gated (x-api-key), self-validated in its
// own preHandler (agentAuth). Called by the agent-node's domain MCP, not the web SSO token.
diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts
index 311e48b63..d5afbb2c7 100644
--- a/backend/src/routes/auth.ts
+++ b/backend/src/routes/auth.ts
@@ -21,6 +21,8 @@ import {
type SsoTx,
} from '../lib/sso.js'
import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'
+import { isHarnessRefreshToken } from '../lib/harnessTokenFormat.js'
+import { redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff } from '../lib/harnessSession.js'
export async function authRoutes(app: FastifyInstance): Promise<void> {
// 1) Start login (web-driven). The web fetches this (XHR, so the API URL never hits the address
@@ -106,6 +108,18 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
const refreshToken = typeof req.body?.refreshToken === 'string' ? req.body.refreshToken.trim() : ''
if (!refreshToken) return sendError(reply, 'refresh token is required', 'INVALID_REFRESH_REQUEST', 400)
+ // A session Harness issued itself (a phone signed in by a QR) renews here, not at the SSO.
+ if (isHarnessRefreshToken(refreshToken)) {
+ try {
+ const tokens = await refreshHarnessSession(refreshToken)
+ if (!tokens) return sendError(reply, 'Refresh token is invalid or expired', 'REFRESH_TOKEN_INVALID', 401)
+ return sendSuccess(reply, tokens)
+ } catch (e) {
+ logger.error('harness session refresh failed', e)
+ return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
+ }
+ }
+
let autonomousEnv: AutonomousEnvironment
try { autonomousEnv = parseAutonomousEnvironment(req.body?.autonomousEnv) } catch {
return sendError(reply, 'invalid Autonomous environment', 'INVALID_AUTONOMOUS_ENV', 400)
@@ -197,6 +211,51 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
})
})
+ // 4) Scan to sign in (lib/harnessSession.ts). A signed-in computer asks for a one-time code for
+ // its Add Phone QR; the phone that scans it redeems the code for a session of its own. Only an
+ // Autonomous sign-in can hand one off — a phone's session cannot mint more of itself.
+ app.post('/api/auth/handoff', async (req, reply) => {
+ if (req.user!.harnessSessionId) {
+ return sendError(reply, 'Add a phone from a computer signed in to Harness', 'HANDOFF_NOT_ALLOWED', 403)
+ }
+ try {
+ return sendSuccess(reply, await startHandoff(req.user!.sub))
+ } catch (e) {
+ logger.error('handoff start failed', e)
+ return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
+ }
+ })
+
+ // Unauthenticated BY DESIGN, like /refresh: the code is the credential. It is 32 random bytes,
+ // good for one redeem within 90 seconds, so there is nothing to guess and nothing to replay.
+ app.post<{ Body: { code?: string; label?: string } }>('/api/auth/handoff/redeem', async (req, reply) => {
+ const code = typeof req.body?.code === 'string' ? req.body.code.trim() : ''
+ const label = (typeof req.body?.label === 'string' ? req.body.label.trim() : '').slice(0, 80) || 'phone'
+ try {
+ const tokens = await redeemHandoff(code, label)
+ // Expired, spent, or never ours — one answer, so a caller learns nothing from which.
+ if (!tokens) return sendError(reply, 'That code has expired. Scan the new one.', 'HANDOFF_INVALID', 401)
+ logger.info('handoff redeemed', { label })
+ return sendSuccess(reply, tokens)
+ } catch (e) {
+ logger.error('handoff redeem failed', e)
+ return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
+ }
+ })
+
+ // Sign a Harness-issued session out. Knowing the refresh token is the authority, as for /refresh;
+ // an Autonomous refresh token is not ours to revoke and is ignored.
+ app.post<{ Body: { refreshToken?: string } }>('/api/auth/revoke', async (req, reply) => {
+ const refreshToken = typeof req.body?.refreshToken === 'string' ? req.body.refreshToken.trim() : ''
+ try {
+ await revokeHarnessSession(refreshToken)
+ return sendSuccess(reply, { revoked: true })
+ } catch (e) {
+ logger.error('harness session revoke failed', e)
+ return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
+ }
+ })
+
// Current session's mirrored user, SSO-access-token gated by the auth middleware.
app.get('/api/auth/me', async (req, reply) => {
const user = await userService.get(req.user!.sub)
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 7ce9c8d8d..a198ad924 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -1312,6 +1312,9 @@ async function fallbackRegister(input, engine, tmuxPane) {
// Fill-only, exactly as the daemon's own registry treats it.
hermesHome: hermesHome || (typeof existing?.hermesHome === 'string' && existing.hermesHome ? existing.hermesHome : null),
...(existing?.bypassPermission === true ? { bypassPermission: true } : {}),
+ // When an app last opened this agent (RegisteredSession.lastOpenedAt): a fact about the person,
+ // not the process, and the daemon's own rebuild carries it the same way.
+ ...(Number.isSafeInteger(existing?.lastOpenedAt) && existing.lastOpenedAt > 0 ? { lastOpenedAt: existing.lastOpenedAt } : {}),
}
const entry = {
schemaVersion: 2,
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 89d0ddccc..e9866d161 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -4,7 +4,7 @@ import { readFileSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs'
import { homedir, tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
-import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow, grokHistoryPage } from './backendSocket.js'
+import { AGENT_OPENED_THROTTLE_MS, BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow, grokHistoryPage } from './backendSocket.js'
import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'
import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
@@ -90,6 +90,118 @@ describe('confirmed harness pause replies', () => {
})
})
+/**
+ * `agent_update {opened: true}` — an app opened this agent, so the daemon that owns it stamps
+ * `lastOpenedAt` on its own clock and tells every app, which then all sort by the same "last used".
+ */
+describe('agent_update opened: one "last used" for every app', () => {
+ const OPENED = Date.UTC(2026, 8, 26, 9, 30)
+ const iso = (ms: number) => new Date(ms).toISOString()
+ let socket: BackendSocket
+ let frames: any[]
+ let agentId = ''
+
+ beforeEach(() => {
+ vi.restoreAllMocks()
+ // Only the clock: the dispatch queue and vi.waitFor still run on real timers.
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(OPENED)
+ socket = new BackendSocket('fixture')
+ frames = []
+ socket.registerLocalClient('local:opened', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ agentId = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7301' }], cwd: '/tmp/opened' })!.agentId
+ })
+
+ afterEach(async () => {
+ registry.removeAgent(agentId)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ await socket.stop()
+ })
+
+ const replyTo = (requestId: string) => frames.find(frame => frame.type === 'agent_update_result' && frame.payload.requestId === requestId)?.payload
+ /** What `handleLocalFrame` queues for a window on this computer, awaited so the clock stays put. */
+ async function update(payload: Record<string, unknown>, requestId: string): Promise<any> {
+ await (socket as any).dispatchDown({ type: 'agent_update', payload: { requestId, ...payload } }, 'local:opened', 'local')
+ return replyTo(requestId)
+ }
+ const pushes = () => frames.filter(frame => frame.type === 'agent_synced')
+
+ it('arrives through the desktop window’s own door (localWsServer → handleLocalFrame)', async () => {
+ socket.handleLocalFrame('local:opened', { type: 'agent_update', payload: { requestId: 'door', agentId, opened: true } })
+ await vi.waitFor(() => expect(replyTo('door')).toBeTruthy())
+ // vi.waitFor moves a faked clock while it polls, so the stamp is read back rather than predicted.
+ const stamped = registry.byAgent(agentId)?.lastOpenedAt
+ expect(stamped).toBeGreaterThanOrEqual(OPENED)
+ expect(replyTo('door').agent.lastOpenedAt).toBe(iso(stamped!))
+ expect(pushes()).toHaveLength(1)
+ })
+
+ it('stamps the owner’s clock, answers with the frame, and pushes it to every app but the dial', async () => {
+ const commander = vi.spyOn(socket, 'sendCommander')
+ // A time from the client is never taken: two apps whose clocks disagree would order the list differently.
+ const reply = await update({ agentId, opened: true, lastOpenedAt: '2001-01-01T00:00:00.000Z', at: 1 }, 'open-1')
+ expect(reply.error).toBeUndefined()
+ expect(reply.agent).toMatchObject({ id: agentId, lastOpenedAt: iso(OPENED) })
+ expect(registry.byAgent(agentId)?.lastOpenedAt).toBe(OPENED)
+ expect(pushes()).toHaveLength(1)
+ expect(pushes()[0].payload.agent).toEqual(reply.agent)
+ expect(commander).not.toHaveBeenCalled()
+ })
+
+ it('answers a repeat inside the throttle with the current frame, and stamps and tells no one', async () => {
+ await update({ agentId, opened: true }, 'open-1')
+ vi.setSystemTime(OPENED + AGENT_OPENED_THROTTLE_MS - 1)
+ const repeat = await update({ agentId, opened: true }, 'open-2')
+ expect(repeat.agent).toMatchObject({ id: agentId, lastOpenedAt: iso(OPENED) })
+ expect(registry.byAgent(agentId)?.lastOpenedAt).toBe(OPENED)
+ expect(pushes()).toHaveLength(1)
+
+ vi.setSystemTime(OPENED + AGENT_OPENED_THROTTLE_MS)
+ const later = await update({ agentId, opened: true }, 'open-3')
+ expect(later.agent.lastOpenedAt).toBe(iso(OPENED + AGENT_OPENED_THROTTLE_MS))
+ expect(pushes()).toHaveLength(2)
+ expect(pushes()[1].payload.agent.lastOpenedAt).toBe(iso(OPENED + AGENT_OPENED_THROTTLE_MS))
+ })
+
+ it('still answers MISSING_UPDATE for a request that asks for nothing, and stamps nothing', async () => {
+ expect(await update({ agentId }, 'empty')).toMatchObject({ error: 'MISSING_UPDATE' })
+ expect(await update({ agentId, opened: false }, 'not-opened')).toMatchObject({ error: 'MISSING_UPDATE' })
+ expect(await update({ agentId, opened: 'yes' }, 'truthy')).toMatchObject({ error: 'MISSING_UPDATE' })
+ expect(await update({ opened: true }, 'no-agent')).toMatchObject({ error: 'MISSING_AGENT_ID' })
+ expect(await update({ agentId: 'nobody', opened: true }, 'unknown')).toMatchObject({ error: 'AGENT_NOT_FOUND' })
+ expect(registry.byAgent(agentId)?.lastOpenedAt).toBeUndefined()
+ expect(pushes()).toHaveLength(0)
+ })
+
+ it('stamps but does not push an agent whose terminal this daemon cannot see', async () => {
+ // Such a row is not in agents_list; a push would put it back on every screen (cli.ts syncSession).
+ registry.setTerminalAvailable(agentId, false)
+ const reply = await update({ agentId, opened: true }, 'hidden')
+ expect(reply.agent.lastOpenedAt).toBe(iso(OPENED))
+ expect(pushes()).toHaveLength(0)
+ })
+
+ it('takes the open from a sealed remote session too — the phone, or another computer’s desktop via its relay', async () => {
+ const internals = socket as any
+ const clear = { type: 'agent_update', payload: { requestId: 'remote-1', agentId, opened: true } }
+ vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(clear)
+ vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)
+ const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_update_result', payload: { __e2e: 'sealed' } })
+ await internals.dispatchDown({ type: 'agent_update', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote-conn')
+ expect(sealedReply).toHaveBeenCalledWith('remote-conn', 'agent_update_result', 'remote-1',
+ expect.objectContaining({ agent: expect.objectContaining({ id: agentId, lastOpenedAt: iso(OPENED) }) }))
+ // ...and this computer's own window hears the new order like everyone else.
+ expect(pushes()).toHaveLength(1)
+ })
+
+ it('refuses an unsealed remote open like any other agent_update', async () => {
+ await (socket as any).dispatchDown({ type: 'agent_update', payload: { requestId: 'plain', agentId, opened: true } }, 'remote-conn')
+ expect(registry.byAgent(agentId)?.lastOpenedAt).toBeUndefined()
+ expect(pushes()).toHaveLength(0)
+ })
+})
+
describe('viewer forwarding authentication', () => {
it('requires encryption and a web-role session remotely, while permitting trusted local clients', async () => {
const socket = new BackendSocket('token')
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index ffe617df0..8396c7352 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -151,6 +151,10 @@ const HANDSHAKE_TIMEOUT_MS = 15_000
* whatever is resolved. Well under the app's 12s `grid_models_list` timeout, leaving that RPC room
* for its own `grid` spawns; a reconcile slower than this lands by the next open. */
const GRID_ATTACH_WAIT_MS = 6_000
+/** An `agent_update {opened: true}` for an agent opened less than this long ago is answered but not
+ * stamped or broadcast: a person flicking between two tabs, or two apps opening the same agent at
+ * once, would otherwise push a frame to every client for each flick. Exported for the spec. */
+export const AGENT_OPENED_THROTTLE_MS = 3_000
const BASE_DELAY_MS = 1_000
const MAX_DELAY_MS = 30_000
const QUEUE_MAX = 2_000
@@ -2196,7 +2200,16 @@ export class BackendSocket {
if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
const hasName = Object.prototype.hasOwnProperty.call(payload, 'name')
const hasProfile = Object.prototype.hasOwnProperty.call(payload, 'selectedModel')
- if (!hasName && !hasProfile) { reply(type, requestId, { error: 'MISSING_UPDATE' }); return }
+ // An app OPENED this agent — see RegisteredSession.lastOpenedAt. Only a literal `true`: a
+ // client that means "opened" says so, and anything else is not an update at all. A client
+ // reaching this handler is already one that may change the agent — a shared harness's
+ // observer never gets here (sharing/owner.ts answers everything but terminal frames with
+ // VIEW_ONLY) — so an open is taken from the local window, a paired web/phone session and a
+ // remote desktop relayed through its own daemon alike.
+ const hasOpened = payload.opened === true
+ // An older client, and a request carrying none of the three, still get MISSING_UPDATE — which
+ // is also what a client learns from a daemon that predates `opened`.
+ if (!hasName && !hasProfile && !hasOpened) { reply(type, requestId, { error: 'MISSING_UPDATE' }); return }
const name = typeof payload.name === 'string' ? payload.name.trim() : ''
if (hasName && !name) { reply(type, requestId, { error: 'MISSING_NAME' }); return }
let s = registry.resolve(projectId)
@@ -2218,8 +2231,27 @@ export class BackendSocket {
s = registry.rename(projectId, name) ?? s
this.onAgentRename?.(s, name)
}
+ // Throttled on the stamp the row already carries, so a repeat inside the window is answered
+ // with the current frame but moves nothing and tells no one. A stamp from the future (the
+ // clock was set back) never throttles: the next open corrects it.
+ let opened = false
+ if (hasOpened) {
+ const since = Date.now() - (s.lastOpenedAt ?? 0)
+ if (!s.lastOpenedAt || since < 0 || since >= AGENT_OPENED_THROTTLE_MS) {
+ s = registry.markOpened(s.agentId) ?? s
+ opened = true
+ }
+ }
const agent = await this.toProject(s)
reply(type, requestId, { agent })
+ // Every app sorts by the same stamp, so every app hears it: the web audience — the phone,
+ // other desktops, and this computer's own windows — through `send`. Not the device: the dial
+ // lists agents in creation order and has nothing to reorder. Not for an agent whose terminal
+ // this daemon cannot see either, the rule `syncSession` (cli.ts) keeps: that row is not in
+ // `agents_list`, and a push would put it back on every screen.
+ if (opened && registry.terminalAvailable(s.agentId)) {
+ this.send({ type: 'agent_synced', payload: { agent } })
+ }
if (hasName) {
const renamed = { type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } }
this.send(renamed) // every OTHER web client on this machine (group-encrypted)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 41b7df8db..0a0c448ea 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -4102,6 +4102,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onMachineRename: (machineId, name) => proxyBackend('PATCH', `/api/machines/${encodeURIComponent(machineId)}`, { name }),
onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),
onAuthMe: () => proxyBackend('GET', '/api/auth/me'),
+ onAuthHandoff: () => proxyBackend('POST', '/api/auth/handoff', {}),
// Signed out there is nothing shared WITH this computer and nobody to ask: a share is made on the
// account. Answered as an empty list rather than proxied into the backend's 401, which is the one
// status the desktop app reads as "your session ended" — and a guest has no session to end.
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 4569b1c40..4027a15a8 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -872,6 +872,9 @@ describe('hook notify terminal scope', () => {
updatedAt: 1,
lastHookAt: 1,
lastTranscriptAt: 1,
+ // When an app last opened it — every app's "last used" order reads this, so a hook that lands
+ // while the daemon is down must not be the write that forgets it.
+ lastOpenedAt: 1_790_000_000_000,
}]))
await runHook({
@@ -891,6 +894,7 @@ describe('hook notify terminal scope', () => {
grid: { baseUrl: gridLaunch.baseUrl, model: null },
gridLaunch,
bypassPermission: true,
+ lastOpenedAt: 1_790_000_000_000,
})
expect(registry[0]).not.toHaveProperty('launch')
})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index d8556c653..d67c306cd 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -416,6 +416,26 @@ describe('the daemon socket', () => {
}
})
+ it('hands out a phone sign-in code over the socket only — never on the loopback port', async () => {
+ const dir = mkdtempSync('/tmp/hsock-')
+ const socketPath = join(dir, 'daemon.sock')
+ const onAuthHandoff = vi.fn(async () => ({ status: 200, body: { success: true, data: { code: 'hnh_x', expiresIn: 90 } } }))
+ const started = await startHookServer(0, { onRegistered: vi.fn(), onSessionEnd: vi.fn(), onAuthHandoff }, { socketPath })
+ server = started.server
+ try {
+ const local = { 'x-adapter-local': '1' }
+ expect(await viaSocket(socketPath, 'POST', '/api/auth/handoff', local)).toBe(200)
+ expect(await viaSocket(socketPath, 'POST', '/api/auth/handoff')).toBe(403)
+ const port = (started.server.address() as { port: number }).port
+ const tcp = await fetch(`http://127.0.0.1:${port}/api/auth/handoff`, { method: 'POST', headers: local })
+ expect(tcp.status).toBe(403)
+ expect(onAuthHandoff).toHaveBeenCalledTimes(1)
+ } finally {
+ await started.localSocket?.close()
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+
it('starts on TCP alone when the socket cannot be opened', async () => {
const dir = mkdtempSync('/tmp/hsock-')
const blocked = join(dir, 'daemon.sock')
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index a74e79988..b083a81ec 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -125,6 +125,9 @@ export interface HookServerHandlers {
onMachineDelete?: (machineId: string) => Promise<PairOutcome>
/** GET /api/auth/me — proxy the signed-in user's profile from backend. */
onAuthMe?: () => Promise<PairOutcome>
+ /** POST /api/auth/handoff — a one-time code that signs a phone in to this account (the desktop's
+ * Add Phone QR), minted by backend against this daemon's own session. */
+ onAuthHandoff?: () => Promise<PairOutcome>
onSharedHarnesses?: () => Promise<PairOutcome>
/** GET /api/desk — the account's tabs, the same on every computer; proxied like the machine list. */
onDeskRead?: () => Promise<PairOutcome>
@@ -686,6 +689,16 @@ export function startHookServer(
if (!me) { json(503, { error: 'UNAVAILABLE' }); return }
await proxied(me); return
}
+ // Add Phone: a code that SIGNS A PHONE IN to this account — the one local route whose answer is
+ // a credential. So not the CSRF header, which any local process can send, but the daemon's
+ // owner-only socket: the filesystem has already said this is the user who signed in. Another
+ // account on a shared computer reaches the loopback port, never the socket. A client on TCP is
+ // refused, and the Add Phone QR goes without the code (the phone asks for an emailed one).
+ if (req.method === 'POST' && url === '/api/auth/handoff') {
+ if (!trustedLocal || !localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onAuthHandoff) { json(503, { error: 'UNAVAILABLE' }); return }
+ await proxied(handlers.onAuthHandoff); return
+ }
if (req.method === 'PATCH' && url.startsWith('/api/machines/')) {
if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
const rename = handlers.onMachineRename
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index a2533bdfe..37a68cae8 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -96,6 +96,19 @@ describe('agentFrame', () => {
expect(frame).not.toHaveProperty('agent')
})
+ // The global "last used" order. Null — never an absent key — until an app opens the agent: a push
+ // without the key would erase an open an earlier frame reported, and a client reads "absent" as a
+ // daemon too old to keep the stamp.
+ it('always carries lastOpenedAt: null until an app opens the agent, then the stamp', async () => {
+ const context = { selectedModel: null, terminalAvailable: true }
+ expect(await agentFrame(session(null), context)).toHaveProperty('lastOpenedAt', null)
+ const opened = { ...session(null), lastOpenedAt: Date.UTC(2026, 8, 26, 9, 30) }
+ const frame = await agentFrame(opened, context)
+ expect(frame.lastOpenedAt).toBe('2026-09-26T09:30:00.000Z')
+ // Its own field: opening an agent is not activity, and activity is not an open.
+ expect(frame.updatedAt).toBe(new Date(1).toISOString())
+ })
+
it('reports launch state and defaults legacy agents to ready', async () => {
const legacy = session(null)
expect(await agentFrame(legacy, { selectedModel: null, terminalAvailable: true }))
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 59e0ef320..11dcf09de 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -60,6 +60,14 @@ export type AgentFrame = {
launch: NonNullable<RegisteredSession['launch']>
createdAt: string
updatedAt: string
+ /**
+ * When any app last opened this agent (`agent_update {opened: true}`), stamped by this daemon's
+ * clock (registry.ts, `markOpened`). ALWAYS present: null means nobody has opened it yet, while an
+ * absent key means a daemon too old to keep the stamp — the distinction a client needs to tell "never
+ * opened" from "cannot say". A client's "last used" is the later of this and `updatedAt`, so every
+ * app orders the same agents the same way.
+ */
+ lastOpenedAt: string | null
/** Cached usage from this conversation's owning machine; null means unreported, never zero. */
tokenUsage: AgentTokenUsage | null
outputStats: (AgentOutputStats & { updatedAt: string }) | null
@@ -159,7 +167,9 @@ function frameTitle(s: RegisteredSession): string | null {
/**
* One agent as every client consumes it. `updatedAt` is {@link lastActivityAt}, so a client sorting by
- * recency follows the conversation rather than the daemon's housekeeping.
+ * recency follows the conversation rather than the daemon's housekeeping; `lastOpenedAt` is the other
+ * half of "last used" — when a person last opened it, from any app — and a client sorts by the later
+ * of the two.
*/
export async function agentFrame(
s: RegisteredSession,
@@ -175,6 +185,9 @@ export async function agentFrame(
launch: s.launch ?? { state: 'ready' },
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(await lastActivityAt(s)).toISOString(),
+ // Null, never omitted, for the reason the module doc gives: a push without the key would erase
+ // the open an earlier frame had reported.
+ lastOpenedAt: s.lastOpenedAt ? new Date(s.lastOpenedAt).toISOString() : null,
tokenUsage: tokenUsage?.totalTokens != null
? { totalTokens: tokenUsage.totalTokens, updatedAt: tokenUsage.updatedAt } : null,
outputStats: tokenUsage?.output ? { ...tokenUsage.output, updatedAt: tokenUsage.updatedAt } : null,
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index e023afee0..d8558fc54 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1840,3 +1840,79 @@ describe('a terminal: a pane that becomes an engine and back', () => {
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(913))).toMatchObject({ engine: 'codex' })
})
})
+
+describe('lastOpenedAt: when an app last opened the agent, on the daemon clock', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-opened-'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ const OPENED = Date.UTC(2026, 8, 26, 9, 30)
+ const onDisk = () => JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
+
+ it('stamps the daemon’s own clock, persists it, and leaves the bookkeeping `touchedAt` alone', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%41' }], cwd: '/tmp/demo' })!
+ expect(pending.lastOpenedAt).toBeUndefined()
+ expect(onDisk()[0]).not.toHaveProperty('lastOpenedAt')
+ const touchedAt = pending.touchedAt
+
+ vi.setSystemTime(OPENED)
+ const opened = registry.markOpened(pending.agentId)
+ expect(opened?.lastOpenedAt).toBe(OPENED)
+ expect(opened?.touchedAt).toBe(touchedAt)
+ expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED, touchedAt })
+ expect(registry.markOpened('nobody')).toBeNull()
+
+ // The load rebuilds every row from a named list: a field missing there is written and then lost.
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(pending.agentId)?.lastOpenedAt).toBe(OPENED)
+ })
+
+ it('survives the hook that rebuilds the row — the first prompt after an open must not erase it', async () => {
+ const transcriptPath = join(dataDir, 'session-opened.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%42' }], cwd: '/tmp/demo' })!
+ vi.setSystemTime(OPENED)
+ registry.markOpened(pending.agentId)
+
+ vi.setSystemTime(OPENED + 60_000)
+ const bound = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
+ expect(bound?.entry.agentId).toBe(pending.agentId)
+ expect(bound?.entry.lastOpenedAt).toBe(OPENED)
+ // ...and again on a re-register of the same session, then on disk.
+ const again = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
+ expect(again?.entry.lastOpenedAt).toBe(OPENED)
+ expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED })
+ })
+
+ it('never lets a hand-edited or nonsensical stamp reach the frame', async () => {
+ const { registry, strictPersistedRow } = await loadRegistryModule()
+ registry.load()
+ const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%43' }], cwd: '/tmp/demo' })!
+ const row = onDisk()[0]
+ expect(strictPersistedRow({ ...row, lastOpenedAt: OPENED })?.lastOpenedAt).toBe(OPENED)
+ for (const bad of ['yesterday', -5, 0, 1.5, Number.NaN, null]) {
+ expect(strictPersistedRow({ ...row, lastOpenedAt: bad })).not.toHaveProperty('lastOpenedAt')
+ }
+
+ writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, lastOpenedAt: 'yesterday' }]), { mode: 0o600 })
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(pending.agentId)).toBeTruthy()
+ expect(reloaded.byAgent(pending.agentId)).not.toHaveProperty('lastOpenedAt')
+ })
+})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 1702a2f82..152fa1e1a 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -232,6 +232,15 @@ export interface RegisteredSession {
touchedAt: number
lastHookAt: number
lastTranscriptAt: number
+ /**
+ * When an app last OPENED this agent (ms epoch) — a desktop window focusing its tab, the phone
+ * landing on it — on any computer. Stamped by `markOpened` with THIS daemon's clock, never a
+ * client's: the agent's owner is the one place every app reads from, so it is the one clock they
+ * can all agree on, and "last used" comes out in the same order on every screen. Absent until the
+ * first open; persisted, carried through a hook bind, a stop and a resume like any other fact
+ * about the agent. A client sorts by the later of this and the frame's `updatedAt`.
+ */
+ lastOpenedAt?: number
}
/** A saved row's `touchedAt`, which rows saved before 2026-09-27 call `updatedAt`. */
@@ -326,6 +335,12 @@ function permissionModeName(value: unknown): value is string {
return typeof value === 'string' && /^[A-Za-z]{1,24}$/.test(value)
}
+/** A persisted `lastOpenedAt`, or undefined for anything that is not a real moment (a row from before
+ * the field, or a hand-edited one) — undefined rather than 0, so "never opened" stays absent. */
+function normalizedOpenedAt(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined
+}
+
function normalizedAgentEngine(value: unknown): AgentEngine {
return typeof value === 'string' && AGENT_ENGINES.has(value)
? value as AgentEngine
@@ -500,8 +515,12 @@ export function strictPersistedRow(value: unknown): RegisteredSession | null {
|| (row.processIdentity !== null && !validProcessIdentity(row.processIdentity))) return null
const placements = runtimes.map(terminalPlacementKey)
if (new Set(placements).size !== placements.length) return null
+ // Taken out of the spread and put back only when it is a real moment: the spread would otherwise
+ // carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
+ const { lastOpenedAt: rawOpenedAt, ...rest } = row
+ const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
return {
- ...row,
+ ...rest,
schemaVersion: 2,
active,
...(launch ? { launch } : {}),
@@ -528,6 +547,7 @@ export function strictPersistedRow(value: unknown): RegisteredSession | null {
touchedAt: savedTouchedAt(row) ?? Date.now(),
lastHookAt: typeof row.lastHookAt === 'number' ? row.lastHookAt : Date.now(),
lastTranscriptAt: typeof row.lastTranscriptAt === 'number' ? row.lastTranscriptAt : Date.now(),
+ ...(lastOpenedAt !== undefined ? { lastOpenedAt } : {}),
}
}
@@ -954,6 +974,9 @@ class Registry {
touchedAt: savedTouchedAt(raw) ?? now,
lastHookAt: typeof raw.lastHookAt === 'number' ? raw.lastHookAt : (savedTouchedAt(raw) ?? now),
lastTranscriptAt: typeof raw.lastTranscriptAt === 'number' ? raw.lastTranscriptAt : (savedTouchedAt(raw) ?? now),
+ // Rehydrated explicitly for the reason the ⚠️ above gives. A reboot keeps it: it is when a
+ // person last looked, which no reboot changes.
+ ...(normalizedOpenedAt(raw.lastOpenedAt) !== undefined ? { lastOpenedAt: normalizedOpenedAt(raw.lastOpenedAt) } : {}),
}
if (
raw.engine !== engine
@@ -1489,6 +1512,10 @@ class Registry {
touchedAt: now,
lastHookAt: now,
lastTranscriptAt: existing?.lastTranscriptAt ?? now,
+ // ⚠️ Carried forward, for the reason the ⚠️ on `subscriptionModel` gives: without this line
+ // the first hook after an open — the next prompt, a `/clear` — erases it from memory, the next
+ // save writes that to disk, and every app's "last used" order forgets the open ever happened.
+ ...(existing?.lastOpenedAt ? { lastOpenedAt: existing.lastOpenedAt } : {}),
}
entry.tmuxPane = tmuxProjection(entry.runtimes)
entry.primaryRuntimeKey = selectedRuntimeKey(entry.runtimes, input.primaryRuntimeKey || existing?.primaryRuntimeKey)
@@ -1843,6 +1870,24 @@ class Registry {
return true
}
+ /**
+ * An app opened this agent: stamp `lastOpenedAt` with THIS daemon's clock. Never takes a time from
+ * the caller — a phone and a laptop whose clocks disagree would otherwise order the same agents
+ * differently, which is the one thing this field exists to prevent.
+ *
+ * `updatedAt` is left alone on purpose. That is the row's bookkeeping (the webui's "when" column,
+ * `session_get`'s timestamp), and looking at an agent changes nothing about the agent. The save
+ * still happens: a row is written whenever its bytes differ from the last write, whichever field
+ * moved.
+ */
+ markOpened(agentId: string): RegisteredSession | null {
+ const session = this.agents.get(agentId)
+ if (!session) return null
+ session.lastOpenedAt = Date.now()
+ this.save()
+ return session
+ }
+
touchTranscript(sessionId: string, at = Date.now()): boolean {
const session = this.bySession(sessionId)
if (!session) return false
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index fd38e5ab6..b45906609 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -52,6 +52,21 @@ describe('stopped harness persistence', () => {
expect(store.patch('never-saved', { cwd: '/tmp' })).toBe(false)
})
+ // The global "last used" order must not forget an agent because it was paused: the archive keeps
+ // the stamp, the store reads it back, and the resumed row carries it into the live registry.
+ it('keeps when an app last opened the agent through a stop and a resume', async () => {
+ const { registry, StoppedAgentStore, saved, store } = await fixture()
+ const opened = registry.markOpened(saved.agentId)!.lastOpenedAt!
+ expect(opened).toBeGreaterThan(0)
+ store.save({ ...registry.byAgent(saved.agentId)!, sessionId: saved.sessionId })
+ registry.removeAgent(saved.agentId)
+ const archived = new StoppedAgentStore(join(directory, 'stopped-agents')).get(saved.agentId)!
+ expect(archived.lastOpenedAt).toBe(opened)
+ const resumed = registry.resumePendingAgent(archived, [{ backend: 'tmux', paneId: '%77' }])!
+ expect(resumed.lastOpenedAt).toBe(opened)
+ expect(registry.byAgent(saved.agentId)?.lastOpenedAt).toBe(opened)
+ })
+
it('hides a running identity or conversation, without discarding its archive', async () => {
const { saved, store } = await fixture()
store.save(saved)
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index a14d30046..93e6bb36a 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -141,6 +141,82 @@ class ApiClient {
return unwrapApiResponse(res) as Map<String, dynamic>?;
}
+ // -- pairing a phone (Harness ▸ Add Phone…) --
+
+ /// `POST /api/pair` — hand THIS computer's daemon the one-time code the Add
+ /// Phone QR is showing, so it runs the end-to-end-encryption handshake with
+ /// the phone that scanned it. The same call `harness pair <code>` makes
+ /// (cli.ts `pairCommand`, hookServer.ts `/api/pair`).
+ ///
+ /// Answers the HTTP status and the daemon's own body, untouched: this route
+ /// does NOT speak the `{success, data, error}` envelope [unwrapApiResponse]
+ /// reads — it answers `{label, fingerprint}` on success and `{error: CODE}`
+ /// otherwise — so the caller (`widgets/add_phone_dialog.dart`) reads the
+ /// code itself. A transport failure still throws its [DioException].
+ ///
+ /// ⚠️ A LONG POLL, hence its own receive timeout. With no phone waiting the
+ /// daemon answers at once (`NO_INTENT`); with one, it holds the request
+ /// until the handshake is over, which its own round timers bound at 15 s a
+ /// round. The client's shared 30 s would cut a slow-but-healthy handshake
+ /// off in the middle and report a timeout for a pairing that then succeeds.
+ Future<({int status, Map<String, dynamic> body})> pair(
+ String code, {
+ CancelToken? cancelToken,
+ }) async {
+ final res = await _dio.post(
+ '/api/pair',
+ data: {'code': code},
+ cancelToken: cancelToken,
+ // A write, so the daemon's CSRF gate wants the local header — as it
+ // does for renaming a machine.
+ options: Options(
+ headers: {'x-adapter-local': '1'},
+ receiveTimeout: const Duration(seconds: 60),
+ // 409 is "no phone yet" (NO_INTENT / EXPIRED / BUSY), asked every
+ // 1.5 s while the dialog is open: not a failure worth a log line.
+ extra: {
+ httpLogRoutineStatusesKey: const <int>{409},
+ },
+ ),
+ );
+ final body = res.data;
+ return (
+ status: res.statusCode ?? 0,
+ body: body is Map ? Map<String, dynamic>.from(body) : <String, dynamic>{},
+ );
+ }
+
+ /// A one-time code that signs a phone in to this account: the Add Phone
+ /// QR's `h=`, which the phone redeems for a session of its own instead of
+ /// asking for an emailed code (backend `lib/harnessSession.ts`).
+ ///
+ /// Minted by the backend against the daemon's own session, and the daemon
+ /// hands it out over its owner-only socket and nowhere else — a code that
+ /// signs a device in is a credential. So null is an ordinary answer: an
+ /// older daemon or backend, this app on the TCP fallback, the backend down.
+ /// The QR then goes without it and the phone falls back to the email code.
+ Future<({String code, Duration ttl})?> phoneSignInCode() async {
+ try {
+ final res = await _dio.post(
+ '/api/auth/handoff',
+ data: const <String, Object?>{},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ final data = unwrapApiResponse(res);
+ final code = data is Map ? data['code'] : null;
+ final expiresIn = data is Map ? data['expiresIn'] : null;
+ if (code is! String || code.isEmpty) return null;
+ return (
+ code: code,
+ ttl: Duration(
+ seconds: expiresIn is int && expiresIn > 0 ? expiresIn : 60,
+ ),
+ );
+ } catch (_) {
+ return null;
+ }
+ }
+
// -- the Harness Store: ratings and reviews (control plane, proxied by the local CLI) --
Future<Map<String, dynamic>?> storeRatings() async {
final res = await _dio.get('/api/store/ratings');
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 6ae05bf2f..a761a5489 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -327,6 +327,24 @@ class Agent {
/// The CLI's transcript/hook activity time, not its registry refresh time.
final DateTime? lastActivityAt;
+ /// When a person last opened or focused this harness in ANY client, as the
+ /// owning daemon recorded it (`lastOpenedAt`, stamped by `agent_update
+ /// {opened: true}`). Null when never opened, or from a daemon that predates
+ /// the field.
+ final DateTime? lastOpenedAt;
+
+ /// What harness lists sort by: the later of [lastActivityAt] and
+ /// [lastOpenedAt], so a harness someone just looked at rises even while it
+ /// is quiet. The order is global — every client and machine reads the same
+ /// daemon stamps.
+ DateTime? get lastUsedAt {
+ final activity = lastActivityAt;
+ final opened = lastOpenedAt;
+ if (activity == null) return opened;
+ if (opened == null) return activity;
+ return opened.isAfter(activity) ? opened : activity;
+ }
+
/// Cached conversation usage reported by this agent's owning machine.
final int? tokensUsed;
final DateTime? tokensUpdatedAt;
@@ -412,6 +430,7 @@ class Agent {
this.parentAgentId,
this.project,
this.lastActivityAt,
+ this.lastOpenedAt,
this.tokensUsed,
this.tokensUpdatedAt,
this.outputStats,
@@ -545,6 +564,9 @@ class Agent {
lastActivityAt: j['updatedAt'] is String
? DateTime.tryParse(j['updatedAt'] as String)
: null,
+ lastOpenedAt: j['lastOpenedAt'] is String
+ ? DateTime.tryParse(j['lastOpenedAt'] as String)
+ : null,
tokensUsed: validTokens ? total : null,
tokensUpdatedAt:
validTokens && usage is Map && usage['updatedAt'] is String
@@ -579,46 +601,51 @@ class Agent {
);
}
- Agent copyWith({String? name, String? status, bool? terminalAvailable}) =>
- Agent(
- id: id,
- sessionId: sessionId,
- name: name ?? this.name,
- title: title,
- engine: engine,
- engineDisplayName: engineDisplayName,
- engineIconHint: engineIconHint,
- codexHome: codexHome,
- modelName: modelName,
- gridModel: gridModel,
- gridWebSearch: gridWebSearch,
- gridState: gridState,
- gridNote: gridNote,
- parentAgentId: parentAgentId,
- project: project,
- lastActivityAt: lastActivityAt,
- tokensUsed: tokensUsed,
- tokensUpdatedAt: tokensUpdatedAt,
- outputStats: outputStats,
- status: status ?? this.status,
- launchState: launchState,
- launchError: launchError,
- launchDetail: launchDetail,
- terminalAvailable: terminalAvailable ?? this.terminalAvailable,
- terminalUnavailableReason: terminalUnavailableReason,
- dsh: dsh,
- dshName: dshName,
- viewerUrl: viewerUrl,
- viewerError: viewerError,
- viewerName: viewerName,
- verdict: verdict,
- forkedFrom: forkedFrom,
- forkable: forkable,
- resumeMode: resumeMode,
- permissionMode: permissionMode,
- bypassPermission: bypassPermission,
- namedAgent: namedAgent,
- );
+ Agent copyWith({
+ String? name,
+ String? status,
+ bool? terminalAvailable,
+ DateTime? lastOpenedAt,
+ }) => Agent(
+ id: id,
+ sessionId: sessionId,
+ name: name ?? this.name,
+ title: title,
+ engine: engine,
+ engineDisplayName: engineDisplayName,
+ engineIconHint: engineIconHint,
+ codexHome: codexHome,
+ modelName: modelName,
+ gridModel: gridModel,
+ gridWebSearch: gridWebSearch,
+ gridState: gridState,
+ gridNote: gridNote,
+ parentAgentId: parentAgentId,
+ project: project,
+ lastActivityAt: lastActivityAt,
+ lastOpenedAt: lastOpenedAt ?? this.lastOpenedAt,
+ tokensUsed: tokensUsed,
+ tokensUpdatedAt: tokensUpdatedAt,
+ outputStats: outputStats,
+ status: status ?? this.status,
+ launchState: launchState,
+ launchError: launchError,
+ launchDetail: launchDetail,
+ terminalAvailable: terminalAvailable ?? this.terminalAvailable,
+ terminalUnavailableReason: terminalUnavailableReason,
+ dsh: dsh,
+ dshName: dshName,
+ viewerUrl: viewerUrl,
+ viewerError: viewerError,
+ viewerName: viewerName,
+ verdict: verdict,
+ forkedFrom: forkedFrom,
+ forkable: forkable,
+ resumeMode: resumeMode,
+ permissionMode: permissionMode,
+ bypassPermission: bypassPermission,
+ namedAgent: namedAgent,
+ );
/// A mode id as `PERMISSION_MODES` spells them (`acceptEdits`, `readOnly`):
/// one word. Not checked against this build's own list — the daemon that
diff --git a/desktop/lib/logging/http_log.dart b/desktop/lib/logging/http_log.dart
index aa332442e..72d84f384 100644
--- a/desktop/lib/logging/http_log.dart
+++ b/desktop/lib/logging/http_log.dart
@@ -26,6 +26,15 @@ Dio attachHttpLog(Dio dio) {
/// the only place an interceptor can keep per-request state.
const String _startedAtKey = 'harnessLogStartedAt';
+/// Statuses a request expects as ROUTINE, as a `Set<int>` in its
+/// `Options.extra` under this key: they log at `debug` like a success.
+///
+/// For a poll whose "not yet" is an HTTP error by design — Add Phone asks the
+/// daemon `POST /api/pair` every 1.5 s, and "no phone is waiting" is a 409.
+/// Logged at `warn`, a minute with the dialog open was forty lines in the
+/// Failed lens about nothing going wrong.
+const String httpLogRoutineStatusesKey = 'harnessLogRoutineStatuses';
+
class _HttpLogInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
@@ -41,7 +50,10 @@ class _HttpLogInterceptor extends Interceptor {
final status = response.statusCode;
// `validateStatus` lets 4xx and 5xx through as responses in both of this
// app's clients, so "it answered" is not the same as "it worked".
- final failed = status == null || status < 200 || status >= 300;
+ final routine = response.requestOptions.extra[httpLogRoutineStatusesKey];
+ final failed =
+ (status == null || status < 200 || status >= 300) &&
+ !(routine is Set<int> && routine.contains(status));
final line =
'${_line(response.requestOptions)} → $status'
'${_took(response.requestOptions)}';
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 7bd496b8f..8154b1dc2 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -53,6 +53,7 @@ import '../state/workspace_status.dart';
import '../state/workspace_pull_request.dart';
import '../state/terminal_pane.dart';
import '../widgets/transient_menus.dart';
+import '../widgets/add_phone_dialog.dart';
import '../widgets/layout_palette.dart';
import '../widgets/move_pane_palette.dart';
import '../widgets/engine_identity.dart';
@@ -1526,6 +1527,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
unawaited(_notifications());
case 'settings':
await _settings();
+ case 'addPhone':
+ await _addPhone();
case 'customize':
await _customize();
}
@@ -1720,6 +1723,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
);
+ /// Harness ▸ Add Phone… and `> add phone`: the QR a phone scans to sign in
+ /// and pair with this computer. See `widgets/add_phone_dialog.dart`.
+ Future<void> _addPhone() =>
+ _dialog(() => showAddPhoneDialog(context, app, keymap: _keymap));
+
/// Settings, by section, as rows of the box: `> usage` goes straight to
/// Settings ▸ Usage. A palette that finds a setting by name is how an editor
/// makes a settings screen nobody has to navigate.
@@ -3740,6 +3748,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'pane.focus_$i': () => app.focusPaneByIndex(i - 1),
'navigation.commands': _showSearchCommands,
'app.customize': () => unawaited(_customize()),
+ 'app.add_phone': () => unawaited(_addPhone()),
'app.store': _openStore,
'agent.add': _addAgent,
if (kDebugSurfaceEnabled) 'app.onboarding_review': _newTab,
@@ -3802,7 +3811,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
if (id == 'keyboard.quick_start' ||
id == 'keyboard.practice' ||
- id == 'app.onboarding_review') {
+ id == 'app.onboarding_review' ||
+ // A viewer has no daemon of its own to pair a phone with.
+ id == 'app.add_phone') {
return app.viewer == null;
}
if (id == 'agent.rename' ||
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index b7d587c1f..7dcf89e84 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -476,6 +476,15 @@ final harnessCommands = <HarnessCommand>[
action: ShortcutAction.showSettings,
nativeAction: 'settings',
),
+ // Harness ▸ Add Phone…, beside Settings in the app menu. No default keys:
+ // it is a once-per-phone errand, not a chord worth learning.
+ const HarnessCommand(
+ 'app.add_phone',
+ 'Add phone',
+ ShortcutGroup.actions,
+ keywords: ['iphone', 'mobile', 'pair', 'qr', 'scan', 'connect'],
+ nativeAction: 'addPhone',
+ ),
const HarnessCommand(
'keyboard.help',
'Keyboard shortcuts',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 726826e36..9cb78aedd 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1537,6 +1537,13 @@ class AppNotifier extends ChangeNotifier {
void _noteNavigation() {
_paneFocusByUser = !_navigatingFromDevice;
+ // A device's move is not a person opening anything — but it does leave a
+ // different harness in front, so the next gesture on it is an open again.
+ if (_navigatingFromDevice) {
+ _touchedFocus = null;
+ } else {
+ _touchFocusedAgent();
+ }
}
/// Native focus also changes during reparenting and dialog dismissal. The
@@ -4690,6 +4697,7 @@ class AppNotifier extends ChangeNotifier {
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
prev.lastActivityAt != agent.lastActivityAt ||
+ prev.lastOpenedAt != agent.lastOpenedAt ||
prev.tokensUsed != agent.tokensUsed ||
prev.outputStats != agent.outputStats ||
prev.tokensUpdatedAt != agent.tokensUpdatedAt ||
@@ -8067,6 +8075,93 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// How long a second open of the SAME harness, with no other harness
+ /// opened in between, folds into the first. Only the same one: A, B, A in
+ /// quick succession is three opens, or the order would say B was last.
+ static const agentTouchDebounce = Duration(seconds: 3);
+
+ ({String machineId, String agentId, DateTime at})? _lastAgentTouch;
+
+ /// The harness the focus last stamped, so the grid's pointer-down — every
+ /// click inside the tile already in front re-focuses it — is not an open.
+ (String, String)? _touchedFocus;
+
+ /// Tell a harness's own daemon that a person just opened or focused it, so
+ /// its `lastOpenedAt` moves and with it "last used" order in EVERY client
+ /// (`agent_update {agentId, opened: true}`, sealed like any agent_update).
+ ///
+ /// Fire-and-forget. Nothing waits on it and nothing is said when it fails:
+ /// an older daemon answers MISSING_UPDATE and the list simply keeps sorting
+ /// by activity; a socket that is down loses one stamp. Never dials a socket
+ /// for it, and never for a view-only shared harness — its owner's order is
+ /// not this window's to move.
+ void touchAgent(String machineId, String agentId) {
+ if (_disposed) return;
+ final machine = machineStates[machineId];
+ if (machine == null ||
+ machine.machine.isShared ||
+ machine.needsLink ||
+ machine.nodeOnline == false ||
+ machine.connectionStatus != ConnectionStatus.connected ||
+ (_pool == null && connectionForTest == null)) {
+ return;
+ }
+ final now = DateTime.now();
+ final last = _lastAgentTouch;
+ if (last != null &&
+ last.machineId == machineId &&
+ last.agentId == agentId &&
+ now.difference(last.at) < agentTouchDebounce) {
+ return;
+ }
+ _lastAgentTouch = (machineId: machineId, agentId: agentId, at: now);
+ unawaited(_sendAgentTouch(machine, agentId));
+ }
+
+ Future<void> _sendAgentTouch(MachineState machine, String agentId) async {
+ final revision = _authRevision;
+ try {
+ final result = await _conn(machine.machine.machineId).request(
+ 'agent_update',
+ payload: {'agentId': agentId, 'opened': true},
+ timeout: const Duration(seconds: 10),
+ );
+ if (!_machineWorkCurrent(machine, revision)) return;
+ // The daemon's own stamp, taken now rather than on the next push, so the
+ // list this window just opened from is already in its new order. Only
+ // this one field: the reply is not a frame to rebuild the agent from.
+ final returned = result['agent'];
+ final raw = returned is Map && (returned['id'] ?? agentId) == agentId
+ ? returned['lastOpenedAt']
+ : null;
+ final opened = raw is String ? DateTime.tryParse(raw) : null;
+ if (opened == null) return;
+ final index = machine.agents.indexWhere((a) => a.id == agentId);
+ if (index == -1) return;
+ final current = machine.agents[index];
+ final known = current.lastOpenedAt;
+ if (known != null && !opened.isAfter(known)) return;
+ machine.agents = [...machine.agents]
+ ..[index] = current.copyWith(lastOpenedAt: opened);
+ notifyListeners();
+ } catch (_) {
+ // MISSING_UPDATE from an older daemon, a timeout, a dropped socket: the
+ // stamp is a courtesy to the ordering, never worth an error band.
+ }
+ }
+
+ /// Stamp the harness now in front, when it is a different one from the
+ /// last stamped — see [touchAgent]. A viewer is its agent's, as in
+ /// [_announceAppFocus].
+ void _touchFocusedAgent() {
+ final pane = focusedPane;
+ final agentId = pane?.agentId ?? pane?.ownerAgentId;
+ final focus = agentId == null ? null : (pane!.machineId, agentId);
+ if (focus == _touchedFocus) return;
+ _touchedFocus = focus;
+ if (focus != null) touchAgent(focus.$1, focus.$2);
+ }
+
bool _agentStopCurrent(_AgentStop request) {
if (!identical(
_agentStops[(request.machine.machine.machineId, request.agent.id)],
@@ -9584,6 +9679,14 @@ class AppNotifier extends ChangeNotifier {
// duplicate with the inferred one is free: the daemon drops the second against where the dial
// already is.
if (focus && target == activeSwarm) _announceAppFocus();
+ // A new tile takes the focus without passing [focusPane], so the open is
+ // said here — for a person's add only, never a device's door.
+ if (focus &&
+ target == activeSwarm &&
+ intent == AttachIntent.person &&
+ !_navigatingFromDevice) {
+ _touchFocusedAgent();
+ }
// The agent may already have a viewer the grid could not show until now,
// because this tile is what it hangs beside.
_syncViewerPane(machine, agent);
diff --git a/desktop/lib/state/harness_sessions.dart b/desktop/lib/state/harness_sessions.dart
index 7d05cbe29..1ffdc054a 100644
--- a/desktop/lib/state/harness_sessions.dart
+++ b/desktop/lib/state/harness_sessions.dart
@@ -8,7 +8,7 @@ import 'swarm_navigation.dart';
enum SessionFilter { all, needsInput, running, paused }
enum SessionSort {
- recent('Recently active'),
+ recent('Recently used'),
name('Name'),
machine('Machine'),
project('Project');
@@ -56,7 +56,10 @@ class HarnessSession {
final bool open, working;
final PendingQuestion? question;
bool get needsInput => question != null && !agent.isStopped;
- DateTime? get lastActiveAt => agent.lastActivityAt;
+
+ /// Activity or a person opening it in any client, whichever is later — see
+ /// [Agent.lastUsedAt]. What every harness list sorts by and shows.
+ DateTime? get lastUsedAt => agent.lastUsedAt;
String get machineId => machine.machine.machineId;
String get id => agentDestinationId(machineId, agent.id);
AgentProject? get project => machine.projectOf(agent);
@@ -178,7 +181,7 @@ List<HarnessSession> visibleHarnessSessions(
final ranks = {for (var i = 0; i < recent.length; i++) recent[i]: i};
result.sort((a, b) {
final comparison = switch (sort) {
- SessionSort.recent => _byActivity(a, b, ranks, recent.length),
+ SessionSort.recent => _byLastUse(a, b, ranks, recent.length),
SessionSort.name => compareNatural(
a.agent.displayName.toLowerCase(),
b.agent.displayName.toLowerCase(),
@@ -202,17 +205,19 @@ List<HarnessSession> visibleHarnessSessions(
return result;
}
-int _byActivity(
+/// Most recently used first — the same global order as Open Harness — then
+/// this window's own visit order for ties and harnesses with no time at all.
+int _byLastUse(
HarnessSession a,
HarnessSession b,
Map<String, int> ranks,
int fallback,
) {
- final activity = (b.lastActiveAt?.millisecondsSinceEpoch ?? 0).compareTo(
- a.lastActiveAt?.millisecondsSinceEpoch ?? 0,
+ final used = (b.lastUsedAt?.millisecondsSinceEpoch ?? 0).compareTo(
+ a.lastUsedAt?.millisecondsSinceEpoch ?? 0,
);
- return activity != 0
- ? activity
+ return used != 0
+ ? used
: (ranks[a.id] ?? fallback).compareTo(ranks[b.id] ?? fallback);
}
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 115723bc4..e4a1238d2 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -339,6 +339,10 @@ class SwarmDestination {
/// and machine before paths and branches, which are more likely to truncate.
final String? terminalDetail;
final PromptContext? promptContext;
+
+ /// When the harness's conversation last moved ([Agent.lastActivityAt]) — the
+ /// true time, not when someone last opened it. What Open Harness sorts by,
+ /// and the age it prints beside the row.
final DateTime? lastActivityAt;
final String? swarmId, machineId, agentId, engine;
final String? modelId;
@@ -770,9 +774,10 @@ class SwarmLocationCatalog {
}
}
-/// Open Harness uses the same activity timestamp it shows beside each session,
-/// within each [SwarmMatchStrength]: typing "hn" puts the harness named hn
-/// first, however many newer ones live in a folder whose path spells h…n.
+/// Open Harness sorts by last use — activity, or a person opening the harness
+/// in any client, whichever is later — the same time it shows beside each
+/// session, within each [SwarmMatchStrength]: typing "hn" puts the harness named
+/// hn first, however many newer ones live in a folder whose path spells h…n.
/// Undated rows come last; ties retain visit recency and search relevance.
List<SwarmDestination> rankSwarmDestinationsByActivity(
List<SwarmDestination> all,
@@ -794,7 +799,7 @@ List<SwarmDestination> rankSwarmDestinationsByActivity(
final strength = a.strength.index.compareTo(b.strength.index);
if (strength != 0) return strength;
// What was said is ranked by the index, which weighs how well it matched
- // against how long ago; activity decides between equal answers.
+ // against how long ago; last use decides between equal answers.
if (a.strength == SwarmMatchStrength.said ||
a.strength == SwarmMatchStrength.content) {
final said = b.said.compareTo(a.said);
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 541898482..5c64e4b6e 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1054,7 +1054,7 @@ class SwarmSearchController extends ChangeNotifier {
swarmId: original?.swarmId,
paneId: original?.paneId,
previewKey: original?.previewKey,
- lastActivityAt: session.lastActiveAt,
+ lastActivityAt: session.agent.lastActivityAt,
current: original?.current ?? false,
searchFields: [
...?original?.fields,
diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dart
new file mode 100644
index 000000000..11a7700d1
--- /dev/null
+++ b/desktop/lib/widgets/add_phone_dialog.dart
@@ -0,0 +1,655 @@
+import 'dart:async';
+import 'dart:io' show SocketException;
+import 'dart:math' as math;
+
+import 'package:dio/dio.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:qr/qr.dart';
+import 'package:xterm/xterm.dart' show TerminalTheme;
+
+import '../api/api_client.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../state/app_state.dart';
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart';
+import 'terminal_prompt.dart';
+
+/// Harness ▸ Add Phone… — a QR the phone scans to sign in to this account AND
+/// pair with this computer, end to end encrypted, with no password typed.
+///
+/// Three parts, and the QR is only one of them:
+///
+/// 1. **The QR** ([phonePairLink]) tells the phone who to sign in as, which
+/// machine to pair with, and the one-time pairing code.
+/// 2. **The sign-in code** ([PhoneSignInCodeCall]), which the QR also carries:
+/// the phone redeems it for a session of its own, so the scan signs it in
+/// with no emailed code. Renewed every minute while the dialog is open —
+/// see [_AddPhoneDialogState._renewSignIn].
+/// 3. **Arming the daemon.** The phone, once signed in, sends this machine an
+/// `e2e_pair_intent`; the daemon runs the handshake only when somebody on
+/// THIS computer hands it the same code (`POST /api/pair`, the call
+/// `harness pair <code>` makes). So while this dialog is open it keeps
+/// handing it over — see [_AddPhoneDialogState._loop] — and the code is
+/// live exactly as long as the QR is on screen.
+///
+/// [pair] and [signInCode] are the transport, injectable so a test needs no
+/// daemon; by default they are this app's own loopback client
+/// ([phonePairOverDaemon], [ApiClient.phoneSignInCode]).
+Future<void> showAddPhoneDialog(
+ BuildContext context,
+ AppNotifier app, {
+ AppKeymap? keymap,
+ PhonePairCall? pair,
+ PhoneSignInCodeCall? signInCode,
+}) => showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (_) => AddPhoneDialog(
+ app: app,
+ pair: pair ?? phonePairOverDaemon(app.api),
+ signInCode: signInCode ?? app.api.phoneSignInCode,
+ ),
+);
+
+/// Where the QR points. The phone's `ConnectCode` (mobile
+/// `lib/phone/welcome/connect_code.dart`) parses exactly this.
+const kPhonePairHost = 'harness.autonomous.ai';
+const kPhonePairPath = '/pair';
+
+/// The characters a pairing code is drawn from: no `0 O 1 I L`, which read
+/// alike — and no `U` either.
+///
+/// ⚠️ `U` is left out on purpose, although it reads fine. The daemon feeds
+/// the code through core.ts `normalizeCode`, which maps `U` to `V` (Crockford
+/// base32); the phone's `normalizePairCode` only uppercases and strips
+/// separators. A code with a `U` in it would therefore reach CPace as two
+/// different secrets and fail as `CODE_MISMATCH` every time — for a 16-letter
+/// code, about four scans in ten. Without it both sides agree whatever either
+/// normaliser does, at 30 symbols: 78 bits over 16 characters, far past what
+/// three guesses per five minutes (the daemon's rate limit) could dent.
+const kPhonePairCodeAlphabet = 'ABCDEFGHJKMNPQRSTVWXYZ23456789';
+const kPhonePairCodeLength = 16;
+
+/// A fresh one-time pairing code, from a cryptographically secure source.
+///
+/// It is the whole secret the pairing rests on — the backend relays the
+/// handshake and must learn nothing from it — so never `Random()`.
+/// [random] exists for tests; `Random.secure().nextInt` is uniform, so no
+/// symbol is likelier than another.
+String newPhonePairCode({math.Random? random}) {
+ final source = random ?? math.Random.secure();
+ return String.fromCharCodes([
+ for (var i = 0; i < kPhonePairCodeLength; i++)
+ kPhonePairCodeAlphabet.codeUnitAt(
+ source.nextInt(kPhonePairCodeAlphabet.length),
+ ),
+ ]);
+}
+
+/// `https://harness.autonomous.ai/pair#e=<email>&m=<machineId>&c=<code>&h=<sign-in code>`.
+///
+/// ⚠️ EVERYTHING rides in the FRAGMENT, never the query. The code is the
+/// out-of-band secret end-to-end encryption rests on, and a browser never
+/// sends a fragment to the server — so a link opened in Safari (no app
+/// installed yet, a desktop camera, a curious person) still keeps the code
+/// off our servers and out of every access log between here and there. The
+/// email and machine id go with it: nothing in this link is the server's
+/// business.
+///
+/// Encoded as a query string inside the fragment, with
+/// [Uri.encodeQueryComponent], because the phone reads it back with
+/// [Uri.splitQueryString] — a `+` in an address has to arrive as a `+`.
+///
+/// [signIn] (`h`) is the one-time code that signs the phone in; without it —
+/// or on a phone app that predates it — the phone signs in with an emailed
+/// code, as before. It is the account's credential for its minute, which is
+/// one more reason all of this rides in the fragment.
+Uri phonePairLink({
+ required String email,
+ required String machineId,
+ required String code,
+ String? signIn,
+}) => Uri(
+ scheme: 'https',
+ host: kPhonePairHost,
+ path: kPhonePairPath,
+ fragment:
+ 'e=${Uri.encodeQueryComponent(email)}'
+ '&m=${Uri.encodeQueryComponent(machineId)}'
+ '&c=$code'
+ '${signIn != null ? '&h=${Uri.encodeQueryComponent(signIn)}' : ''}',
+);
+
+/// What one `POST /api/pair` came to, as far as this dialog cares.
+@immutable
+class PhonePairAnswer {
+ /// The phone is paired; [label] is its own name for itself.
+ const PhonePairAnswer.paired(String this.label) : error = null;
+
+ /// The daemon's error code (`NO_INTENT`, `CODE_MISMATCH`, …), or
+ /// [unavailable] for a daemon that cannot pair at all.
+ const PhonePairAnswer.failed(String this.error) : label = null;
+
+ final String? label;
+ final String? error;
+
+ /// The daemon has no pairing to offer: it said so (a build without E2EE),
+ /// it predates `/api/pair` (404), or nobody is listening. Asking again will
+ /// not change that.
+ static const unavailable = 'PAIRING_UNAVAILABLE';
+
+ @override
+ String toString() =>
+ label != null ? 'PhonePairAnswer.paired($label)' : 'failed($error)';
+}
+
+/// Hand the daemon [code] once. [cancel] is cancelled when the dialog closes:
+/// the transport should give up waiting on its long poll then.
+typedef PhonePairCall = Future<PhonePairAnswer> Function(
+ String code,
+ CancelToken cancel,
+);
+
+/// [PhonePairCall] over this app's own loopback client — the daemon's Unix
+/// socket, or its port (see [ApiClient]).
+PhonePairCall phonePairOverDaemon(ApiClient api) => (code, cancel) async {
+ try {
+ final (:status, :body) = await api.pair(code, cancelToken: cancel);
+ final error = body['error'];
+ if (status >= 200 && status < 300 && error == null) {
+ final label = body['label'];
+ return PhonePairAnswer.paired(
+ label is String && label.trim().isNotEmpty ? label.trim() : 'phone',
+ );
+ }
+ // A daemon from before `/api/pair` answers its catch-all 404, which is
+ // `{error: 'not found'}` — a code, but not one of the pairing's.
+ if (status == 404) {
+ return const PhonePairAnswer.failed(PhonePairAnswer.unavailable);
+ }
+ return PhonePairAnswer.failed(
+ error is String && error.isNotEmpty ? error : 'HTTP_$status',
+ );
+ } on DioException catch (error) {
+ return PhonePairAnswer.failed(switch (error.type) {
+ // Nobody on the port or the socket.
+ DioExceptionType.connectionError => PhonePairAnswer.unavailable,
+ DioExceptionType.unknown when error.error is SocketException =>
+ PhonePairAnswer.unavailable,
+ // Our own 60 s ran out on a handshake: the phone went quiet.
+ DioExceptionType.receiveTimeout ||
+ DioExceptionType.sendTimeout ||
+ DioExceptionType.connectionTimeout => 'TIMEOUT',
+ _ => 'UNREACHABLE',
+ });
+ }
+};
+
+/// A fresh one-time sign-in code for the QR and how long it stays good, or
+/// null when there is none to be had (see [ApiClient.phoneSignInCode]).
+typedef PhoneSignInCodeCall = Future<({String code, Duration ttl})?> Function();
+
+class AddPhoneDialog extends StatefulWidget {
+ const AddPhoneDialog({
+ super.key,
+ required this.app,
+ required this.pair,
+ required this.signInCode,
+ });
+
+ final AppNotifier app;
+ final PhonePairCall pair;
+ final PhoneSignInCodeCall signInCode;
+
+ @override
+ State<AddPhoneDialog> createState() => _AddPhoneDialogState();
+}
+
+class _AddPhoneDialogState extends State<AddPhoneDialog> {
+ /// With no phone waiting the daemon answers at once, so this is the whole
+ /// cadence of the loop: how soon after the phone's intent lands the
+ /// handshake starts. ⚠️ `NO_INTENT`, `EXPIRED` and `BUSY` are answered
+ /// BEFORE any handshake runs, and only a handshake that ran and failed
+ /// counts against the daemon's three-per-five-minutes limit (manager.ts
+ /// `failPair`) — so asking this often costs the person nothing.
+ static const _poll = Duration(milliseconds: 1500);
+ static const _rateLimited = Duration(seconds: 60);
+ static const _unexpected = Duration(seconds: 5);
+
+ /// How long "Connected" stays up before the dialog closes itself.
+ static const _connectedHold = Duration(milliseconds: 1500);
+
+ /// How often the QR gets a new sign-in code. Shorter than the code's own
+ /// life (90 s at the backend), so the one on screen always has at least
+ /// half a minute left in it when a phone reads it.
+ static const _signInRenew = Duration(seconds: 60);
+
+ AppNotifier get app => widget.app;
+
+ /// A fresh code each time the dialog opens, and a fresh one again after a
+ /// scan that did not match — see [_loop].
+ late String _code = newPhonePairCode();
+
+ /// ONE token for the dialog's whole life: cancelling it is closing.
+ final _cancel = CancelToken();
+ bool _closed = false;
+ bool _running = false;
+ Timer? _timer;
+ Completer<bool>? _sleeping;
+
+ /// The sign-in code in the QR, once asked for. Null after asking is a QR
+ /// without one: the phone then asks for an emailed code.
+ String? _signIn;
+ bool _signInAsked = false;
+ Timer? _signInTimer;
+
+ /// No pairing to be had from this daemon — asking stopped for good.
+ bool _stopped = false;
+ String? _connected;
+ String? _message;
+
+ /// A message that is an instruction to the person ("scan the new code"),
+ /// which the next "no phone yet" must not wipe before they have read it.
+ /// Everything else describes a condition, and goes when it does.
+ bool _sticky = false;
+
+ @override
+ void initState() {
+ super.initState();
+ app.addListener(_appChanged);
+ _syncLoop();
+ unawaited(_renewSignIn());
+ }
+
+ @override
+ void dispose() {
+ _closed = true;
+ app.removeListener(_appChanged);
+ _timer?.cancel();
+ _signInTimer?.cancel();
+ if (_sleeping case final sleeping? when !sleeping.isCompleted) {
+ sleeping.complete(false);
+ }
+ // ⚠️ This only stops WAITING. A handshake the daemon has already started
+ // runs to its end whatever happens here, and a phone that finishes it is
+ // paired: the person scanned the code, which is the consent. What closing
+ // does guarantee is that nothing arms the daemon again — the code dies
+ // with the QR.
+ _cancel.cancel('Add Phone closed');
+ super.dispose();
+ }
+
+ void _appChanged() {
+ if (_closed) return;
+ setState(() {});
+ _syncLoop();
+ }
+
+ /// Who and what the QR is for, or null while there is nothing to show yet.
+ ///
+ /// The machine is the one the phone will see in its own list: this
+ /// computer's row, whose id is the backend's once someone is signed in (the
+ /// daemon serves this computer under the account's `machineId` then — see
+ /// `AppNotifier._followLocalMachineId`).
+ ({String email, String machineId})? get _target {
+ if (app.isGuest) return null;
+ final email = app.currentUser?.email.trim();
+ final machineId = app.localMachineState?.machine.machineId;
+ // `CurrentUserProfile.local()` says "local terminal": not an address.
+ if (email == null || !email.contains('@')) return null;
+ if (machineId == null || machineId.isEmpty) return null;
+ return (email: email, machineId: machineId);
+ }
+
+ bool get _asking => !_closed && !_stopped && _connected == null;
+
+ /// Starts the loop when there is a QR worth arming and nothing is asking
+ /// yet. Called again whenever the app changes, so a profile that loads
+ /// after the dialog opened arms it then.
+ void _syncLoop() {
+ if (_running || !_asking || _target == null) return;
+ _running = true;
+ unawaited(_loop().whenComplete(() => _running = false));
+ }
+
+ Future<void> _loop() async {
+ while (_asking && _target != null) {
+ final code = _code;
+ PhonePairAnswer answer;
+ try {
+ answer = await widget.pair(code, _cancel);
+ } catch (error) {
+ answer = PhonePairAnswer.failed('$error');
+ }
+ // A long poll can come back long after the dialog went — a handshake
+ // that finished (or failed) behind a closed window must not touch it.
+ if (_closed) return;
+ if (answer.label case final label?) {
+ setState(() {
+ _connected = label;
+ _message = null;
+ });
+ if (await _sleep(_connectedHold) && mounted) {
+ Navigator.of(context).pop();
+ }
+ return;
+ }
+ final Duration wait;
+ switch (answer.error) {
+ // No phone yet, one whose minute ran out, or one mid-handshake with
+ // somebody else. Ask again.
+ case 'NO_INTENT' || 'EXPIRED' || 'BUSY':
+ if (!_sticky && _message != null) setState(() => _message = null);
+ wait = _poll;
+ case 'CODE_MISMATCH':
+ // The phone holds the old code and the daemon has spent it. A new
+ // one — and a new QR — is the only way forward.
+ _say("That didn't match. Scan the new code.", sticky: true);
+ setState(() => _code = newPhonePairCode());
+ wait = _poll;
+ case 'RATE_LIMITED':
+ _say('Too many tries. Wait a minute.');
+ wait = _rateLimited;
+ case 'BACKEND_DOWN':
+ _say("This ${_thisComputer()} can't reach Harness right now.");
+ wait = _poll;
+ // The phone started and went quiet, or said no. The QR is still
+ // good: scanning it again starts over.
+ case 'TIMEOUT':
+ _say('Your phone stopped answering. Scan again.', sticky: true);
+ wait = _poll;
+ case 'CANCELLED':
+ _say('Cancelled on your phone. Scan again.', sticky: true);
+ wait = _poll;
+ case PhonePairAnswer.unavailable:
+ _say('Update Harness on this ${_thisComputer()} to add a phone.');
+ setState(() => _stopped = true);
+ return;
+ case final other:
+ _say('Could not pair ($other). Trying again.');
+ wait = _unexpected;
+ }
+ if (!await _sleep(wait)) return;
+ }
+ }
+
+ /// Ask for a sign-in code, put it in the QR, and ask again before it runs
+ /// out — for as long as the QR is on screen. A failure is not retried
+ /// sooner: the QR works without one, and the next renewal tries again.
+ Future<void> _renewSignIn() async {
+ ({String code, Duration ttl})? next;
+ try {
+ next = await widget.signInCode();
+ } catch (_) {
+ next = null;
+ }
+ if (_closed || !mounted) return;
+ setState(() {
+ _signIn = next?.code;
+ _signInAsked = true;
+ });
+ if (_connected != null || _stopped) return;
+ final ttl = next?.ttl;
+ final wait = ttl != null && ttl - const Duration(seconds: 30) < _signInRenew
+ ? ttl - const Duration(seconds: 30)
+ : _signInRenew;
+ _signInTimer = Timer(
+ wait > Duration.zero ? wait : _signInRenew,
+ () => unawaited(_renewSignIn()),
+ );
+ }
+
+ void _say(String message, {bool sticky = false}) => setState(() {
+ _message = message;
+ _sticky = sticky;
+ });
+
+ /// A wait the dialog can cut short: true when it ran out, false when the
+ /// dialog closed. `Future.delayed` cannot be cancelled, and a timer left
+ /// behind by a closed dialog is one more wake-up for nothing.
+ Future<bool> _sleep(Duration duration) {
+ final done = Completer<bool>();
+ _sleeping = done;
+ _timer = Timer(duration, () {
+ if (!done.isCompleted) done.complete(!_closed);
+ });
+ return done.future;
+ }
+
+ void _close() => Navigator.of(context).maybePop();
+
+ TerminalTheme get _theme =>
+ terminalThemeFor(grid.AppTheme.palette.value, terminalThemeStore.value);
+ Color get _faint => _theme.foreground.withValues(alpha: .54);
+ TextStyle _ink([Color? color]) =>
+ terminalContentStyle(color: color ?? _theme.foreground);
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ // Live font and colour changes reach an open dialog too — see the dialog
+ // guide, design/terminal-dialogs.md.
+ return ListenableBuilder(
+ listenable: Listenable.merge([
+ terminalFontStore,
+ terminalThemeStore,
+ grid.AppTheme.palette,
+ ]),
+ builder: (context, _) => _dialog(context),
+ );
+ }
+
+ Widget _dialog(BuildContext context) {
+ // The grid: margins in whole character columns, spacing in whole rows.
+ final cell = terminalCellSizeOf(context);
+ final margin = cell.width * 2;
+ final row = cell.height;
+ // The window is the QR and one line: 240 points — a phone camera reads that
+ // from across a desk — in a whole number of rows, so the line under it stays
+ // on the grid, and the window just wider than the code.
+ final qrSide = (240 / row).ceil() * row;
+ final width = math.min(
+ qrSide + margin * 4,
+ MediaQuery.sizeOf(context).width - 32,
+ );
+ return TerminalPromptKeys(
+ cancel: _close,
+ child: Dialog(
+ insetPadding: const EdgeInsets.all(16),
+ elevation: 0,
+ backgroundColor: Colors.transparent,
+ child: SizedBox(
+ width: width,
+ child: Material(
+ elevation: 0,
+ color: _theme.background,
+ surfaceTintColor: Colors.transparent,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),
+ side: terminalPaneBorder(focused: true),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: DefaultTextStyle.merge(
+ style: _ink(),
+ child: SingleChildScrollView(
+ padding: EdgeInsets.fromLTRB(margin, row, margin, row),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ 'Add your phone',
+ textAlign: TextAlign.center,
+ style: _ink(),
+ ),
+ SizedBox(height: row),
+ ..._body(qrSide, row),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _body(double qrSide, double row) {
+ if (app.isGuest) {
+ return [Text('Sign in to add your phone.', style: _ink())];
+ }
+ final target = _target;
+ if (target == null) {
+ return [
+ Text(
+ app.currentUser?.email.contains('@') == true
+ ? 'Waiting for Harness on this ${_thisComputer()}…'
+ : 'Waiting for your account…',
+ style: _ink(_faint),
+ ),
+ ];
+ }
+ // A moment's wait for the sign-in code, in the QR's own space: a QR that
+ // changed right after it appeared would be one scanned without it.
+ if (!_signInAsked) return [SizedBox(height: qrSide + row * 2)];
+ final link = phonePairLink(
+ email: target.email,
+ machineId: target.machineId,
+ code: _code,
+ signIn: _signIn,
+ ).toString();
+ return [
+ Center(
+ // Dimmed once it has done its job, so nobody scans a spent code.
+ child: Opacity(
+ opacity: _connected == null && !_stopped ? 1 : .25,
+ child: PhonePairQr(data: link, side: qrSide),
+ ),
+ ),
+ SizedBox(height: row),
+ // One line, and it is the status too: what to do, then that it worked.
+ // The phone's own screen says the rest (Yes — scan to connect).
+ _status(),
+ ];
+ }
+
+ Widget _status() {
+ final connected = _connected;
+ final (text, color) = connected != null
+ ? ('✓ Connected $connected', _theme.green)
+ : _message != null
+ ? (_message!, _theme.red)
+ : ('Scan with Harness on your iPhone', _faint);
+ return Semantics(
+ liveRegion: true,
+ child: Text(
+ text,
+ key: const ValueKey('add-phone-status'),
+ textAlign: TextAlign.center,
+ style: _ink(color),
+ ),
+ );
+ }
+}
+
+/// "Mac" where the menu says Harness ▸ Add Phone…; the command palette also
+/// reaches this dialog on Linux, where "this Mac" would be wrong.
+String _thisComputer() =>
+ defaultTargetPlatform == TargetPlatform.macOS ? 'Mac' : 'computer';
+
+/// [data] as a QR code: dark modules on a white square with its quiet zone.
+///
+/// ⚠️ White and black whatever the theme. A dark-mode QR — light modules on a
+/// dark field — is one many phone cameras will not read, and the four-module
+/// white margin (the "quiet zone") is part of the code, not decoration: it is
+/// how a scanner finds the edges. So the white square stays, on every palette.
+class PhonePairQr extends StatelessWidget {
+ const PhonePairQr({super.key, required this.data, required this.side});
+
+ /// What the code says — the whole link, secret included.
+ final String data;
+ final double side;
+
+ static const _quietModules = 4;
+
+ // One entry: the dialog rebuilds on every font or palette change, and
+ // choosing the best of eight mask patterns is not free.
+ static (String, QrImage)? _cached;
+
+ static QrImage _imageOf(String data) {
+ if (_cached case (final cachedData, final image) when cachedData == data) {
+ return image;
+ }
+ final image = QrImage(
+ QrCode.fromData(data: data, errorCorrectLevel: QrErrorCorrectLevel.M),
+ );
+ _cached = (data, image);
+ return image;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final image = _imageOf(data);
+ final module = side / (image.moduleCount + _quietModules * 2);
+ return Semantics(
+ image: true,
+ label: 'QR code to add your phone',
+ child: Container(
+ width: side,
+ height: side,
+ decoration: BoxDecoration(
+ color: Colors.white,
+ borderRadius: BorderRadius.circular(module * 2),
+ ),
+ child: CustomPaint(painter: _QrPainter(image, data)),
+ ),
+ );
+ }
+}
+
+class _QrPainter extends CustomPainter {
+ _QrPainter(this.image, this.data);
+
+ final QrImage image;
+ final String data;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final count = image.moduleCount;
+ final total = count + PhonePairQr._quietModules * 2;
+ // Snapped to half a point — a whole device pixel on a Retina screen — so
+ // neighbouring modules meet exactly instead of leaving hairline seams.
+ final module = (size.shortestSide / total * 2).floorToDouble() / 2;
+ final origin = Offset(
+ (size.width - module * count) / 2,
+ (size.height - module * count) / 2,
+ );
+ final path = Path();
+ for (var y = 0; y < count; y++) {
+ for (var x = 0; x < count; x++) {
+ if (!image.isDark(y, x)) continue;
+ path.addRect(
+ Rect.fromLTWH(
+ origin.dx + x * module,
+ origin.dy + y * module,
+ module,
+ module,
+ ),
+ );
+ }
+ }
+ canvas.drawPath(
+ path,
+ Paint()
+ ..color = Colors.black
+ ..isAntiAlias = false,
+ );
+ }
+
+ @override
+ bool shouldRepaint(_QrPainter oldDelegate) => oldDelegate.data != data;
+}
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index e2ed06399..904d76709 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -605,9 +605,10 @@ class _SessionRow extends StatelessWidget {
'Ready' || 'Paused' || 'Working' || 'Needs input' => null,
final status => status,
};
- final activity = row.lastActiveAt == null
- ? 'Last activity unavailable'
- : 'Last active ${harnessActivityAge(row.lastActiveAt, now)} ago';
+ // The time the panel sorts by (Recently used), so the ages read in order.
+ final activity = row.lastUsedAt == null
+ ? 'Last use unknown'
+ : 'Last used ${harnessActivityAge(row.lastUsedAt, now)} ago';
Widget detail(IconData icon, String text, Color color, {String? tooltip}) =>
Tooltip(
message: tooltip ?? text,
@@ -716,16 +717,16 @@ class _SessionRow extends StatelessWidget {
),
),
),
- if (row.lastActiveAt != null)
+ if (row.lastUsedAt != null)
Padding(
padding: const EdgeInsets.only(
left: 8,
),
child: Tooltip(
message:
- 'Last active ${row.lastActiveAt!.toLocal()}',
+ 'Last used ${row.lastUsedAt!.toLocal()}',
child: Text(
- '· ${harnessActivityAge(row.lastActiveAt, now)}',
+ '· ${harnessActivityAge(row.lastUsedAt, now)}',
key: ValueKey(
'session-age:${row.id}',
),
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 3f4a59627..d253c998a 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1360,7 +1360,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
'${modelAction == null ? '' : ', $modelAction'}'
'${widget.unavailableReason == null ? '' : ', ${widget.unavailableReason}'}'
'${row.shortcut == null ? '' : ', Shortcut ${row.shortcut}'}'
- '${widget.activityAge == null ? '' : ', Last active ${widget.activityAge} ago'}',
+ '${widget.activityAge == null ? '' : ', Last used ${widget.activityAge} ago'}',
excludeSemantics: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 219c075e4..6cb52d128 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -230,6 +230,16 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
settings.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "settings")
settings.keyEquivalentModifierMask = [.command]
if settings.menu == nil { appMenu.insertItem(settings, at: min(2, appMenu.numberOfItems)) }
+ // Directly under Settings…, in its group: pairing a phone is a setting of
+ // this computer, not a workspace action. Same channel and same keymap hook
+ // as Settings (`app.add_phone` in keymap_commands.dart), so a binding a
+ // person gives it shows here. Dart owns the dialog (add_phone_dialog.dart).
+ let addPhone = NSMenuItem(title: "Add Phone…", action: #selector(menuAction(_:)), keyEquivalent: "")
+ addPhone.target = self
+ addPhone.representedObject = "addPhone"
+ addPhone.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "addPhone")
+ addPhone.image = NSImage(systemSymbolName: "iphone", accessibilityDescription: nil)
+ appMenu.insertItem(addPhone, at: appMenu.index(of: settings) + 1)
let customize = NSMenuItem(title: "Customize Harness", action: #selector(menuAction(_:)), keyEquivalent: "")
customize.target = self
customize.representedObject = "customize"
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index 9f33908d8..21f62cc7d 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -455,6 +455,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.6"
+ qr:
+ dependency: "direct main"
+ description:
+ name: qr
+ sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.2"
quiver:
dependency: transitive
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 1880f40a3..e537aebd3 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -49,6 +49,11 @@ dependencies:
# Pure Dart, so it registers no native plugin and leaves the macOS SPM
# package list untouched — see CLAUDE.md on what a plugin costs here.
unorm_dart: ^0.3.2
+ # The QR in Harness ▸ Add Phone… (`widgets/add_phone_dialog.dart`). The bare
+ # encoder, NOT `qr_flutter`: the dialog paints the modules itself in a few
+ # lines, and pure Dart registers no native plugin — see CLAUDE.md on what a
+ # plugin costs here.
+ qr: ^3.0.2
# Keep the terminal core in-tree until the upstream circular-buffer ownership
# fix is released. See third_party/xterm/lib/src/core/buffer/buffer.dart.
xterm:
diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dart
new file mode 100644
index 000000000..14a142f3e
--- /dev/null
+++ b/desktop/test/add_phone_dialog_test.dart
@@ -0,0 +1,425 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:dio/dio.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/add_phone_dialog.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+/// The alphabet the Add Phone contract names. The code must come from it —
+/// and, see [kPhonePairCodeAlphabet], from the part both normalisers agree on.
+const _contractAlphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
+
+/// A signed-in window whose machine `m` is this computer.
+AppNotifier _signedInApp() {
+ final app = createApp()
+ ..status = AppStatus.authenticated
+ ..signedIn = true
+ ..currentUser = const CurrentUserProfile(email: '[email protected]');
+ app.machineStates['m']!.localOnly = true;
+ return app;
+}
+
+/// A scripted daemon: answers in order, records every code it was handed.
+class _FakeDaemon {
+ _FakeDaemon(this.answers);
+
+ final List<FutureOr<PhonePairAnswer> Function()> answers;
+ final codes = <String>[];
+ final tokens = <CancelToken>[];
+
+ Future<PhonePairAnswer> call(String code, CancelToken cancel) async {
+ codes.add(code);
+ tokens.add(cancel);
+ return answers.removeAt(0)();
+ }
+}
+
+PhonePairAnswer Function() _failed(String code) =>
+ () => PhonePairAnswer.failed(code);
+
+/// A backend that mints sign-in codes `h1`, `h2`, … — or none at all.
+class _FakeSignIn {
+ _FakeSignIn({this.available = true});
+
+ final bool available;
+ var minted = 0;
+
+ Future<({String code, Duration ttl})?> call() async {
+ if (!available) return null;
+ minted++;
+ return (code: 'h$minted', ttl: const Duration(seconds: 90));
+ }
+}
+
+Future<void> _open(
+ WidgetTester tester,
+ AppNotifier app,
+ PhonePairCall pair, {
+ PhoneSignInCodeCall? signInCode,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: const Scaffold(body: SizedBox.expand()),
+ ),
+ );
+ unawaited(
+ showAddPhoneDialog(
+ tester.element(find.byType(Scaffold)),
+ app,
+ pair: pair,
+ signInCode: signInCode ?? _FakeSignIn().call,
+ ),
+ );
+ await tester.pump();
+ // The sign-in code's answer, which the QR waits for.
+ await tester.pump();
+}
+
+String _qrData(WidgetTester tester) =>
+ tester.widget<PhonePairQr>(find.byType(PhonePairQr)).data;
+
+String _status(WidgetTester tester) =>
+ tester.widget<Text>(find.byKey(const ValueKey('add-phone-status'))).data!;
+
+void main() {
+ group('the QR payload', () {
+ test('is the /pair link with everything in the fragment', () {
+ final link = phonePairLink(
+ email: '[email protected]',
+ machineId: '3f2c9a10-7d4e-4b8a-9c61-0e5f2a7b8c9d',
+ code: 'ABCDEFGHJKMNPQRS',
+ );
+ expect(
+ link.toString(),
+ 'https://harness.autonomous.ai/pair'
+ '#e=dee%2Bphone%40example.com'
+ '&m=3f2c9a10-7d4e-4b8a-9c61-0e5f2a7b8c9d'
+ '&c=ABCDEFGHJKMNPQRS',
+ );
+ // The code is the E2EE secret: a browser sends the query to the server
+ // and never the fragment.
+ expect(link.hasQuery, isFalse);
+ expect(link.query, isEmpty);
+ expect(link.path, '/pair');
+ // What the phone does with it (mobile ConnectCode.parse).
+ final scanned = Uri.parse(link.toString());
+ expect(Uri.splitQueryString(scanned.fragment), {
+ 'm': '3f2c9a10-7d4e-4b8a-9c61-0e5f2a7b8c9d',
+ 'c': 'ABCDEFGHJKMNPQRS',
+ });
+ });
+
+ test(
+ 'codes are 16 characters from the allowed alphabet, fresh each time',
+ () {
+ final seen = <String>{};
+ for (var i = 0; i < 500; i++) {
+ final code = newPhonePairCode();
+ expect(code, hasLength(16));
+ for (final char in code.split('')) {
+ expect(_contractAlphabet, contains(char), reason: code);
+ expect(kPhonePairCodeAlphabet, contains(char), reason: code);
+ }
+ seen.add(code);
+ }
+ expect(seen, hasLength(500));
+ // Every symbol turns up: nothing in the alphabet is unreachable.
+ final used = seen.join().split('').toSet();
+ expect(used, kPhonePairCodeAlphabet.split('').toSet());
+ },
+ );
+
+ test('no code carries a character the two normalisers disagree on', () {
+ // core.ts normalizeCode maps I L O U; the phone's does not.
+ final random = math.Random(7);
+ for (var i = 0; i < 2000; i++) {
+ expect(
+ newPhonePairCode(random: random),
+ isNot(matches(RegExp('[ILOU01]'))),
+ );
+ }
+ });
+ });
+
+ group('the sign-in code', () {
+ test('rides in the fragment as h, after the pairing code', () {
+ final link = phonePairLink(
+ email: '[email protected]',
+ machineId: 'm',
+ code: 'ABCDEFGHJKMNPQRS',
+ signIn: 'hnh_abc-_XYZ',
+ );
+ expect(link.hasQuery, isFalse);
+ expect(Uri.splitQueryString(Uri.parse(link.toString()).fragment), {
+ 'm': 'm',
+ 'c': 'ABCDEFGHJKMNPQRS',
+ 'h': 'hnh_abc-_XYZ',
+ });
+ });
+
+ testWidgets('is in the QR, and a new one replaces it every minute', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final signIn = _FakeSignIn();
+ final daemon = _FakeDaemon(List.filled(80, _failed('NO_INTENT')));
+ await _open(tester, app, daemon.call, signInCode: signIn.call);
+
+ expect(
+ Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment)['h'],
+ 'h1',
+ );
+ await tester.pump(const Duration(seconds: 60));
+ await tester.pump();
+ expect(signIn.minted, 2);
+ expect(
+ Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment)['h'],
+ 'h2',
+ );
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(minutes: 3));
+ expect(signIn.minted, 2, reason: 'nothing is minted after closing');
+ });
+
+ testWidgets('without one the QR still pairs — the phone emails a code', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon(List.filled(10, _failed('NO_INTENT')));
+ await _open(
+ tester,
+ app,
+ daemon.call,
+ signInCode: _FakeSignIn(available: false).call,
+ );
+ final fields = Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment);
+ expect(fields.keys, ['e', 'm', 'c']);
+ expect(fields['c'], daemon.codes.single);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 10));
+ });
+ });
+
+ group('arming the daemon', () {
+ testWidgets('retries while no phone is waiting and closes once paired', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon([
+ _failed('NO_INTENT'),
+ _failed('NO_INTENT'),
+ () => const PhonePairAnswer.paired('Dee’s iPhone'),
+ ]);
+ await _open(tester, app, daemon.call);
+
+ expect(find.text('Add your phone'), findsOneWidget);
+ expect(daemon.codes, hasLength(1));
+ final code = daemon.codes.single;
+ expect(
+ _qrData(tester),
+ phonePairLink(
+ email: '[email protected]',
+ machineId: 'm',
+ code: code,
+ signIn: 'h1',
+ ).toString(),
+ );
+ expect(_status(tester), 'Scan with Harness on your iPhone');
+
+ await tester.pump(const Duration(milliseconds: 1500));
+ expect(daemon.codes, [code, code]);
+ await tester.pump(const Duration(milliseconds: 1500));
+ expect(daemon.codes, [code, code, code]);
+ await tester.pump();
+ expect(_status(tester), '✓ Connected Dee’s iPhone');
+ expect(find.byType(AddPhoneDialog), findsOneWidget);
+
+ await tester.pump(const Duration(milliseconds: 1500));
+ await tester.pump();
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ expect(daemon.codes, hasLength(3));
+ });
+
+ testWidgets('a code that did not match is replaced, QR and all', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon([
+ _failed('CODE_MISMATCH'),
+ _failed('NO_INTENT'),
+ _failed('NO_INTENT'),
+ ]);
+ await _open(tester, app, daemon.call);
+ await tester.pump();
+ final first = daemon.codes.single;
+ expect(_status(tester), "That didn't match. Scan the new code.");
+ expect(_qrData(tester), isNot(contains('c=$first')));
+
+ await tester.pump(const Duration(milliseconds: 1500));
+ expect(daemon.codes, hasLength(2));
+ final second = daemon.codes.last;
+ expect(second, isNot(first));
+ expect(_qrData(tester), contains('c=$second&'));
+ // An instruction outlives the "no phone yet" that follows it.
+ await tester.pump();
+ expect(_status(tester), "That didn't match. Scan the new code.");
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ expect(daemon.tokens.last.isCancelled, isTrue);
+ await tester.pump(const Duration(seconds: 10));
+ expect(daemon.codes, hasLength(2), reason: 'nothing asks after closing');
+ });
+
+ testWidgets('rate limited waits a minute before asking again', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon([
+ _failed('RATE_LIMITED'),
+ _failed('NO_INTENT'),
+ ]);
+ await _open(tester, app, daemon.call);
+ await tester.pump();
+ expect(_status(tester), 'Too many tries. Wait a minute.');
+ await tester.pump(const Duration(seconds: 59));
+ expect(daemon.codes, hasLength(1));
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pump();
+ expect(daemon.codes, hasLength(2));
+ expect(_status(tester), 'Scan with Harness on your iPhone');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ });
+
+ testWidgets('a daemon that cannot pair stops the loop', (tester) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon([_failed(PhonePairAnswer.unavailable)]);
+ await _open(tester, app, daemon.call);
+ await tester.pump();
+ expect(_status(tester), startsWith('Update Harness on this '));
+ await tester.pump(const Duration(seconds: 30));
+ expect(daemon.codes, hasLength(1));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ });
+
+ testWidgets('a long poll that ends after closing touches nothing', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final answer = Completer<PhonePairAnswer>();
+ final daemon = _FakeDaemon([() => answer.future]);
+ await _open(tester, app, daemon.call);
+ expect(daemon.codes, hasLength(1));
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ expect(daemon.tokens.single.isCancelled, isTrue);
+
+ answer.complete(const PhonePairAnswer.paired('Late phone'));
+ await tester.pump(const Duration(seconds: 5));
+ expect(tester.takeException(), isNull);
+ expect(daemon.codes, hasLength(1));
+ });
+
+ testWidgets('a guest is asked to sign in, and nothing is armed', (
+ tester,
+ ) async {
+ final app = _signedInApp()..signedIn = false;
+ addTearDown(app.dispose);
+ final daemon = _FakeDaemon([]);
+ await _open(tester, app, daemon.call);
+ expect(find.text('Sign in to add your phone.'), findsOneWidget);
+ expect(find.byType(PhonePairQr), findsNothing);
+ expect(daemon.codes, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ });
+ });
+
+ group('the way in', () {
+ // `createApp` has no profile and no local machine, so the dialog opens
+ // with nothing to arm — these tests never reach for a real daemon.
+ testWidgets('Harness ▸ Add Phone… opens the dialog', (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (_) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final app = createApp()..status = AppStatus.authenticated;
+ addTearDown(app.dispose);
+ await mount(tester, app, nativeTabs: true);
+
+ final handled = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('addPhone'),
+ ),
+ (_) => handled.complete(),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(find.text('Add your phone'), findsOneWidget);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await handled.future;
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('> add phone opens the dialog from the command search', (
+ tester,
+ ) async {
+ final app = createApp()..status = AppStatus.authenticated;
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> add phone',
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(AddPhoneDialog), findsOneWidget);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+ });
+}
diff --git a/desktop/test/add_phone_transport_test.dart b/desktop/test/add_phone_transport_test.dart
new file mode 100644
index 000000000..4849a4467
--- /dev/null
+++ b/desktop/test/add_phone_transport_test.dart
@@ -0,0 +1,80 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:dio/dio.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/widgets/add_phone_dialog.dart';
+
+/// Add Phone's transport against a real loopback server standing in for the
+/// daemon. Its own file, with no `testWidgets`: under the widget binding every
+/// HttpClient answers 400 without touching the network.
+void main() {
+ group('the transport', () {
+ ApiClient client(int port) => ApiClient(
+ config: AppConfig(
+ apiBaseUrl: 'http://unused.invalid',
+ localCliBaseUrl: 'http://127.0.0.1:$port',
+ ),
+ session: AuthSession(),
+ );
+
+ test(
+ 'POSTs the code to /api/pair and reads the daemon\'s own codes',
+ () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final seen = <(String, String, String?, Object?)>[];
+ final replies = [
+ (409, {'error': 'NO_INTENT'}),
+ (200, {'label': 'Dee’s iPhone', 'fingerprint': 'ab:cd'}),
+ (404, {'error': 'not found'}),
+ ];
+ final subscription = server.listen((request) async {
+ seen.add((
+ request.method,
+ request.uri.path,
+ request.headers.value('x-adapter-local'),
+ jsonDecode(await utf8.decodeStream(request)),
+ ));
+ final (status, body) = replies.removeAt(0);
+ request.response
+ ..statusCode = status
+ ..headers.contentType = ContentType.json
+ ..write(jsonEncode(body));
+ await request.response.close();
+ });
+ try {
+ final pair = phonePairOverDaemon(client(server.port));
+ expect((await pair('CODE', CancelToken())).error, 'NO_INTENT');
+ expect((await pair('CODE', CancelToken())).label, 'Dee’s iPhone');
+ expect(
+ (await pair('CODE', CancelToken())).error,
+ PhonePairAnswer.unavailable,
+ reason: 'a daemon from before /api/pair',
+ );
+ final (method, path, localHeader, body) = seen.first;
+ expect((method, path), ('POST', '/api/pair'));
+ // The daemon's CSRF gate refuses a write without it.
+ expect(localHeader, '1');
+ expect(body, {'code': 'CODE'});
+ } finally {
+ await subscription.cancel();
+ await server.close(force: true);
+ }
+ },
+ );
+
+ test('nobody listening is a daemon that cannot pair', () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final port = server.port;
+ await server.close(force: true);
+ final answer = await phonePairOverDaemon(client(port))(
+ 'CODE',
+ CancelToken(),
+ );
+ expect(answer.error, PhonePairAnswer.unavailable);
+ });
+ });
+}
diff --git a/desktop/test/agent_last_used_test.dart b/desktop/test/agent_last_used_test.dart
new file mode 100644
index 000000000..cdefad7ea
--- /dev/null
+++ b/desktop/test/agent_last_used_test.dart
@@ -0,0 +1,117 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'support/rename_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+/// Opening a harness stamps it on its own daemon (`agent_update {opened}`), so
+/// every client's "last used" order moves with it.
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late RenameConnection connection;
+ late AppNotifier app;
+ setUp(() {
+ connection = RenameConnection();
+ app = createApp(connectionForTest: (_) => connection, connected: true);
+ });
+ tearDown(() => app.dispose());
+
+ Map<String, dynamic> opened(String id) => {'agentId': id, 'opened': true};
+
+ test('one stamp per harness inside the debounce window', () {
+ app.touchAgent('m', 'a0');
+ app.touchAgent('m', 'a0');
+ app.touchAgent('m', 'a0');
+ expect(connection.renames, [opened('a0')]);
+ });
+
+ test('A, B, A in quick succession is three opens, not two', () {
+ app.touchAgent('m', 'a0');
+ app.touchAgent('m', 'a1');
+ app.touchAgent('m', 'a0');
+ expect(connection.renames, [opened('a0'), opened('a1'), opened('a0')]);
+ });
+
+ test(
+ 'the daemon\'s stamp in the reply lands without waiting for a push',
+ () async {
+ final stamp = DateTime.utc(2026, 9, 26, 12);
+ app.touchAgent('m', 'a0');
+ connection.replies.single.complete({
+ 'agent': {'id': 'a0', 'lastOpenedAt': stamp.toIso8601String()},
+ });
+ await pumpEventQueue();
+ final agent = app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0');
+ expect(agent.lastOpenedAt, stamp);
+ expect(agent.lastUsedAt, stamp);
+ expect(agent.name, 'Agent 0');
+ },
+ );
+
+ test('an older daemon\'s refusal or a dead socket is swallowed', () async {
+ app.touchAgent('m', 'a0');
+ app.touchAgent('m', 'a1');
+ connection.replies.first.complete({'error': 'MISSING_UPDATE'});
+ connection.replies.last.completeError(StateError('socket closed'));
+ await pumpEventQueue();
+ expect(
+ app.stateOf('m')!.agents.every((a) => a.lastOpenedAt == null),
+ isTrue,
+ );
+ expect(app.lastError, isNull);
+ });
+
+ test('never for a disconnected machine or a view-only shared harness', () {
+ app.stateOf('m')!.connectionStatus = ConnectionStatus.disconnected;
+ app.touchAgent('m', 'a0');
+ app.machineStates['shared'] =
+ MachineState(
+ const Machine(
+ machineId: 'shared',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ ),
+ )
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agents = const [Agent(id: 's0', name: 'Shared')];
+ app.touchAgent('shared', 's0');
+ app.touchAgent('missing', 'a0');
+ expect(connection.renames, isEmpty);
+ });
+
+ test('a person focusing a harness stamps it; clicks inside it and a '
+ 'device\'s move do not', () {
+ final first = app.adoptSessionForTest(terminal('a0', []));
+ final second = app.adoptSessionForTest(terminal('a1', []));
+ // A restored layout puts a tile in front without anybody opening it.
+ expect(connection.renames, isEmpty);
+
+ app.focusPane(first.id, reveal: true);
+ expect(connection.renames, [opened('a0')]);
+ // The grid's pointer-down re-focuses the tile already in front.
+ app.focusPane(first.id);
+ app.focusPane(first.id);
+ expect(connection.renames, [opened('a0')]);
+
+ app.focusPane(second.id);
+ expect(connection.renames, [opened('a0'), opened('a1')]);
+
+ // Native focus echoing a reparent is the renderer's doing, not a person's.
+ app.focusPaneFromRenderer(first.id);
+ expect(connection.renames, hasLength(2));
+ // …but the next gesture on the harness it left in front is an open again.
+ app.focusPane(first.id);
+ expect(connection.renames, [opened('a0'), opened('a1'), opened('a0')]);
+ });
+
+ test('adding a harness to the grid opens it', () async {
+ // No terminal capability yet: the tile is placed, nothing is attached.
+ expect(app.stateOf('m')!.terminalCapabilityAvailable, isFalse);
+ await app.addAgentToSwarm('m', 'a3');
+ expect(app.focusedPane?.agentId, 'a3');
+ expect(connection.renames, [opened('a3')]);
+ });
+}
diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dart
index d8b4f817b..e5d6f66d0 100644
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@ -140,6 +140,7 @@ void main() {
});
_dshTests();
_cloneTests();
+ _lastUsedTests();
test('uses explicit terminal availability from a new CLI', () {
final dormantPane = Agent.fromJson({
'id': 'agent-1',
@@ -455,3 +456,83 @@ void _cloneTests() {
});
});
}
+
+/// `lastOpenedAt` and the "last used" order built on it.
+void _lastUsedTests() {
+ group('last used', () {
+ final active = DateTime.utc(2026, 9, 26, 10);
+ final opened = DateTime.utc(2026, 9, 26, 12);
+
+ test('reads lastOpenedAt, and a daemon that sends null or nothing', () {
+ final parsed = Agent.fromJson({
+ 'id': 'a',
+ 'updatedAt': active.toIso8601String(),
+ 'lastOpenedAt': opened.toIso8601String(),
+ });
+ expect(parsed.lastActivityAt, active);
+ expect(parsed.lastOpenedAt, opened);
+ expect(parsed.copyWith(name: 'Renamed').lastOpenedAt, opened);
+ expect(
+ Agent.fromJson({'id': 'a', 'lastOpenedAt': null}).lastOpenedAt,
+ isNull,
+ );
+ // An older daemon: the field is absent altogether.
+ expect(Agent.fromJson({'id': 'a'}).lastOpenedAt, isNull);
+ expect(
+ Agent.fromJson({'id': 'a', 'lastOpenedAt': 'not a time'}).lastOpenedAt,
+ isNull,
+ );
+ expect(
+ Agent.fromJson({'id': 'a', 'lastOpenedAt': 42}).lastOpenedAt,
+ isNull,
+ );
+ });
+
+ test('lastUsedAt is the later of activity and the last open', () {
+ Agent agent({DateTime? activity, DateTime? open}) => Agent(
+ id: 'a',
+ name: 'a',
+ lastActivityAt: activity,
+ lastOpenedAt: open,
+ );
+ expect(agent().lastUsedAt, isNull);
+ expect(agent(activity: active).lastUsedAt, active);
+ expect(agent(open: opened).lastUsedAt, opened);
+ expect(agent(activity: active, open: opened).lastUsedAt, opened);
+ expect(agent(activity: opened, open: active).lastUsedAt, opened);
+ expect(
+ agent(activity: active).copyWith(lastOpenedAt: opened).lastUsedAt,
+ opened,
+ );
+ });
+
+ test('a push that only moves lastOpenedAt is a change to the roster', () {
+ final raw = {
+ 'id': 'a',
+ 'name': 'Work',
+ 'updatedAt': active.toIso8601String(),
+ };
+ final agent = Agent.fromJson(raw);
+ expect(AppNotifier.agentsEqual([agent], [Agent.fromJson(raw)]), isTrue);
+ final touched = Agent.fromJson({
+ ...raw,
+ 'lastOpenedAt': opened.toIso8601String(),
+ });
+ expect(AppNotifier.agentsEqual([agent], [touched]), isFalse);
+ expect(
+ AppNotifier.agentsEqual(
+ [touched],
+ [
+ Agent.fromJson({
+ ...raw,
+ 'lastOpenedAt': opened
+ .add(const Duration(seconds: 1))
+ .toIso8601String(),
+ }),
+ ],
+ ),
+ isFalse,
+ );
+ });
+ });
+}
diff --git a/desktop/test/bios_navigation_test.dart b/desktop/test/bios_navigation_test.dart
index 7102c0903..ed7871162 100644
--- a/desktop/test/bios_navigation_test.dart
+++ b/desktop/test/bios_navigation_test.dart
@@ -138,6 +138,69 @@ void main() {
},
);
+ testWidgets(
+ 'Open Harness sorts by when the conversation last moved: opening a '
+ 'harness does not move it',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ Agent agent(String id, int active, {int? opened}) => Agent(
+ id: id,
+ sessionId: 'session-$id',
+ name: 'Agent $id',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: DateTime.utc(2026, 9, 26, active),
+ lastOpenedAt: opened == null ? null : DateTime.utc(2026, 9, 26, opened),
+ );
+ app.machineStates['m']!.agents = [
+ agent('busy', 11),
+ agent('quiet', 9, opened: 12),
+ agent('idle', 10),
+ // Opened long ago, then busy since: activity is the later of the two.
+ agent('worked', 8, opened: 7),
+ ];
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ activityFirst: true,
+ placement: HarnessPlacement.newTab,
+ );
+ addTearDown(search.dispose);
+ List<String?> order() => [
+ for (final row in search.rows)
+ if (!row.isCreate) row.agentId,
+ ];
+ // The owner: "use conversation last move, not last open — that's the
+ // true timestamp". `quiet`, opened at 12 but quiet since 9, stays put.
+ expect(order(), ['busy', 'idle', 'quiet', 'worked']);
+ expect(
+ search.rows.firstWhere((row) => row.agentId == 'quiet').lastActivityAt,
+ DateTime.utc(2026, 9, 26, 9),
+ );
+
+ // Another client opens `idle`: the daemon's push carries only the new
+ // open stamp, and an open is not work, so nothing moves.
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'idle',
+ 'sessionId': 'session-idle',
+ 'name': 'Agent idle',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ 'updatedAt': '2026-09-26T10:00:00Z',
+ 'lastOpenedAt': '2026-09-26T13:00:00Z',
+ },
+ },
+ });
+ expect(order(), ['busy', 'idle', 'quiet', 'worked']);
+ },
+ );
+
test(
'activity ordering spans tabs with deterministic ties and missing times',
() {
diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dart
index 0c1ea7d68..236acbec4 100644
--- a/desktop/test/command_dock_interaction_test.dart
+++ b/desktop/test/command_dock_interaction_test.dart
@@ -76,7 +76,21 @@ void main() {
terminalAvailable: true,
lastActivityAt: DateTime.now().subtract(const Duration(minutes: 33)),
),
- ...app.machineStates['m']!.agents.skip(1),
+ // Quiet for hours, though opened a moment ago in some client: an open
+ // is not work, so the age is the conversation's — three hours.
+ () {
+ final quiet = app.machineStates['m']!.agents[1];
+ return Agent(
+ id: quiet.id,
+ name: quiet.name,
+ engine: quiet.engine,
+ project: quiet.project,
+ terminalAvailable: true,
+ lastActivityAt: DateTime.now().subtract(const Duration(hours: 3)),
+ lastOpenedAt: DateTime.now().subtract(const Duration(minutes: 5)),
+ );
+ }(),
+ ...app.machineStates['m']!.agents.skip(2),
];
await configured.mount(tester, app, map);
await openHarnessPicker(tester);
@@ -89,6 +103,19 @@ void main() {
find.descendant(of: row, matching: find.text('33m')),
findsOneWidget,
);
+ final opened = find.byKey(ValueKey(agentDestinationId('m', 'a1')));
+ expect(
+ find.descendant(of: opened, matching: find.text('3h')),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<Tooltip>(
+ find.descendant(of: opened, matching: find.byType(Tooltip)),
+ )
+ .message,
+ startsWith('Last active '),
+ );
expect(
find.descendant(of: row, matching: find.byType(SearchResultText)),
findsOneWidget,
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index 2cd2b6c9f..066bc7ce4 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -156,6 +156,97 @@ void main() {
);
});
+ test(
+ 'recent sorts by last use: a harness opened anywhere outranks a busier one',
+ () {
+ app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'busy', 'updatedAt': '2026-09-26T11:00:00Z'}),
+ // Quiet since nine, but somebody opened it at noon — in any client.
+ Agent.fromJson({
+ 'id': 'opened',
+ 'updatedAt': '2026-09-26T09:00:00Z',
+ 'lastOpenedAt': '2026-09-26T12:00:00Z',
+ }),
+ // Opened long ago and busy since: the later of the two counts.
+ Agent.fromJson({
+ 'id': 'worked',
+ 'updatedAt': '2026-09-26T10:00:00Z',
+ 'lastOpenedAt': '2026-09-26T08:00:00Z',
+ }),
+ const Agent(id: 'unknown', name: 'Unknown'),
+ ];
+ for (final id in ['busy', 'opened', 'worked', 'unknown']) {
+ app.rememberOpenedHarness('m', id);
+ }
+ expect(SessionSort.recent.label, 'Recently used');
+ expect(
+ visibleHarnessSessions(harnessSessions(app)).map((row) => row.agent.id),
+ ['opened', 'busy', 'worked', 'unknown'],
+ );
+ expect(
+ harnessSessions(app)
+ .singleWhere((row) => row.agent.id == 'opened')
+ .lastUsedAt,
+ DateTime.utc(2026, 9, 26, 12),
+ );
+ },
+ );
+
+ testWidgets('each row shows and says the time it is sorted by', (
+ tester,
+ ) async {
+ final now = DateTime.now();
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: _running.id,
+ name: _running.name,
+ engine: _running.engine,
+ sessionId: _running.sessionId,
+ terminalAvailable: true,
+ project: _project,
+ lastActivityAt: now.subtract(const Duration(hours: 3)),
+ lastOpenedAt: now.subtract(const Duration(minutes: 5)),
+ ),
+ _paused,
+ ];
+ await open(tester);
+ final id = agentDestinationId('m', 'a0');
+ final age = find.byKey(ValueKey('session-age:$id'));
+ expect(tester.widget<Text>(age).data, '· 5m');
+ expect(
+ tester
+ .widget<Tooltip>(
+ find.ancestor(of: age, matching: find.byType(Tooltip)).first,
+ )
+ .message,
+ startsWith('Last used '),
+ );
+ expect(
+ tester
+ .widget<Semantics>(find.byKey(ValueKey('session-open:$id')))
+ .properties
+ .value,
+ contains('Last used 5m ago'),
+ );
+ // A daemon with no time for it at all.
+ expect(
+ tester
+ .widget<Semantics>(
+ find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', 'saved')}'),
+ ),
+ )
+ .properties
+ .value,
+ contains('Last use unknown'),
+ );
+ await tester.tap(find.byTooltip('Sort harnesses'));
+ await tester.pumpAndSettle();
+ expect(find.text('Recently used'), findsOneWidget);
+ expect(find.text('Recently active'), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
testWidgets(
'displays remote cached tokens beneath context and leaves missing usage empty',
(tester) async {
diff --git a/docs/plans/2026-09-26-001-mobile-zero-questions.md b/docs/plans/2026-09-26-001-mobile-zero-questions.md
new file mode 100644
index 000000000..1dd42333a
--- /dev/null
+++ b/docs/plans/2026-09-26-001-mobile-zero-questions.md
@@ -0,0 +1,194 @@
+# Mobile: zero questions
+
+September 26, 2026. A review of the phone app (1.0.0 build 45) and the plan to rebuild it around one
+rule: **open the app and have no questions.**
+
+## What a new person meets today
+
+From a fresh install to the first agent, on the happy path, the phone requires:
+
+1. **Sign in** — "Sign in with the email of your Autonomous account." Nothing says what Autonomous
+ is, there is no sign-up, and the app never says it needs a computer. Switch to Mail for a 4-digit
+ code.
+2. **A notification prompt**, the instant sign-in ends, before anything has been shown.
+3. **Machines** — every computer reads "Needs its password". Nothing says what password or where it
+ is set (on the desktop: Machines ▸ Set password, which is not set by default). With no computer,
+ "No machines yet" is a dead end: no button, no link, and the list never refreshes, so a computer
+ set up afterwards does not appear until the app is relaunched.
+4. **Link** — "This computer isn't linked to X yet. Enter the remote password…". Walk to the
+ computer. Errors quote CLI commands (`harness start`, `harness remote-password set`); progress
+ shows raw protocol names (`deriving_key`).
+5. **New Harness** — a desktop form: machine, four project sources, branch, worktree, 14 engines,
+ Codex profiles, five approval modes.
+6. **A terminal**, with no way back to a list and no sign of which other agent needs you.
+
+Prerequisites nobody is told about: Harness installed on a Mac or Linux computer, signed in with the
+same email (not as a guest), running and awake, with a remote password set.
+
+After that the app is **11 screens, 19 sheets and dialogs, ~120 controls, 13 gestures and ~30
+concepts** (harness, agent, engine, machine, link, remote password, desk tab, worktree, approvals,
+take control, Live/Attaching/Resyncing…, `>` `#` `@` `?` search modes, usage windows…). Most of it
+is the desktop carried onto a phone. What works on the go — watching one agent's live stream and
+talking to it — is buried under it, and moving between agents means a hidden swipe inside a desk tab,
+or three taps through tab pills to reach another tab.
+
+## The target
+
+A phone is where you **watch and talk to the one to three agents you picked**, on the go — in the
+car, walking. Agents mostly run on their own now (auto-approve), so the phone is not a triage inbox:
+you choose the few you want to work with out of five to ten (or a hundred at a desk), then watch their
+live stream and talk to them. Everything else stays on the computer.
+
+### First launch: one screen, one action
+
+```
+┌─────────────────────────────┐
+│ │
+│ [ live camera viewfinder ]│
+│ │
+│ Scan the code on your │
+│ computer │
+│ │
+│ In Harness on your Mac, │
+│ click Phone │
+│ │
+│ No Harness on your │
+│ computer yet? Get it → │
+└─────────────────────────────┘
+```
+
+Scan → "Connected to your MacBook" → your most recent agent. No email, no code, no password, no machine list.
+"Get it →" opens the share sheet with the download link, so it can be sent to the computer.
+
+The computer side is one button: **Phone** in the desktop app (and a step in desktop onboarding)
+shows a QR code. The same QR is a universal link: a camera that scans it without the app installed
+lands on the App Store page.
+
+### After: Focus, with Find and New a swipe either side (Snapchat's layout)
+
+```
+ Find ← swipe right ─ Focus ─ swipe left → New
+┌──────────────┐░░ ┌────────────────────────┐ ┌──────────────┐
+│ ⌕ Find… + │░░ │ fix login test ⌄ · Mac │ │ What should │
+│ fix login ✓ │░░ │ │ │ it do? │
+│ docs rewrite │░░ │ live terminal, full │ │ │
+│ payments bug │░░ │ screen to the bottom │ │ │
+└──────────────┘░░ │ (🎤) │ └──────────────┘
+ └────────────────────────┘
+```
+
+- **Focus** (home) is Snapchat's camera: one agent's live terminal, full screen, and the mic. It
+ opens on the agent you last worked with, on any device.
+- **Swipe right → Find**, a drawer in from the left edge that follows the finger: your **recent
+ agents first**, full-width two-line rows so long names fit. Type or say a few words to narrow — it
+ matches name, project, computer, what the agent is doing and what it said; no `>` `#` `@` `?` modes.
+ Tap a row and you are back in Focus on that agent; swipe left or tap the terminal beside it to
+ close. **Tapping the agent's name** (it wears a `⌄`) opens Find too, so the swipe is never the only
+ way in.
+- **Swipe left → New**: a new agent on the same computer; the form slides in from the right. Find
+ has a `+` for it as well.
+- **Settings** stays in the `⋮` menu.
+
+The places never move, so the thumb learns them — what makes Snapchat fast once learned. The swipes
+live on the terminal only; the terminal scrolls vertically and the key bar keeps its own sideways
+scroll. **No bar** at the foot (it cost full screen) and **no swipe between agents**.
+
+**Words:** *computer* (never "machine") and the agent's own name for the work ("fix the login bug").
+No "link", "remote password", "desk", "tab", "worktree", "engine", "take control", or connection
+states unless something is actually broken.
+
+## The plan
+
+Three tracks. Track A can ship this week on its own; B and C together deliver the target.
+
+### A. Stop the bleeding — phone only, days
+
+Ship on the current app while B and C are built:
+
+- A first screen that says what this is and what you need: *"Harness on your phone runs the agents
+ on your computer. Get Harness on your Mac first."* with a share button for the link.
+- Sign-in copy: *"Your email"* / *"We'll email you a code"* — drop "Autonomous account". Confirm what
+ the account API does with an unknown email; if it does not create the account, say so in one line
+ with the sign-up link.
+- "No computers yet" gets a button (share the download link) and refreshes itself every few seconds
+ while it is on screen.
+- Link page: say where the password is — *"On your computer: Harness ▸ Machines ▸ Set password"* —
+ autofocus the field, and replace raw stage names and CLI commands in errors with plain sentences.
+- Ask for notifications the first time an agent finishes, not at sign-in.
+- Fix copy written for the desktop: "Connecting this window to the local Harness service",
+ "This computer isn't linked", "Your previous harness will reconnect".
+
+### B. One scan instead of sign-in and a password — phone + desktop + backend
+
+**B1. The QR links the computer (no protocol change).** The daemon still has the live-code pairing
+the retired web client used (`e2e_pair_intent` → CPace, `cli/src/lib/e2ee/manager.ts:405`). The
+desktop generates a high-entropy one-time code and shows it as a QR with the machine id and key
+fingerprint. The phone scans, sends the pair intent; the desktop sees it pending and completes the
+pairing with the same code. Work: a scanner on the phone and a port of the pairing context from
+`cli/src/lib/e2ee/core.ts`; a QR and a "waiting for your phone" state on the desktop; optionally, let
+the desktop arm the code so the daemon answers the intent without polling. **Removes the remote
+password from the phone path entirely.** Estimate: 1–1.5 weeks.
+
+Until B2 lands, the QR also carries the account email: the phone pre-fills it and sends the code
+itself, so first run is *scan → type 4 digits (autofilled from Mail) → your agent*.
+
+**B2. The QR signs the phone in too.** The backend issues no tokens of its own today — every route
+checks an Autonomous token (`backend/src/routes/auth.ts:47`, `backend/src/lib/ssoAuth.ts`). Add a
+phone handoff: the signed-in desktop asks the backend for a single-use code (2-minute TTL, modelled
+on `backend/src/lib/deviceAuth.ts`), puts it in the QR, and the phone redeems it for a phone-scoped
+token that the relay, the REST middleware and refresh all accept, revocable per phone from the
+desktop. First run becomes *scan → your agent*. Estimate: 2 weeks plus a security review; it touches every
+auth path.
+
+A cheaper route to B2 exists if auth.autonomous.ai offers a token exchange or device grant — check
+first.
+
+**B3. One scan, every computer.** A desktop that already trusts other computers introduces the phone
+to them, so a person with two Macs scans once. New protocol; after B1/B2, only if people ask.
+
+### C. Rebuild the signed-in app — phone only, 2–3 weeks, parallel with B
+
+- Keep what works on the go: the terminal page and the voice input (`phone/terminal_page.dart`,
+ `phone/voice_*`), on the existing state, WS, E2EE and terminal code (`lib/state`, `lib/ws`,
+ `lib/e2ee`, `lib/terminal` stay).
+- Build Find as above: one search, recents first, matching on the fields the desktop's content index
+ already has (`phone/phone_search_*`), voice as an input to it.
+- New becomes one voice/text field; Settings shrinks to four rows.
+- Take control happens implicitly on the first keystroke or voice send; no band, no button.
+- An agent that finished or is asking puts a dot beside the name's `⌄`, and its row rises in Find.
+ No inbox.
+- **Delete from the phone:** the swipe pager (`phone/agent_swipe.dart`) and the look-ahead attach;
+ desk tabs and their panel/strip/sheets; the `>` `#` `@` `?` command palette and two of the three
+ searches; branch/worktree/engine/profile/approval pickers and the remote folder browser; Usage and
+ Stats; terminal font/size/colors and palette; Rename; machine administration beyond "Add a
+ computer" and "Remove"; the hidden tab shell, `AgentsPage`, `MachineSwipeHost`, the Model sheet and
+ hold-to-talk. Most of `lib/phone/` (94 files, ~25k lines) goes.
+
+### Targets
+
+| | Today | Target |
+|---|---|---|
+| Steps from install to a live agent | sign in + code + find machine + password + link | **scan** |
+| Things to type | email, code, password | nothing |
+| Screens / sheets | 11 / 19 | 2 (Focus, New) / 1 (Find) |
+| Concepts named | ~30 | 2: computer, agent |
+| Switch to another agent | swipe within a tab; 3 taps across tabs | Find → row, across every computer |
+| Gestures to learn | 13 | 2: swipe right (Find), swipe left (New) — each also a tap |
+
+**The test:** hand the phone to someone who has Harness on their Mac and has never seen the app. They
+reach a working agent, talk to it, and switch to another without asking anything. Run it before each
+TestFlight build.
+
+## Decisions for you
+
+1. **B2 or B1+email.** B2 (scan signs you in) is the only way to zero typing; it is two weeks and a
+ security review on every auth path. B1 with a pre-filled email ships sooner and costs 4 digits.
+2. **Word for a session on the phone.** The app and desktop say "Harness" for one session ("New
+ Harness", "Stop Harness"). On the phone this plan uses the agent's own name and *New* instead,
+ so a new person meets one word — Harness — as the app. Keep, or align the phone with the desktop?
+3. **No computer at all.** The backend has cloud machines (`self`/`managed` in
+ `backend/src/services/MachineService.ts`) that the phone filters out. A "Try it in the cloud" path
+ would answer "I don't have Harness on my computer" in-app; it is out of scope here and needs its
+ own look.
+4. **App Review.** Reviewers cannot scan a QR. A hidden demo account or a canned demo agent is
+ needed for submission either way.
diff --git a/docs/plans/2026-09-26-002-mobile-terminal-ux-spec.md b/docs/plans/2026-09-26-002-mobile-terminal-ux-spec.md
new file mode 100644
index 000000000..c03762820
--- /dev/null
+++ b/docs/plans/2026-09-26-002-mobile-terminal-ux-spec.md
@@ -0,0 +1,98 @@
+# Mobile: the terminal-native UX spec (the room, round 1)
+
+September 26, 2026. Four expert seats reviewed renders of the phone app — a mobile UI/UX designer
+(the Jony Ive seat), a terminal/TUI purist (the Woz seat, checking against real tmux 3.5a, fzf 0.67
+and zsh), a visual designer, and a heavy Claude Code/Codex user — each scored it 6/10, then argued
+the conflicts; a product lead (the Jobs seat) made the calls. Owner decisions that stand: full-screen
+terminal, the floating mic, Snapchat swipes (right = Find, left = New), voice first. Owner calls on
+the two open questions: the terminal ends at the bottom bar (the home-indicator strip stays plain),
+and the mic floats clear of the bar (centre ~96pt from the bottom).
+
+## Owner override (after Batch 1)
+No status bar. The owner rejected the tmux window list at the foot: it costs the terminal two rows
+all day and lists agents nobody needs listed. Agents are vim buffers — one on screen, the rest a
+search away (Find). In its place: the title at the top (agent name; `machine:folder` and branch;
+`N!` for agents elsewhere asking; `…`), shown at the end of the output and slid away while reading
+back. The foot is the terminal's; answer keys, the recording row and the echo are vim's last line,
+laid over the bottom rows only while they have something to say. The mic stays centred 4R above
+the home strip; prompt mode lifts the terminal 6R. Where the sections below say "the bar", read
+"the command line" for those three modes; the window list, flags and `esc` are gone.
+
+## Units
+SF Mono 13pt; cell C ≈ 7.8pt, row R ≈ 15.6pt (line height 1.2, the terminal's). Column n at
+x = 10 + n·C; ~47 columns; nothing past the last whole cell. Gutter: col 0 = `▌` cursor, col 1 =
+mark, text from col 2. A tappable row is ceil(44/R) rows (3R); a read-only line 2R. Every tap target
+is grown to ≥ 44pt high and ≥ 6 cells wide; the selection ground shows on the visible part only.
+
+## Colour roles
+green: tmux bar, fzf matches, `*` current, ` ⏎ run `. yellow: asking (`!`, the prompt bar,
+`asking`), counts (`3/3`, `+N!`), the scroll-back position. cyan: tappable actions on the dark ground.
+red: recording, errors, stop. blue: prompts (`>`, `M2%`). faint (#878787): secondary text.
+brightBlack: rules and frames. Selection: `▌` + text at 12% behind the row + bold.
+
+## Focus (from the bottom edge up)
+0–34 home-indicator strip, plain (only the bar's tap slop reaches in). 34–65.2 the status line, 2R,
+tmux green. 65.2–127.6 the mic band: a 56pt disc centred at 96.4pt, 64pt hit circle, floating over
+the terminal; filled when it is your turn, a 2pt ring while the agent works. Above the bar: the
+terminal, a whole number of rows, leftover space at the top.
+
+Status line: `[M2] hn*# api-fix@mini! docs~ +1! esc …` — `[M2]` opens Find; windows are the
+current agent, pinned asking agents, the last, then recents; each wears `*`/`-` and one flag,
+`!` asking (whole word black on yellow) > `#` working > `~` done and unread; `@mini` only for another
+machine; no window numbers; `+N!` for asking agents that do not fit; `esc` only while the current
+agent works (sends ESC, no confirm); `…` the actions menu. Bar modes, highest first: recording,
+prompt, message (2s), normal. Scroll-back: `[42/1380]` black on yellow on terminal row 0, right
+aligned; a tap goes back to the end.
+
+Recording (replaces the bar): ` ✕ ● 0:04 ▁▃▅▇▆▃▁▃▅▂ → hn` — `●` and the timer red;
+`✕` cancels; the mic shows `↑` to send.
+
+Prompt mode (a Claude/Codex dialog is open): the terminal lifts 4R so the dialog sits above the mic;
+the bar turns yellow with equal answer keys ` 1 yes │ 2 always │ 3 no ` (labels from the rows,
+lowercased, cut at `,`/`(`; "don't ask again"/"allow all" → `always`; >4 options → three keys +
+` more `; multi-select toggles `[x]` with ` ⏎ submit `; Codex enterSubmits: digit then a chosen
+Return; partly readable → `answer on screen`, no keys).
+
+Voice: a take is bound at touch-down to the agent it started on (`→ hn`) and never retargets. With a
+dialog open it never sends the paste-and-Return message: "one"/"yes"/label words press their key;
+"no, …" presses 3 then sends the rest once the dialog closes; anything else shows red
+`✗ no match — tap an answer` and sends nothing. The echo appears only after the send is
+acknowledged: `✓ hn fix the login te··` (2s); failure `✗ not sent retry`.
+
+## Find (fzf)
+Rows bottom-up: asking (newest first), the last agent, the rest by last use, the current agent last;
+the cursor on the first row. Name at col 2 (≤14 chars then `··`), place at col 16, state word right
+aligned (`asking` yellow, `working` faint, `done 12m`, an idle age faint, `exited` red). An asking
+agent gets a faint second line with the question at col 4. Rows 3R (4R with the second line);
+header and info lines 2R; the prompt 3R. Typing filters without reordering; a new asking agent
+re-ranks at once (after the finger lifts). The header shows only on an empty query; the query is
+bold with a block cursor. `+new` → New, `esc` → Focus.
+
+## New
+Labels faint at col 2, values at col 11, rows 3R: agent, project, options, task (a voice take).
+`new ──── esc` above the prompt; the prompt `M2% harness new claude @M2 ~/code/x -- "task"`
+hard-wrapped by column, with a reverse-green ` ⏎ run ` at the right. Choosers use Find's layout,
+open instantly with the cursor on the current value (`*`); actions (`+ new folder`, `+ open folder`,
+`+ clone repo`) with a cyan `+` at the far end from the prompt.
+
+## Menus and Settings
+tmux display-menu: a brightBlack `┌─┐ ├┤` frame, centred title, rows 3R, `stop` red, opened above
+the bar right-aligned to `…`; selection like fzf (not yellow); `stop` confirms in the bar
+(`stop hn? y │ n`). Settings uses New's grammar with `── terminal ──` section rules, values right
+aligned, `- 13 +` words 6 cells wide.
+
+## Motion and latency
+Selection ground in the same frame as touch-down; selection haptic on a committed tap, light impact
+on mic start and on the `✓` echo. Only horizontal pages move: 1:1 with the finger, settle 200ms
+ease-out or cancel 160ms, no spring. Everything else is instant (bar modes, keys, the lift, menus,
+choosers, re-ranking, mic states). A fling ends on a whole row. Switching agents paints the cached
+screen in the first frame.
+
+## Build order
+Batch 1: line height 1.2 + faint; the bar at the bottom and the terminal in whole rows; bar grammar
+and esc; mic 56/64 at 96.4 with the ring, no search orb; the recording row, no capsule; prompt mode
+and the lift; voice binding, answer matching and the echo; slop and haptics.
+Batch 2: fzf rows/cursor/`n/m ─`/`··`; Find order, state words, second line, header, block cursor;
+New; choosers.
+Batch 3: the actions menu and the bar confirm; Settings; motion timings and row-snapped scrolling;
+the scroll-back position on row 0; the render fixture.
diff --git a/docs/plans/2026-09-26-003-mobile-find-new-spec.md b/docs/plans/2026-09-26-003-mobile-find-new-spec.md
new file mode 100644
index 000000000..c489aaa35
--- /dev/null
+++ b/docs/plans/2026-09-26-003-mobile-find-new-spec.md
@@ -0,0 +1,148 @@
+# Mobile: Find and New (the room, round 2)
+
+2026-09-26. Panel: iOS, consumer, voice and dev-tools seats; the product lead (the Jobs seat) decides.
+
+## Calls
+1. **Keyboard down on open.** The list is usually the answer; the field is one tap away.
+2. **No chips.** Plain typing finds every kind, in sections; `#` `@` `:` `>` (models included) stay as hidden shortcuts.
+3. **Mic in the field**, turning into `✕` once there is text; the floating mic is Focus's alone.
+4. **Current harness shown, last**, marked `current`, so search never misses one.
+5. **Rows on top, task docked above Start.** The task is optional (first place looks required); it's the iMessage composer, in thumb reach.
+6. **`Start`.** The rows above it say who and where.
+7. **Plain rows, hidden when they don't apply.** No Options, More or Model row (`:` switches models). Worktree moves into the Branch picker.
+8. **Command text cut.** Even a faint line reads as tappable.
+9. **Full-height sheets that slide up.** Sideways is navigation.
+10. **17 and 13 only.** 17 for what you decide on or tap, 13 for the rest; the terminal keeps its size.
+11. **Voice-parsed New and the countdown are out.** The mic fills the task verbatim; starting takes a tap.
+12. **Zero states:** below.
+
+Mockups: one 13pt cell per character; 17pt lines fit ~34, then `…`.
+
+## Find
+Opened:
+```
+╭──────────────────────────────────╮
+│ Search harnesses mic │ Cancel
+╰──────────────────────────────────╯
+needs you
+api-fix asking
+"Run the migration on the test db?"
+pr-review asking
+"Push the branch to origin?"
+
+recent
+tests idle
+mini:api · main · 3h
+hn working
+M2:autonomous-harness · main · current
+
++ New Harness
+```
+Typing "ap": Return opens the first row (#262626 ground); matches green.
+```
+╭──────────────────────────────────╮
+│ ap▏ ✕ │ Cancel
+╰──────────────────────────────────╯
+api-fix asking
+"Run the migration on the test db?"
+tests idle
+mini:api · main · 3h
+
++ New Harness in api
+mini:api
+──────────────── keyboard ──────────────────
+```
+- **Field:** 44pt, #262626, 6pt radius; `Cancel` 17pt cyan.
+- **Rows:** 60pt; 17pt name, 13pt state word on the right, 13pt faint line 2. An asking row's question is white.
+- **States:** `asking` yellow, `working` green, `idle`/`done` faint, `exited` red.
+- **Order:** `needs you` (newest first), `recent` (last opened), current, `+ New Harness`. Headers show only on an empty query with someone asking.
+- **Typing** filters in place across name, place, branch and question, adds `commands` and `models` sections, and ends on `+ New Harness in <best project>`.
+- **Navigation:** tap opens Focus; Cancel or swipe left goes back.
+
+## New
+Default:
+```
+New Harness Cancel
+
+agent Claude Code ›
+project M2:autonomous-harness ›
+branch main ›
+approvals Auto-approve ›
+
+
+task (optional)
+╭──────────────────────────────────────────╮
+│ What should it do? │
+│ mic │
+╰──────────────────────────────────────────╯
+╭──────────────────────────────────────────╮
+│ Start │
+╰──────────────────────────────────────────╯
+```
+Task filled:
+```
+New Harness Cancel
+agent Claude Code ›
+project mini:api ›
+branch main ›
+approvals Auto-approve ›
+task (optional)
+╭──────────────────────────────────────────╮
+│ Fix the login test that fails on CI, │
+│ then run the whole suite.▏ mic │
+╰──────────────────────────────────────────╯
+╭──────────────────────────────────────────╮
+│ Start │
+╰──────────────────────────────────────────╯
+──────────────── keyboard ──────────────────
+```
+Picking a project:
+```
+New Harness (dimmed)
+────────────────────────────────────────────
+Project Cancel
+╭──────────────────────────────────────────╮
+│ Search projects mic │
+╰──────────────────────────────────────────╯
+recent
+autonomous-harness ✓
+M2:~/code/autonomous-harness
+api
+mini:~/code/api
+
+all
+blog
+M2:~/code/blog
+
++ Open Folder
++ Clone Repository
++ New Folder
+```
+- **Rows:** 56pt, prefilled from the last Start. `branch` only for git projects, `approvals` only for agents with modes, `profile` only for Codex profiles. First time: a cyan `Choose a project`, and Start dimmed.
+- **Task:** 3–6 lines; `1840/2000` past 1800. Task and Start ride 8pt above the keyboard.
+- **Start:** full width, 52pt, green fill, black 17pt bold.
+- **Pressing Start:** `Starting…`, `agent_create` with `prompt` (none if empty), then the new harness's Focus. On failure or 15s silence: red `✗ Couldn't start: M2 is offline.`, the button becomes `Try Again`, values stay. A task survives Cancel.
+- **Pickers:** search on top, `✓` on current, `+` rows last. Agent: `Claude Code`, `Codex`, then `more` A–Z; faint `not on M2` if missing. Branch: `main · this folder`, `+ New Worktree`, branches. Approvals: a description line each, risky ones red.
+
+## Zero states
+- **No computer:** `No computer linked`, then `Harness runs your agents on your own computer. Open Harness on your Mac and sign in; it shows up here.`
+- **Can't reach it:** `Couldn't reach your computers.` with `Try Again`.
+- **Nothing running:** the app opens on New, subtitled `Nothing running yet. Start your first harness.` Find: `No harnesses running.` above `+ New Harness`.
+
+## Terminal, but consumer-clear
+- SF Mono, 17/13, regular and bold; flat, no blur or shadow.
+- Colour only for meaning: yellow needs you, green working/go/match, red failed/risky, cyan tappable, faint secondary.
+- Glyphs only `+ ✓ › ✕ …`; no sigils, counts or keyboard words.
+- Actions Title Case, descriptions lowercase.
+- Lists grow down from their search field.
+- One filled button per screen; targets ≥44pt.
+- Instant except page and sheet motion (200ms, no spring).
+
+## Cut
+Find: `3/3 ─── +new esc`, the legend, the scope bar, the red bar, `*`, bottom-anchored lists. New: `$ harness new …`, `⏎ tap to run`, the `options` and `worktree` rows.
+
+## Build order
+1. **Find:** top field with mic/`✕`, keyboard down, 17/13 type, rows, order, `+ New Harness in`, sections, zero state.
+2. **New:** form and dock, conditional rows, Start → Focus, failure line, sheet pickers, app zero states.
+
+Each deletes its cuts.
diff --git a/docs/plans/2026-09-26-004-mobile-round-3.md b/docs/plans/2026-09-26-004-mobile-round-3.md
new file mode 100644
index 000000000..175a6985e
--- /dev/null
+++ b/docs/plans/2026-09-26-004-mobile-round-3.md
@@ -0,0 +1,93 @@
+# Mobile: round 3 — onboarding and the whole app (the room)
+
+September 26, 2026, overnight. Four seats reviewed renders of every screen, from the first launch to Settings:
+- a first-time user walking in cold (a Claude Code developer who had never heard of Harness)
+- an iOS system-app designer
+- a terminal power user (vim, tmux, fzf)
+- an onboarding and activation lead
+
+Scores: iOS 7/10 overall (Find 8, Settings 5); terminal user 7/10 "feels like home"; the first-time user understood *what* it does in about 5 seconds but saw it *work* only after 5–10 minutes at a desk.
+
+## What changed before this round
+- **Welcome and sign-in:** a phone-native welcome, with email then a 4-digit code. It replaces the desktop login card.
+- **Set up your computer:** shown with no computer, and behind the welcome. It watches for the computer.
+- **Computers and unlock:** plain states (ready / locked / asleep) and a phone unlock page.
+- **Focus hints:** one time only. The notification prompt comes after them, not at sign-in.
+- **How Harness works:** in Help, in Find ("help") and on setup.
+- **Look:** menus and Settings use the terminal's face.
+
+## Calls, and what was done
+| # | Finding (seat) | Call |
+|---|---|---|
+| 1 | Finding out late that a computer is needed, and 55% drop-off at setup when away from it (onboarding) | "Continue with email" is the one green button. The setup page leads with **Email me the setup link** (the phone's Mail, to yourself), then "Already at your computer?" with a **Mac app / Terminal** choice (first-time user: "1/2" read as steps). |
+| 2 | "Autonomous account" is a second brand (all) | Gone. "Your email — use the same email as Harness on your computer." |
+| 3 | The hints swallow the swipe they teach, and sit on the name (iOS) | The hints let the touch through: it dismisses *and* navigates. The name hint moves below the title. |
+| 4 | esc is two taps away (terminal) | An `esc` chip beside the mic while the agent works or asks; Interrupt stays in `…`. |
+| 5 | "1 asking": which one? (first-time user) | It names the harness (`api-fix asking`), or counts when several. |
+| 6 | No quick toggle to the last harness (terminal) | Double-tap the name: tmux's `prefix L`, vim's `:b#`. |
+| 7 | No first harness: an empty task box (onboarding, first-time user) | When nothing is running, New suggests three first tasks to tap. |
+| 8 | The mic is see-through, and red ↑ reads as stop (iOS, terminal) | An opaque disc with a hairline ring. While recording, the send face is green; red stays only for the ● timer. |
+| 9 | Answer keys are 31pt tall (iOS) | 48pt, with a pressed state and a haptic. |
+| 10 | Settings looks like another app (iOS, terminal) | Flat raised groups, lowercase headers, the email in place of the "?" avatar. |
+| 11 | Choosers: search on 2 items; dead Clone/New Folder rows (iOS) | Search only on long lists. Rows that can't be used say why, or are hidden. |
+| 12 | Type and gutters drift, and the footer is 11pt (iOS) | 13pt floor everywhere. Gesture labels are green, not cyan. |
+| 13 | Copy/paste, `^C`, sticky ctrl on typed letters, ⇧tab (terminal) | Next: the key bar and selection work. |
+| 14 | QR pairing, a signed-in handoff link, and `harness pair` (onboarding) | Needs desktop, CLI and backend work: proposed, not built tonight. |
+| 15 | The sample: the real Focus playing a session, end card "Set up my Mac" (onboarding) | Being built as the offline sample; the script follows the onboarding seat's 60 seconds. |
+
+## Not changing (every seat agreed)
+- The real terminal: ANSI colours, SF Mono 13, no chat bubbles.
+- Find's structure.
+- The yellow answer bar.
+- `[24/45]`.
+- One green button per screen, cyan for what can be tapped, and the 17/13 scale.
+- New's rows on top with the task and Start at the foot.
+- The words "harness" and "phone password".
+
+## Round 4 (the real app on a simulator)
+`mobile/integration_test/first_run_journey_test.dart` walks the real app from a clean install with `flutter drive` on an iPhone simulator, taking a screenshot at each step:
+1. the welcome
+2. the sample: hints, a question answered, Find, New with a task, the new harness, the menu, the end card
+3. set up your computer
+4. sign-in
+
+The same three seats reviewed those shots:
+
+| Seat | Round 3 | Round 4 |
+|---|---|---|
+| First-time user | understood in about 5s; saw it work in 5–10 min | about 15s to see it work, 60–90s to have done it; 7/10 "would use without help" |
+| iOS designer | 7 | 7.5 (Welcome 8.5, Find 8.5, Sample 7, New 6.5) |
+| Terminal user | 7 | 8 ("works like a remote for tmux") |
+
+Round 4 also found:
+- **Walking the app caught a real bug:** on a computer this phone had never used, New had no project and a dead Start. It now defaults to the computer's latest folder, and Start names what is missing.
+- **Setup:** it says who is signed in and that it is waiting. Terminal is the first tab.
+- **Sample:** the guide is a step counter (`[1/3] refactor-db needs you — swipe right →`), and the end card is a tally (`✓ watched a harness work · ✓ answered its question · ✓ started dark-mode-toggle`). Your own harness is named for its task.
+- **Terminal:**
+ - esc is offered whenever the pane says "esc to interrupt".
+ - `^C` is on the key bar.
+ - ctrl is shared with typed letters.
+ - Copy follows a long-press selection, and Paste is in `…`.
+ - Holding the name goes back to this phone's last harness (`:b#`).
+ - The mic fades while you read history.
+
+## Still open
+- **Needs the desktop app, the CLI or the backend:**
+ - QR pairing, so there's no phone password on first run.
+ - `harness pair`.
+ - A signed-in "set up your Mac" link, sent from the phone, and a "your computer is ready" notification.
+ - Renaming "remote-password" to "phone password" in the CLI.
+- **Perf "after" run** (`integration_test/perf_test.dart`, merged): it needs the phone unlocked and untouched for about 7 minutes.
+- **Smaller:**
+ - A single-tap shift-tab or plan-mode key.
+ - Middle-truncated branches in the title.
+ - Settings rows even flatter, which the terminal seat wants.
+
+## Final round (product lead)
+Verdict: 8/10 overall; first touch 7, about 8.5 once its three must-fixes landed. Ready for a TestFlight group; a public launch waits for pairing. The fixes, all done and checked on the simulator:
+1. **"Set up my computer" goes through sign-in first** ("First, your email"), from both the welcome and the sample's end card. Signed in, home is the setup page that watches for the computer. It used to be a signed-out dead end.
+2. **The title fits:** the words on the right take at most 45% of the row, and `machine:folder · branch` ends in `…` instead of being cut mid-letter.
+3. **A clean sample start:** no coach marks (the guide teaches by doing), and the terminal starts below the guide.
+4. **New while typing:** the choices fold into one line.
+
+Not done, on purpose: padding the terminal so the mic never sits on the last rows. That goes against the owner's call that the terminal stays full screen with the mic floating; left for the owner to decide.
diff --git a/docs/plans/2026-09-26-005-mobile-ten.md b/docs/plans/2026-09-26-005-mobile-ten.md
new file mode 100644
index 000000000..91f40037a
--- /dev/null
+++ b/docs/plans/2026-09-26-005-mobile-ten.md
@@ -0,0 +1,92 @@
+# Mobile: from 5 to 10 (the calls)
+
+## 1. The idea
+**Every agent on your computers, live in your pocket, driven by voice.**
+
+**The magic moment: pocket to answered in five seconds.** The harness that needs you is already on screen, live. Hold the mic, say "yes, and add a test", and let go. Your words type themselves into Claude's prompt, and the agent moves. Everything below is ranked by how well it serves that.
+
+## 2. Conflicts (the owner's word wins)
+1. **`[19/20]`:** cut. The reading strip's faint `↑19` says the same thing with less ink.
+2. **The yellow slab:** cut. `1 yes` and `3 no` flank the mic, so the mic never moves. `2 always` is a tap on its own terminal line, where its scope is written.
+3. **`→ fix-login` while recording:** cut; the title names it.
+4. **"Interrupt esc" in the menu:** cut. The esc chip, the key bar and `>interrupt` cover it.
+5. **SF Mono everywhere:** yes, on Ive's scale. The owner asked for terminal-native.
+6. **Cyan and magenta in the chrome:** out. The agent's output keeps its sixteen colours.
+7. **Landscape and pinch:** yes, on Focus. Gestures, not buttons, and diffs fit.
+8. **Hide the mic while reading:** no. The owner said it is always visible. Only esc hides.
+9. **Scroll takes control:** stays. It is the owner's call; a view-only size is Next.
+10. **× while recording:** cut, because the owner said no Cancel buttons. Tapping outside the mic discards.
+11. **The gutter:** 12, not 16. At 13pt, 16 costs the terminal a column.
+
+## 3. The system (`tty.dart`)
+**Type:** SF Mono only, ligatures off. No w700, and no prose past one line.
+Display 28/34 w600 −0.6; title 17/22 w600 −0.2; row 15/20 w500; meta 13/18; key 13/16 w500; terminal at the user's size, 1.2.
+
+**Grid:** 4pt. One 12pt gutter everywhere (`Tty.origin` 10→12). Rows are 44pt, or 56pt with two lines.
+
+**Colours** (Graphite; other themes derive them from fg over bg):
+- Planes: ground #181818; surface #202020 (sheets, the mic, cards); raised #2C2C2C (fields, keycaps); hairline #333333, 1px.
+- Words: text #F5F5F5; faint #8B8B8B; dim #666666 (furniture only).
+- Accent #0DBC79: the primary, the cursor, hits, recording, the current harness. Asking #E5E510. Alert #F14C4C. Scrim: black at 48%.
+
+**Elevation:** three planes. No shadows, and no outlines except the mic ring (text at 14%) and the asking line.
+
+**Radii** (superellipse): keycaps 6; fields, buttons, cards and chips 10; sheets 14; the mic is a circle.
+
+**Motion:** enter 240ms `Cubic(0.2,0,0,1)`; exit 160ms `Cubic(0.4,0,1,1)`. Swipes and sheets follow the finger (spring 0.32/1.0) and commit at 35% or 500pt/s. The mic presses to 0.94 and springs back 0.30/0.62, the only overshoot. Never animated: output, the mic's position, a row under the finger.
+
+**Haptics:** selection for a row, swipe or answer; light for mic down; medium for sent and esc; success when the watched harness finishes; warning when another asks.
+
+## 4. Work (Flutter only; effort S/M/L)
+
+### A: the look
+1. **Tokens:** add `TtyType`, `TtyColor`, `TtyMotion` and `TtyHaptics`, and route all chrome through them. **M**
+2. **One edge and four radii everywhere.** Delete the 10/16/21/24 insets and every other radius. **S**
+3. **Sweep:** w700 becomes w600, 17pt rows become 15, cyan and magenta chrome turns text or faint, and the #666 title rule goes. **S**
+4. **Welcome:** the wordmark, the headline, the live card and "Continue with email", then "Try it first" and "end-to-end encrypted" in faint. Drop the paragraph and "Set up my computer". **S**
+5. **Settings:** a chevron-only back; drop Stats, the "—" values and the descriptions; Colors reads "Graphite"; a live terminal line previews the font. **S**
+6. **Sample:** the guide becomes one faint line 12pt above the mic, "refactor-db needs you →". **S**
+
+### B: Focus and the terminal
+1. **Instant open:** cache each harness's last frame on disk and paint it on open. Keep the 3 most recent attached; the skeleton shows only on a first open. Target: under 100ms. **L**
+2. **Open on the asker:** after 5 or more minutes away, if exactly one other harness asks, open on it. **S**
+3. **Clear region:** pty rows = ⌊(micTop − 12 − stripBottom) / row⌋. The three-line title overlays the top through a 12pt fade, and collapses to a 28pt strip while the cursor row is under it or on the alternate screen. This fixes the sample's blank band. **M**
+4. **Mic zone:** the mic is 60pt, surface, with a 1px ring, centred, its bottom at the safe inset + 12. esc is a 48×32 raised keycap 20pt to its left, shown only while the pane says "esc to interrupt". Tap toggles; a hold of 300ms or more is push-to-talk. Recording turns the mic green with a black ↑, with a red dot and `0:02` on its right. **M**
+5. **Asking:** `1 yes` and `3 no` are 88×44 keycaps with yellow digits, 20pt either side of the mic, under a 1px yellow line at the terminal's bottom. Tapping an option line (`❯ 2.`) sends its digit. **M**
+6. **Selection:** a long press selects the whole ⏺ block, with green handles and a `Copy` keycap. **L**
+7. **Key bar:** 44pt, with 36pt keys: `esc` (swipe up for `^C`), `⇧tab` (up for `tab`), `ctrl`, a 48pt `✥` (one arrow per 12pt dragged), `/`, `|`, `~`, then `▾` and the mic docked at 36pt. Photo… moves to the menu. **M**
+8. **Reading:** the strip reads `fix-login ↑19` in faint. A tap returns to live. **S**
+9. **Landscape:** the strip only, with about 95 columns, and a 48pt mic low in the right inset. **M**
+10. **Pinch:** 10–20pt, with a `57×52` HUD, and one resize on release. **M**
+11. **Done:** tapping a link opens it, and voice replies always land.
+
+### C: Find, New, the menu
+1. **Find field:** 44pt, raised, with the placeholder "Search". A prefix lights green and names its mode (`# projects`). **S**
+2. **Find rows:** 56pt. On the right, a yellow `asking` or a faint spinner; the age replaces idle, done and current. The current harness ends in a green ▍. Attached harnesses show their spinner line (`Testing… 13s`). **M**
+3. **Hygiene:** pin "needs you" only on an empty query; fuzzy-match only names, places and branches; `:` says "studio offline"; `>` shows names only. **S**
+4. **`>` verbs:** interrupt, /compact, /clear, plan mode, copy last reply, restart. **M**
+5. **New:** drop "task (optional)", `[+]`/`[-]` and the pills. Options reads `main · auto-approve` and expands in place. The field and a green 50pt `Start` share one row above the mic, which sits in its Focus spot: speak, and the harness starts. **M**
+6. **Menu:** hugs its content, with 44pt rows: Paste, Photo…, Copy last reply, Rename (in place), Restart, Settings ›, and Stop… in faint. **S**
+7. **Choosers:** a green ✓, `More agents 12 ›`, and no detail lines. **S**
+
+### D: delight
+1. **Voice to keys:** the ring swells from 60 to 76pt with your voice. The transcript goes out in 8-character chunks every 16ms, so it types itself. **M**
+2. **Heartbeat:** the ring brightens from 14% to 30% with output. When the harness finishes, a green arc sweeps around it. **M**
+3. **Edge light:** while another harness asks, a 2pt yellow line breathes on the left edge. **S**
+4. **Settling:** at the live end, the title unfolds over 280ms. **S**
+5. **Peek:** long-press a Find row to see its last 8 lines. **M**
+6. **You were here:** a faint hairline marks where you left off. **M**
+7. **Small ones:** the wordmark cursor blinks thrice; the end card's ticks land 120ms apart. **S**
+
+## 5. Next (backend, CLI, desktop)
+Lock-screen answers (APNs, notification actions, a Live Activity), status lines in Find for every harness, a catch-up line, a view-only size, streaming transcripts, Sign in with Apple, QR pairing and AirPods walkie-talkie.
+
+## 6. The bar for 10/10
+1. Pocket to answered takes 5s or less on a real iPhone.
+2. A harness you've seen before paints in under 100ms.
+3. No chrome ever covers the cursor row or a dialog.
+4. A lint finds one gutter, four radii, one accent and no w700.
+5. Every string fits on one line: no "—" and no raw errors.
+6. Diffs never wrap mid-token in landscape.
+7. Copying takes two gestures, and terminal keys need no symbol layer.
+8. A tmux user and a non-programmer switch, start, answer, interrupt and copy unaided.
diff --git a/docs/plans/2026-09-27-006-mobile-first-setup.md b/docs/plans/2026-09-27-006-mobile-first-setup.md
new file mode 100644
index 000000000..f875f94ea
--- /dev/null
+++ b/docs/plans/2026-09-27-006-mobile-first-setup.md
@@ -0,0 +1,186 @@
+# One way in, from any device
+
+September 27, 2026. People arrive in three orders:
+
+- **Phone → computer:** they find the app, then set up their Mac.
+- **Computer → computer:** they add a second Mac.
+- **Computer → phone:** they already use Harness and add the phone.
+
+Each device needs the same two things, and today it gets them through two separate chores:
+
+1. **An account session: who you are.** The phone signs in with an email code; the desktop app and
+ `harness login` sign in through a browser.
+2. **Trust: an end-to-end key the other devices accept.** It lets this device read and drive your
+ terminals, which the server relays but cannot read. Today that means inventing a remote password
+ and typing it on every client, once per computer.
+
+**Proposal: approving a new device on one you already have does both, and it looks the same on
+every path.** This plan builds on `2026-09-26-001-mobile-zero-questions.md`.
+
+## Today
+
+1. **Two sign-ins.** The phone uses an email code (`mobile/lib/viewer/email_code_api.dart`); the
+ desktop and CLI use browser SSO (`cli/src/cli.ts:846-932`). Over SSH you paste a callback URL
+ back by hand.
+2. **A password per computer, typed on every client.** You set it twice on the computer and enter it
+ on the phone. Wrong guesses lock you out for 5 minutes, doubling up to a day (`e2ee/store.ts:24-25`).
+ The desktop app doesn't set one by default (Machines ▸ Set password).
+3. **The phone's setup page is four terminal commands**, in a different order from the installer's.
+ It can only email them to yourself (`mobile/lib/phone/welcome/connect_computer.dart:15-20, 66-92`).
+4. **Nothing survives a reboot without the desktop app.** The CLI installs no launch agent or
+ service (`cli/src/cli.ts:6311-6319`).
+5. **Your existing sessions aren't there.** Plain `claude` and `codex` sessions are invisible
+ (`cli/src/lib/tmuxAgentDiscovery.ts:129-148`).
+
+## The pattern: approve on a device you have
+
+A new device (the phone app, the desktop app, or the CLI) asks for one thing, your email:
+
+```
+ NEW DEVICE A DEVICE YOU ALREADY HAVE
+ ────────── ─────────────────────────
+ Your email [ dee@… ]
+ [ Continue ]
+
+ Approve on your iPhone ┌──────────────────────────────┐
+ or MacBook Pro. │ MacBook Air wants to join │
+ │ your Harness. │
+ The code on it should read: │ │
+ 482 913 │ Its code: 482 913 │
+ │ │
+ [ Use an email code instead ] │ [ Deny ] [ Approve ]│
+ └──────────────────────────────┘
+ ✓ You're in. MacBook Air can reach
+ your computers, and they can reach it.
+```
+
+- **Approve does both.** The new device is signed in and trusted by every computer and phone you
+ have. There's no email code and no password.
+- **The first device of an account** has nothing to approve with. It signs in with an email code and
+ starts your list of devices.
+- **With the phone in hand,** a desktop or the CLI also shows the code as a QR. Scanning it approves
+ without comparing numbers.
+- **No approval, no entry.** Only the account's first device gets in on an email code alone.
+
+### The three orders
+
+1. **Phone → computer.**
+ - The phone signs in with an email code. It is your first device.
+ - **Set up your computer** leads with the app: *"Get Harness for Mac"* sends
+ `harness.autonomous.ai/desktop` to the Mac by AirDrop, Messages or email.
+ - On the Mac, install and open the app, then enter your email.
+ - The phone shows *"Approve MacBook Pro? 482 913"*. Approve. The Mac is signed in, its daemon is
+ running, and the phone lists its sessions.
+2. **Computer → computer.** The second Mac enters your email. The first Mac, and the phone if you have
+ one, show the approval. Approve. All of them trust each other.
+3. **Computer → phone.** The phone enters your email. The Mac shows *"Approve iPhone? 482 913"*.
+ Approve.
+
+**The terminal path (the 1%):** `curl -fsSL https://cdn.autonomous.ai/harness/desktop/install.sh | bash`
+installs the same desktop app (macOS or Linux) and opens it; the app does the rest. A server over SSH,
+with no desktop, gets the CLI alone: `curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash`,
+`harness login`, `harness start`. The phone's set-up page is the website's download menu
+(autonomous.ai/harness-app): macOS Apple Silicon and Intel, Linux Intel/AMD and ARM, each SENT to the
+computer from the release manifest, and CLI, which copies its command. The phone's setup page offers it second, under *"Using a terminal or Linux?"*.
+
+## How one approval is enough
+
+**The device list.** Every device already has its own identity key. The account gets a list of its
+trusted devices' keys, and each entry is signed by the device that approved it. The server stores
+and hands out the list, but it can't add to it: an entry without a valid signature from a device
+already on the list is ignored. A computer's daemon trusts every key it can verify on the list,
+where today it trusts only the keys it pinned with a password. So one approval reaches every
+computer. Parts exist already: a trusted client can vouch for a new hardware device
+(`pairDeviceFromTrustedWeb`, `cli/src/lib/e2ee/manager.ts:465-496`), and the live-code pairing that
+underlies it (`manager.ts:405-568`).
+
+**Why comparing six digits replaces the password.** The danger E2E guards against is the server
+handing each side its own key and sitting in the middle. The approval exchange commits to both
+devices' keys first, then derives the six digits from both (Bluetooth's numeric comparison and
+Signal's safety numbers work this way). A server that swapped a key can't make the two screens show
+the same digits except by a one-in-a-million guess, and every attempt is a new approval someone has
+to accept. You compare instead of typing, and nothing secret has to be chosen or remembered.
+
+**The session comes with the approval.** The approving device asks the backend for a one-time
+handoff. The new device, polling, receives its own session: the tokens `harness login` stores today
+(`~/.harness/auth/session.json`), written by the app. The backend's device-code flow is most of this
+(`backend/src/routes/deviceAuth.ts`). It needs to return a session the daemon's socket accepts;
+today it returns a machine key that `/api/adapter-ws` rejects (`backend/src/lib/adapterWs.ts:11-13`).
+
+**Removing a device** is signed from any trusted device, in Settings ▸ Devices.
+
+**Losing every device:** an email code starts a new list. Your computers keep trusting the old one
+until you approve at each computer itself (`harness trust reset` shows a code and a QR). This is
+rare, and it is deliberate.
+
+**The remote password stays** as a fallback for computers set up by hand and for older CLIs. It is
+never asked for on these paths.
+
+## Sessions you already have
+
+After a computer joins, the phone and desktop list its sessions, **including ones started outside
+Harness**.
+
+- The session search indexer already reads every engine's transcripts
+ (`docs/research/2026-09-26-session-search.md`). Index `~/.claude/projects` and `~/.codex/sessions`
+ whole, not only sessions Harness registered.
+- Outside sessions show as sessions to resume. Tapping one resumes it in a Harness pane
+ (`claude --resume <id>`, `codex resume <id>`).
+
+## Work
+
+| | Part | Est. |
+|---|---|---|
+| **1. Phone, now** | The setup page leads with "Get Harness for Mac" (share `harness.autonomous.ai/desktop`). The terminal path is second, with `cdn.autonomous.ai/harness/desktop/install.sh` and the installer's own order. Plain-words errors. The computer list refreshes live. | 2 days |
+| **2. Backend** | Approval requests (start, poll, approve, deny) that return a daemon-ready session. The signed device list: append-only, delivered to every device. Push to the phone for approvals (APNs; "needs you" wants it too). | 1.5–2 weeks + security review |
+| **3. CLI / daemon** | Trust keys on the verified list. `harness login` shows the code and QR and waits. A launchd/systemd unit so the daemon survives a reboot. | 1 week |
+| **4. Desktop app** | Email-and-approve sign-in in place of the browser. The approval prompt. Settings ▸ Devices. | 1 week |
+| **5. Phone** | The same sign-in, the approval prompt, a QR scanner, Settings ▸ Devices. | 1 week |
+| **6. Sessions** | Index outside sessions; "Resume" rows. | 1 week |
+
+Part 1 stands alone. Parts 2–5 ship together behind the remote password, which keeps working
+throughout. Part 6 stands alone.
+
+## The bar
+
+Hand a phone to someone with a Mac who has never heard of Harness. Within three minutes they are
+talking to one of their existing Claude Code sessions from the phone, and they haven't typed a
+password or signed in twice.
+
+## Decided (2026-09-27)
+
+- **The welcome screen is your sessions.** When a computer joins, the first screen is "Pick up where
+ you left off": the Claude Code and Codex sessions already on it, newest first, including ones
+ started outside Harness. Tap one to resume it. Only an account with no sessions sees New.
+- **A QR skips the email.** A device you have shows "Add your phone" (or a new Mac shows a QR); the
+ other scans it and is signed in and approved in one step. Email is typed only on the first device.
+- **Spam-proof approvals:** the approver picks the new device's number from three, not just Approve
+ (number matching, so a flood can't be tapped through). Requests are rate-limited per account and
+ expire in 2 minutes. The prompt names the device and city, with "Not me" to block it.
+
+1. **Approval:** compare six digits everywhere; a QR where a phone camera is in hand.
+2. **Unapproved devices get nothing.** Only the account's first device signs in on an email code.
+3. **Sign-in is your email, never a password,** on the phone, the desktop and the CLI: approve on a
+ device you have, or a six-digit email code for your first. The browser sign-in retires.
+
+- **Scan and go, built (2026-09-27).** The Autonomous account service can't sign one device in
+ from another (its grants are password, otp, refresh_token and social_token), so Harness issues
+ the phone's session itself. The signed-in Mac asks the backend for a one-time code
+ (`POST /api/auth/handoff`, 32 random bytes, 90 s, spent by the first redeem) through its daemon's
+ owner-only socket. Add Phone puts it in the QR as `h=` and renews it every minute. The phone
+ trades it at `/api/auth/handoff/redeem` for a `hna_`/`hnr_` session (`backend/src/lib/harnessSession.ts`),
+ renewed at `/api/auth/refresh` and revoked on sign-out. Every sign-in check goes through
+ `authenticateAccessToken`, so that is the one branch; machine connections refuse these sessions.
+ No Allow click on the Mac, by decision: the QR is fresh, single use and on screen for a minute.
+ "Remove" for a phone that isn't yours comes later. Old apps, CLIs and backends fall back to the
+ emailed code. A phone session can't mint codes, or use billing routes that forward the token to
+ the account service.
+- **Trust stays per computer, as it is.** A computer admits only keys on its own list
+ (`cli/src/lib/e2ee/manager.ts` `onHello`), so one viewer links N computers: O(N), which is fine.
+ The signed device list is shelved; it would only save the per-computer password steps.
+
+## Open
+
+1. **Outside sessions** (Claude Code or Codex started by hand, not through Harness). Index them by default, or ask once on the computer ("Show my Claude Code and
+ Codex sessions on my phone?"). They never leave the machine except as sealed search hits and
+ previews, as today.
diff --git a/mobile/assets/video/how_it_works.mp4 b/mobile/assets/video/how_it_works.mp4
new file mode 100644
index 000000000..689343c7f
Binary files /dev/null and b/mobile/assets/video/how_it_works.mp4 differ
diff --git a/mobile/integration_test/README.md b/mobile/integration_test/README.md
new file mode 100644
index 000000000..fdcde06e0
--- /dev/null
+++ b/mobile/integration_test/README.md
@@ -0,0 +1,132 @@
+# Phone performance benchmark
+
+`perf_test.dart` measures the phone app on a real phone, in a profile build,
+with production widgets: `TerminalPage`, Find (`TerminalSearchOverlay`), the
+mic orb, and the new-agent form. The account is synthetic — one machine, eight
+agents, two attached terminals — and its terminals are fed Claude Code-shaped
+output through the production binary path (`TerminalSession.handleBinary`:
+zlib when the daemon would compress, UTF-8, the xterm parse). Nothing in it can
+reach a real machine: no config or layout store, an in-memory auth session, and
+a machine connection that never dials.
+
+The method is the desktop benchmark's
+([`desktop/tool/native_benchmark/README.md`](../../desktop/tool/native_benchmark/README.md)):
+**framework dispatch → raster finish of the first frame that shows the verified
+result**, joined to the engine's `FrameTiming` by frame number; five warmups;
+every measured observation kept; nearest-rank percentiles. Touches are
+delivered as device pointer events into the framework's hit test and dispatch —
+not as test events, which the live test binding paints a crosshair for.
+
+The results and what they exclude are in
+[`docs/performance/2026-09-26-mobile-baseline.md`](../../docs/performance/2026-09-26-mobile-baseline.md).
+
+## Run it
+
+The phone must be connected, unlocked and signed for development. Build the
+benchmark app first — building takes about a minute, and a phone left alone
+that long can auto-lock before the app is up to keep it awake — then drive the
+prebuilt app. From `mobile/`:
+
+```sh
+flutter build ios --profile --target=integration_test/perf_test.dart
+
+flutter drive --profile --no-dds --keep-app-running \
+ --use-application-binary=build/ios/iphoneos/Runner.app \
+ --driver=test_driver/perf_driver.dart \
+ --target=integration_test/perf_test.dart \
+ -d <device id>
+```
+
+- `--profile` — timings from a debug build mean nothing.
+- `--no-dds` — the in-app timeline trace connects to the VM service itself,
+ which DDS would otherwise hold exclusively.
+- `--keep-app-running` — **always.** Without it `flutter drive` UNINSTALLS the
+ app when it finishes (`drive_service.dart`, `stop()`), and deleting the last
+ app from a free developer team makes iOS drop the phone's trust in it. The
+ benchmark is installed under the app's own development bundle id, so it
+ replaces the development build on the phone; reinstall that afterwards.
+- `--dart-define`s (below) go on the `flutter build` line: the prebuilt binary
+ carries them.
+
+(`flutter drive` without `--use-application-binary` builds and runs in one go;
+it measures the same thing, it just leaves the phone idle for the build.)
+
+The run takes about six minutes, most of it the 40 taps, swipes and switches per
+interaction. The app keeps the screen awake while it runs, and ignores real
+touches: only the benchmark's own events reach it, so picking the phone up
+cannot add frames — but locking it or switching apps ends the run. The results
+are written by the driver to
+`../docs/performance/2026-09-26-mobile-data/baseline-<UTC time>.json`; an
+earlier file is never overwritten. A run with a failed scenario goes to
+`failed/` under the same directory, kept for review and never pooled.
+
+### Measuring the redesign ("after")
+
+Same commands, labelled and into their own directory, so the two can be
+compared side by side with identical fixture code:
+
+```sh
+flutter build ios --profile --target=integration_test/perf_test.dart
+
+HARNESS_PERF_LABEL=after \
+HARNESS_PERF_OUT=../docs/performance/<date>-mobile-after-data \
+flutter drive --profile --no-dds --keep-app-running \
+ --use-application-binary=build/ios/iphoneos/Runner.app \
+ --driver=test_driver/perf_driver.dart \
+ --target=integration_test/perf_test.dart \
+ -d <device id>
+```
+
+If the redesign renames what the benchmark taps or waits for — the
+`terminal-find` key, `TerminalSearchOverlay`, `VoiceMicButton`'s face,
+`NewAgentPage`, `FindRow` — update `perf/scenarios.dart` in the same
+change and say so in the report: the boundary of each scenario must stay the
+same for the numbers to compare. `test/perf_fixture_test.dart` runs the
+fixture's assumptions on every `flutter test`, so a rename shows up there
+first.
+
+### Options
+
+Passed as `--dart-define`s:
+
+| Define | Default | |
+|---|---|---|
+| `PERF_SCENARIOS` | all | Comma-separated name prefixes: `idle`, `stream_redraw`, `stream_append`, `scroll_read`, `find_open_tap`, `find_open_swipe`, `mic_tap`, `new_open_swipe`, `find_switch`, `trace_`, `control_panel_redraw`. |
+| `PERF_SAMPLES` | 35 | Measured observations per interaction. |
+| `PERF_WARMUPS` | 5 | Warmups before them, kept in the file, excluded from percentiles. |
+| `PERF_STREAM_SECONDS` | 10 | Length of each streaming window, after a 2 s warmup. |
+| `PERF_TRACE` | true | Also record timeline passes (per-widget build/layout/paint events on) and rank their costliest events. |
+
+Use small values only to check the harness; report only full runs.
+
+`HARNESS_PERF_DEVICE` (optional) is copied into the result's `host` block — a
+model name, for instance. Nothing from the host machine other than the git
+revision and the Flutter version is recorded.
+
+## Summarize
+
+```sh
+python3 scripts/perf_summarize.py ../docs/performance/2026-09-26-mobile-data
+python3 scripts/perf_summarize.py <dir> --label after
+```
+
+It pools every measured observation and every frame across the runs in the
+directory, then takes percentiles — it never averages percentiles — and prints
+markdown tables, plus each run's timeline rankings.
+
+## Files
+
+- `perf_test.dart` — entry point; one test that runs the suite.
+- `perf/perf_binding.dart` — the integration-test binding, drawing only frames
+ the framework asked for (the live binding otherwise renders every vsync).
+- `perf/scenarios.dart` — the scenarios and their verification.
+- `perf/fixture.dart` — the synthetic account, terminals and the home host.
+- `perf/claude_output.dart` — Claude Code-shaped ANSI output.
+- `perf/stream.dart` — the 20 Hz producer.
+- `perf/frames.dart` — frame numbers, `FrameTiming`, percentiles.
+- `perf/gestures.dart` — device-sourced touches; real ones are ignored.
+- `perf/timeline.dart` — self/inclusive time ranking of a VM timeline.
+- `../test_driver/perf_driver.dart` — host side; writes the result file.
+- `../scripts/perf_summarize.py` — the summarizer.
+- `../test/perf_fixture_test.dart` — the fixture's assumptions, and that an
+ idle terminal page asks for no frames, on every `flutter test`.
diff --git a/mobile/integration_test/demo_video_test.dart b/mobile/integration_test/demo_video_test.dart
new file mode 100644
index 000000000..5d6c486fc
--- /dev/null
+++ b/mobile/integration_test/demo_video_test.dart
@@ -0,0 +1,68 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+
+import 'package:harness_mobile/main.dart' as app;
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+
+/// "See how it works": the sample, walked at a person's pace, for a screen recording of the app —
+/// a harness at work, one asking, answered by voice, and a new one started. Not a test of anything.
+///
+/// xcrun simctl io <sim> recordVideo --codec=h264 --force demo.mp4 &
+/// flutter drive -d <sim> --dart-define=HARNESS_RECORDING=true \
+/// --driver=test_driver/journey_driver.dart --target=integration_test/demo_video_test.dart
+///
+/// It prints `DEMO_START <ms since epoch>` where the recording should begin, to trim it by.
+void main() {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('see how it works', (tester) async {
+ Future<void> wait(int ms) async {
+ for (var elapsed = 0; elapsed < ms; elapsed += 50) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ }
+
+ await app.main();
+ for (var i = 0; i < 400; i++) {
+ if (find.text('Is Harness on your computer?').evaluate().isNotEmpty) {
+ break;
+ }
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ await tester.longPress(find.byKey(const ValueKey('welcome-wordmark')));
+ await wait(1200);
+ // ignore: avoid_print
+ print('DEMO_START ${DateTime.now().millisecondsSinceEpoch}');
+
+ // Your sessions, one working.
+ await wait(1800);
+ await tester.tap(find.text('fix-login', findRichText: true).first);
+ await wait(4000);
+
+ // Another needs you: Find, a swipe right.
+ await tester.dragFrom(const Offset(40, 450), const Offset(300, 0));
+ await wait(1600);
+ await tester.tap(find.text('refactor-db', findRichText: true).first);
+ await wait(2600);
+
+ // Answered by voice.
+ await tester.tap(find.byType(VoiceMicCore));
+ await wait(2000);
+ await tester.tap(find.byType(VoiceMicCore));
+ await wait(4200);
+
+ // A new one: a swipe left.
+ await tester.dragFrom(const Offset(350, 450), const Offset(-300, 0));
+ await wait(1400);
+ await tester.enterText(
+ find.byType(TextField).last,
+ 'Add a dark mode toggle',
+ );
+ await wait(1000);
+ await tester.tap(find.text('Start'));
+ await wait(5000);
+ // ignore: avoid_print
+ print('DEMO_END ${DateTime.now().millisecondsSinceEpoch}');
+ });
+}
diff --git a/mobile/integration_test/first_run_journey_test.dart b/mobile/integration_test/first_run_journey_test.dart
new file mode 100644
index 000000000..8e30a6587
--- /dev/null
+++ b/mobile/integration_test/first_run_journey_test.dart
@@ -0,0 +1,124 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+
+import 'package:harness_mobile/main.dart' as app;
+
+/// A first-time user's walk through the real app on a fresh simulator, a screenshot at each
+/// step: the welcome, the sample (hints, answering a question, Find, New with a task, the menu),
+/// leaving it, and the way in — email, then setting up a computer.
+///
+/// Signed out on a clean install, so nothing here can reach a real account or a real machine: the
+/// sample is offline by construction (`lib/demo/`).
+///
+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \
+/// --target=integration_test/first_run_journey_test.dart
+///
+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).
+void main() {
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('first run, as a new user', (tester) async {
+ var step = 0;
+ Future<void> shot(String name) async {
+ await tester.pump(const Duration(milliseconds: 300));
+ 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');
+ }
+
+ await app.main();
+ await waitFor(find.text('Is Harness on your computer?'));
+ await shot('welcome');
+
+ // The sample: no account, no computer.
+ await tester.longPress(find.byKey(const ValueKey('welcome-wordmark')));
+ await wait(2000);
+ // "Pick up where you left off": the sessions, a tap from their terminals.
+ await shot('sample-pick-up');
+ await tester.tap(find.text('fix-login', findRichText: true).first);
+ await wait(1500);
+ await shot('sample-first-time-hints');
+ // The hints go on the first touch, which also does what it touched.
+ await tester.tapAt(const Offset(200, 300));
+ await wait(2500);
+ await shot('sample-focus-working');
+
+ // Find: swipe right.
+ await tester.dragFrom(const Offset(40, 400), const Offset(300, 0));
+ await wait(800);
+ await shot('sample-find');
+
+ // The harness that is asking.
+ final asking = find.text('refactor-db');
+ if (asking.evaluate().isNotEmpty) {
+ await tester.tap(asking.first);
+ await wait(2000);
+ await shot('sample-asking');
+ final yes = find.textContaining('1 yes');
+ if (yes.evaluate().isNotEmpty) {
+ await tester.tap(yes.first);
+ await wait(3000);
+ await shot('sample-answered');
+ }
+ }
+
+ // New: swipe left.
+ await tester.dragFrom(const Offset(350, 400), const Offset(-300, 0));
+ await wait(1000);
+ await shot('sample-new');
+ await tester.enterText(
+ find.byType(TextField).last,
+ 'Add a dark mode toggle',
+ );
+ await wait(300);
+ await shot('sample-new-task');
+ await tester.tap(find.text('Start'));
+ await wait(4000);
+ await shot('sample-new-harness-working');
+
+ // The menu: a tap on the title; a tap anywhere else puts it away.
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await wait(800);
+ await shot('sample-menu');
+ await tester.tapAt(const Offset(200, 120));
+ await wait(600);
+
+ // The end card, once the new harness has run a while — and the way to the real thing.
+ await waitFor(find.text('Set up my computer'), seconds: 20);
+ await wait(400);
+ await shot('sample-end-card');
+ await tester.tap(find.text('Set up my computer'));
+ await wait(1500);
+ await shot('set-up-after-sample');
+ await tester.tap(find.bySemanticsLabel('Back'));
+ await wait(800);
+ await shot('back-to-welcome');
+
+ // The two ways in: set it up, or scan the code the desktop app shows.
+ await tester.tap(find.text('Not yet — set it up'));
+ await wait(800);
+ await shot('set-up-computer');
+ await tester.tap(find.bySemanticsLabel('Back'));
+ await wait(800);
+ await tester.tap(find.text('Yes — scan to connect'));
+ await wait(1500);
+ await shot('scan-to-connect');
+ await tester.tap(find.text('Use email instead'));
+ await wait(800);
+ await shot('sign-in-email');
+ });
+}
diff --git a/mobile/integration_test/perf/claude_output.dart b/mobile/integration_test/perf/claude_output.dart
new file mode 100644
index 000000000..57b324aae
--- /dev/null
+++ b/mobile/integration_test/perf/claude_output.dart
@@ -0,0 +1,260 @@
+import 'dart:math' as math;
+
+/// Synthetic output shaped like Claude Code's, for a terminal [cols] wide.
+///
+/// What reaches the phone is the RAW bytes the agent wrote: the daemon reads
+/// its pane through `tmux -C attach-session`, whose `%output` is the program's
+/// own output, not tmux's re-rendering (`cli/src/lib/tmuxStream.ts`). Claude
+/// Code draws with Ink, so a live turn is:
+///
+/// - a transcript that only grows — bullets, tool calls with `⎿` results,
+/// red/green diffs, and prose long enough to wrap several times on a phone;
+/// - under it, a live region Ink erases and redraws in place on every tick:
+/// the spinner line with its timer and token count, the todo list, the
+/// prompt box drawn in box-drawing characters, and the mode line.
+///
+/// Colours are 24-bit SGR, as Claude Code emits them; each burst is bracketed
+/// by synchronized-output mode 2026 the way current versions do. Everything is
+/// seeded, so two runs stream the same bytes.
+class ClaudeOutput {
+ ClaudeOutput({required this.cols, int seed = 26})
+ : _random = math.Random(seed);
+
+ final int cols;
+ final math.Random _random;
+
+ /// Rows in the live region — the same count as the desktop benchmark's
+ /// eight-row redraw.
+ static const int liveRows = 8;
+
+ static const _reset = '\x1b[0m';
+ static const _bold = '\x1b[1m';
+ static const _dim = '\x1b[2m';
+ static const _orange = '\x1b[38;2;215;119;87m';
+ static const _gray = '\x1b[38;2;153;153;153m';
+ static const _code = '\x1b[38;2;177;185;249m';
+ static const _green = '\x1b[38;2;78;186;101m';
+ static const _purple = '\x1b[38;2;175;135;255m';
+ static const _addBg = '\x1b[48;2;34;92;43m';
+ static const _delBg = '\x1b[48;2;122;41;54m';
+
+ static const _spinner = ['·', '✢', '✳', '✶', '✻', '✽'];
+ static const _verbs = [
+ 'Thinking',
+ 'Compiling',
+ 'Pondering',
+ 'Reticulating',
+ 'Crafting',
+ 'Brewing',
+ ];
+
+ static const _words = [
+ 'the',
+ 'test',
+ 'login',
+ 'flaky',
+ 'because',
+ 'session',
+ 'token',
+ 'expires',
+ 'before',
+ 'the',
+ 'assertion',
+ 'runs',
+ 'so',
+ 'I',
+ 'will',
+ 'wait',
+ 'for',
+ 'response',
+ 'instead',
+ 'of',
+ 'checking',
+ 'status',
+ 'immediately',
+ 'and',
+ 'the',
+ 'fixture',
+ 'now',
+ 'resets',
+ 'clock',
+ 'between',
+ 'cases',
+ 'which',
+ 'keeps',
+ 'retry',
+ 'logic',
+ 'honest',
+ 'while',
+ 'CI',
+ 'stays',
+ 'green',
+ 'refresh',
+ 'handler',
+ 'races',
+ 'with',
+ 'teardown',
+ 'when',
+ 'suite',
+ 'shares',
+ 'a',
+ 'server',
+ 'across',
+ 'files',
+ 'that',
+ 'was',
+ 'hiding',
+ 'real',
+ 'bug',
+ 'in',
+ 'middleware',
+ 'order',
+ ];
+
+ static const _files = [
+ 'src/auth/login.test.ts',
+ 'src/auth/session.ts',
+ 'src/server/middleware.ts',
+ 'test/fixtures/clock.ts',
+ 'src/api/rateLimit.ts',
+ ];
+
+ String _pick(List<String> from) => from[_random.nextInt(from.length)];
+
+ /// A paragraph of [minWords]..[maxWords] words with an inline code span, one
+ /// logical line — the terminal wraps it.
+ String _prose({int minWords = 24, int maxWords = 48}) {
+ final count = minWords + _random.nextInt(maxWords - minWords + 1);
+ final words = [for (var i = 0; i < count; i++) _pick(_words)];
+ final codeAt = _random.nextInt(count);
+ words[codeAt] = '$_code`${_pick(_files)}`$_reset';
+ final text = words.join(' ');
+ return '${text[0].toUpperCase()}${text.substring(1)}.';
+ }
+
+ int _diffLine = 12;
+
+ /// One logical transcript line. The mix repeats a turn: prompt, prose, tool
+ /// calls with results, a diff, a test run.
+ String transcriptLine(int index) {
+ switch (index % 24) {
+ case 0:
+ return '$_gray> ${_pick(['fix the flaky login test', 'why does CI fail on main', 'tighten the rate limiter', 'add a retry to the session refresh'])}$_reset';
+ case 1:
+ case 4:
+ case 8:
+ case 16:
+ case 22:
+ return '';
+ case 2:
+ case 3:
+ case 20:
+ case 21:
+ return '⏺ ${_prose()}';
+ case 5:
+ return '⏺ $_bold${'Read'}$_reset(${_pick(_files)})';
+ case 6:
+ return ' $_gray⎿ Read ${80 + _random.nextInt(300)} lines (ctrl+r to expand)$_reset';
+ case 7:
+ return '⏺ $_bold${'Update'}$_reset(${_pick(_files)})';
+ case 9:
+ return ' $_gray⎿ Updated ${_pick(_files)} with 2 additions and 1 removal$_reset';
+ case 10:
+ return '$_gray ${_diffLine++} it(\'logs in\', async () => {$_reset';
+ case 11:
+ return '$_delBg ${_diffLine++} - expect(res.status).toBe(200)$_reset';
+ case 12:
+ return '$_addBg $_diffLine + await waitFor(() => expect(res.status).toBe(200))$_reset';
+ case 13:
+ return '$_addBg ${_diffLine++} + expect(session.expiresAt).toBeGreaterThan(now())$_reset';
+ case 14:
+ return '$_gray ${_diffLine++} })$_reset';
+ case 15:
+ return '⏺ $_bold${'Bash'}$_reset(npm test -- ${_pick(['login', 'session', 'rateLimit'])})';
+ case 17:
+ return ' $_gray⎿$_reset $_green${_bold}PASS$_reset src/auth/login.test.ts (${(2 + _random.nextDouble() * 5).toStringAsFixed(1)} s)';
+ case 18:
+ return ' Tests: ${10 + _random.nextInt(30)} passed, ${10 + _random.nextInt(30)} total';
+ case 19:
+ return ' Time: ${(3 + _random.nextDouble() * 9).toStringAsFixed(2)} s';
+ default:
+ return '⏺ ${_prose(minWords: 10, maxWords: 20)}';
+ }
+ }
+
+ /// [count] transcript lines starting at [from], each ending in CRLF.
+ String transcript(int from, int count) {
+ final buffer = StringBuffer();
+ for (var i = 0; i < count; i++) {
+ buffer.write(transcriptLine(from + i));
+ buffer.write('\r\n');
+ }
+ return buffer.toString();
+ }
+
+ /// A prose-only line for the append load: long, so it wraps 3–7 times on a
+ /// phone, the shape of an answer streaming in.
+ String proseLine() => '⏺ ${_prose(minWords: 28, maxWords: 60)}';
+
+ /// Clips plain text to the row, three columns short of the edge: some of
+ /// Claude's glyphs (`⏺`, `⏵`, `☐`) may take two cells in the emulator's
+ /// width table, and a row that wrapped would make the region taller than
+ /// the erase above it.
+ String _fit(String plain) =>
+ plain.length <= cols - 3 ? plain : plain.substring(0, cols - 3);
+
+ /// The live region at tick [tick], rows joined by CRLF with no trailing
+ /// newline: the cursor rests at the end of its last row, as Ink leaves it.
+ String liveRegion(int tick) {
+ final seconds = tick ~/ 20;
+ final tokens = (tick * 7.3).round();
+ final spinner = _spinner[tick % _spinner.length];
+ final verb = _verbs[(tick ~/ 60) % _verbs.length];
+ final width = cols - 1;
+ final rows = <String>[
+ '$_orange${_fit('$spinner $verb… (${seconds}s · ↓ ${(tokens / 1000).toStringAsFixed(1)}k tokens · esc to interrupt)')}$_reset',
+ '$_gray${_fit(' ⎿ ☒ Read the flaky test')}$_reset',
+ '$_orange${_fit(' ☐ Run the login tests again')}$_reset',
+ '',
+ '$_dim╭${'─' * (width - 2)}╮$_reset',
+ '$_dim│$_reset > ${' ' * (width - 5)}$_dim│$_reset',
+ '$_dim╰${'─' * (width - 2)}╯$_reset',
+ '$_purple${_fit(' ⏵⏵ accept edits on (shift+tab to cycle)')}$_reset',
+ ];
+ assert(rows.length == liveRows);
+ return rows.join('\r\n');
+ }
+
+ /// Ink's `eraseLines`: from the end of the region's last row, clear each row
+ /// and step up, leaving the cursor at column 1 of the region's first row.
+ static String get eraseLive =>
+ '\r${List.filled(liveRows - 1, '\x1b[2K\x1b[1A').join()}\x1b[2K';
+
+ static const _syncStart = '\x1b[?2026h';
+ static const _syncEnd = '\x1b[?2026l';
+
+ /// A redraw burst: the live region erased and drawn again in place — the
+ /// desktop benchmark's eight-row redraw, in Claude Code's shape.
+ String redrawBurst(int tick) =>
+ '$_syncStart$eraseLive${liveRegion(tick)}$_syncEnd';
+
+ /// An append burst: [lines] new transcript lines above the live region, and
+ /// the region drawn again under them.
+ String appendBurst(int tick, {int lines = 3}) {
+ final buffer = StringBuffer(_syncStart)..write(eraseLive);
+ for (var i = 0; i < lines; i++) {
+ buffer
+ ..write(proseLine())
+ ..write('\r\n');
+ }
+ buffer
+ ..write(liveRegion(tick))
+ ..write(_syncEnd);
+ return buffer.toString();
+ }
+
+ /// A keyframe's body: [historyLines] transcript lines and the live region
+ /// under them, with the cursor hidden the way Claude Code keeps it.
+ String keyframe(int historyLines) =>
+ '\x1b[?25l${transcript(0, historyLines)}${liveRegion(0)}';
+}
diff --git a/mobile/integration_test/perf/fixture.dart b/mobile/integration_test/perf/fixture.dart
new file mode 100644
index 000000000..c22e5e332
--- /dev/null
+++ b/mobile/integration_test/perf/fixture.dart
@@ -0,0 +1,341 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io' show ZLibCodec;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/phone/voice_recorder.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_binary.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+/// The machine every fixture agent lives on.
+const perfMachineId = 'perf-machine';
+
+/// The agents Find lists: the first two have live terminals (Find switches
+/// between them), the rest are rows. Most recent first, so the two switched
+/// between are always the top rows.
+const perfAgents = <(String, String)>[
+ ('agent-a', 'fix flaky login test'),
+ ('agent-b', 'tighten rate limiter'),
+ ('agent-c', 'docs rewrite'),
+ ('agent-d', 'release notes 1.0'),
+ ('agent-e', 'db migration dry run'),
+ ('agent-f', 'search ranking'),
+ ('agent-g', 'onboarding copy'),
+ ('agent-h', 'mobile perf pass'),
+];
+
+/// A synthetic live terminal, fed through the production binary path.
+///
+/// Output goes through [TerminalSession.handleBinary] — the same decode
+/// (zlib when the daemon would have compressed), UTF-8 and xterm parse a
+/// relayed frame gets — with a sequence number, as the daemon sends it. What is
+/// NOT here: the socket, the relay/P2P transport and its E2EE decryption, and
+/// the daemon and tmux on the far side.
+class FixtureTerminal {
+ FixtureTerminal._(this.session, this.agentId);
+
+ final TerminalSession session;
+ final String agentId;
+ int _seq = 0;
+
+ /// `terminal_resize` frames the session sent, which a steady terminal must
+ /// not send — a fixture that resizes is measuring the wrong thing.
+ int resizes = 0;
+
+ /// The grid the last `terminal_resize` asked for: what the view measured.
+ ///
+ /// ⚠️ **Not `terminal.viewWidth`.** The phone's emulator stays at the size
+ /// the machine last drew — xterm does not resize it locally — and asks the
+ /// machine for its own size instead, which answers with a keyframe at that
+ /// size. A seed at `viewWidth` was an 80×24 screen drawn into a phone.
+ (int, int)? lastResize;
+
+ static final ZLibCodec _zlib = ZLibCodec(level: 1);
+
+ /// The daemon's rule (`encoded` in `cli/src/lib/terminalStreamManager.ts`):
+ /// zlib level 1 above 1 KiB, when it actually saves bytes. The phone asks
+ /// for zlib, so this is what its frames look like.
+ static ({Uint8List bytes, bool compressed}) encode(String text) {
+ final raw = Uint8List.fromList(utf8.encode(text));
+ if (raw.length > 1024) {
+ final packed = Uint8List.fromList(_zlib.encode(raw));
+ if (packed.length < raw.length) return (bytes: packed, compressed: true);
+ }
+ return (bytes: raw, compressed: false);
+ }
+
+ /// A full screen and its history, as the machine sends on attach — a new
+ /// emulator, replaced atomically.
+ Future<void> keyframe(String text, {required int cols, required int rows}) {
+ final body = encode(text);
+ return session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: session.streamId!,
+ seq: _seq++,
+ bytes: body.bytes,
+ compressed: body.compressed,
+ cols: cols,
+ rows: rows,
+ ),
+ );
+ }
+
+ /// One output frame, pre-encoded. Answers the microseconds the session took
+ /// to take it in: decode, UTF-8 and the xterm parse, on this thread.
+ Future<int> output(({Uint8List bytes, bool compressed}) body) async {
+ final watch = Stopwatch()..start();
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.output,
+ streamId: session.streamId!,
+ seq: _seq++,
+ bytes: body.bytes,
+ compressed: body.compressed,
+ ),
+ );
+ return watch.elapsedMicroseconds;
+ }
+}
+
+/// The account the benchmark shows: one machine, eight agents, two of them
+/// attached — and nothing that can reach a real machine.
+///
+/// ⚠️ **Nothing here can reach the owner's harnesses.** No config store, no
+/// layout store (so nothing is read from or written to the app's files), a
+/// fresh in-memory auth session, and every machine connection is
+/// [_SilentConn]: it never dials and answers every request with nothing. The
+/// installed build shares its bundle id — and so its data container — with the
+/// owner's development copy, which is exactly why none of that may be touched.
+class PerfFixture {
+ PerfFixture._(this.notifier, this.terminals, this.voice, this._language);
+
+ final AppNotifier notifier;
+ final Map<String, FixtureTerminal> terminals;
+ final VoiceInputController voice;
+ final ValueNotifier<String> _language;
+
+ static PerfFixture create() {
+ final now = DateTime.now();
+ // As the daemon's `agents_list` carries them — the connection answers a
+ // reload with these same records, so a reload changes nothing.
+ final wireAgents = [
+ for (final (index, (id, name)) in perfAgents.indexed)
+ <String, dynamic>{
+ 'id': id,
+ 'name': name,
+ 'sessionId': 'session-$id',
+ 'engine': 'claude',
+ 'status': 'active',
+ 'terminal': {'available': true},
+ 'project': {'name': 'harness', 'cwd': '/srv/harness'},
+ 'updatedAt': now
+ .subtract(Duration(minutes: 3 + index * 17))
+ .toUtc()
+ .toIso8601String(),
+ },
+ ];
+ final notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ connectionForTest: (machineId) => _SilentConn(machineId, wireAgents),
+ );
+ const machine = Machine(
+ machineId: perfMachineId,
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ );
+ notifier.machines = [machine];
+ notifier.machineStates[perfMachineId] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [for (final json in wireAgents) Agent.fromJson(json)];
+ final terminals = <String, FixtureTerminal>{};
+ for (final (id, name) in perfAgents.take(2)) {
+ late FixtureTerminal terminal;
+ final session =
+ TerminalSession(
+ machineId: perfMachineId,
+ agentId: id,
+ agentName: name,
+ engineId: 'claude',
+ send: (type, payload) async {
+ if (type == 'terminal_resize') {
+ terminal.resizes++;
+ terminal.lastResize = (
+ payload['cols'] as int,
+ payload['rows'] as int,
+ );
+ }
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )
+ ..streamId =
+ '00000000-0000-4000-8000-00000000000${terminals.length + 1}';
+ terminal = FixtureTerminal._(session, id);
+ terminals[id] = terminal;
+ // ignore: invalid_use_of_visible_for_testing_member
+ notifier.adoptSessionForTest(session);
+ }
+ final language = ValueNotifier('en');
+ return PerfFixture._(
+ notifier,
+ terminals,
+ VoiceInputController(
+ transcriber: (_, _) async => '',
+ recorder: FakeRecorder(),
+ language: language,
+ ),
+ language,
+ );
+ }
+
+ String nameOf(String agentId) =>
+ perfAgents.firstWhere((agent) => agent.$1 == agentId).$2;
+
+ void dispose() {
+ voice.dispose();
+ _language.dispose();
+ notifier.dispose();
+ }
+}
+
+/// The app's own dark theme, as `app_shell.dart` builds it, around [home].
+Widget perfApp(Widget home, {List<NavigatorObserver> observers = const []}) {
+ grid.AppTheme.brightness.value = Brightness.dark;
+ return MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ navigatorObservers: observers,
+ builder: (context, child) =>
+ grid.BrightnessScope(child: child ?? const SizedBox.shrink()),
+ home: home,
+ );
+}
+
+/// The home screen's one agent at a time: [TerminalPage] at the root, swapped
+/// for another agent's when Find opens one.
+///
+/// ⚠️ **The production home is `AgentHome` → `AgentSwipeHost` → `TerminalPage`,
+/// and this is the last of those three.** Opening an agent from Find calls the
+/// shell's `onOpenAgent` (see `openAgent` in `phone_navigation.dart`); this
+/// answers it by building the other agent's page in place, keyed by agent, as
+/// `AgentHome` does with its pager. Not included: `AgentHome`'s pager snapshot
+/// and bookkeeping, `AgentSwipeHost`'s visit record, the shell's tab reset, and
+/// `selectAgent`'s attach — both agents' terminals are already attached and
+/// rendered here, so a switch never waits on a keyframe.
+class FocusHost extends StatefulWidget {
+ const FocusHost({
+ super.key,
+ required this.fixture,
+ required this.initialAgentId,
+ });
+
+ final PerfFixture fixture;
+ final String initialAgentId;
+
+ @override
+ State<FocusHost> createState() => FocusHostState();
+}
+
+class FocusHostState extends State<FocusHost> {
+ late String agentId = widget.initialAgentId;
+
+ void show(String next) => setState(() => agentId = next);
+
+ @override
+ Widget build(BuildContext context) => PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (_, next) => show(next),
+ child: TerminalPage(
+ key: ValueKey(agentId),
+ notifier: widget.fixture.notifier,
+ machineId: perfMachineId,
+ agentId: agentId,
+ voice: widget.fixture.voice,
+ ),
+ );
+}
+
+/// A microphone that opens at once and hears nothing: the benchmark times the
+/// app's answer to a tap, not the audio hardware opening.
+class FakeRecorder implements VoiceRecorder {
+ @override
+ Future<bool> allowed() async => true;
+
+ @override
+ Future<void> start() async {}
+
+ @override
+ Future<VoiceTake?> stop() async => null;
+
+ @override
+ Future<void> cancel() async {}
+
+ @override
+ Future<void> dispose() async {}
+}
+
+class MemoryStore implements LocalKeyValueStore {
+ final Map<String, String> values = {};
+
+ @override
+ Future<String?> read(String key) async => values[key];
+
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+/// A machine connection that never dials: it reads as ready, answers
+/// `agents_list` with the fixture's own agents (so a reload the notifier starts
+/// by itself is a no-op rather than a ten-second wait with the header showing a
+/// refresh), and answers every other request — what the new-agent form asks as
+/// it opens — with nothing.
+class _SilentConn extends WsConn {
+ _SilentConn(String machineId, this._agents)
+ : super(
+ wsBaseUrl: 'ws://perf.invalid',
+ autonomousEnv: 'test',
+ machineId: machineId,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final List<Map<String, dynamic>> _agents;
+
+ @override
+ bool get isReady => true;
+
+ @override
+ Future<void> waitUntilReady({required Duration timeout}) async {}
+
+ @override
+ Future<void> connect() async {}
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => type == 'agents_list' ? {'agents': _agents} : {};
+}
diff --git a/mobile/integration_test/perf/frames.dart b/mobile/integration_test/perf/frames.dart
new file mode 100644
index 000000000..7331095f3
--- /dev/null
+++ b/mobile/integration_test/perf/frames.dart
@@ -0,0 +1,188 @@
+import 'dart:async';
+import 'dart:ui' as ui;
+
+import 'package:flutter/scheduler.dart';
+import 'package:flutter/widgets.dart';
+
+/// Wall-clock microseconds, the clock every dispatch time here is taken on.
+///
+/// FrameTiming carries its phases on the engine's monotonic clock plus ONE
+/// wall-clock stamp (raster finish), which is what lets a dispatch taken here be
+/// placed against them — see [FrameClock.wall].
+int wallMicros() => DateTime.now().microsecondsSinceEpoch;
+
+/// Asks for a frame and waits for it; answers the engine's number for it, the
+/// key its [ui.FrameTiming] arrives under.
+///
+/// The desktop benchmark's `_frame()`: a post-frame callback reads the number
+/// of the frame it runs in, and a forced schedule makes sure there is one even
+/// when nothing is dirty. The zero delay lets a focus or setState requested
+/// from a post-frame callback land before the caller acts again.
+Future<int> nextFrame() async {
+ final done = Completer<int>();
+ SchedulerBinding.instance.addPostFrameCallback((_) {
+ done.complete(ui.PlatformDispatcher.instance.frameData.frameNumber);
+ });
+ SchedulerBinding.instance.scheduleFrame();
+ final number = await done.future;
+ await Future<void>.delayed(Duration.zero);
+ return number;
+}
+
+/// The frame number of the frame currently being produced, read inside a
+/// post-frame callback — for observers that must not force a frame themselves.
+int currentFrameNumber() =>
+ ui.PlatformDispatcher.instance.frameData.frameNumber;
+
+/// Every [ui.FrameTiming] the engine reports, by frame number, for the life of
+/// the run.
+class FrameClock {
+ FrameClock() {
+ SchedulerBinding.instance.addTimingsCallback(_take);
+ }
+
+ final Map<int, ui.FrameTiming> byNumber = {};
+ final List<ui.FrameTiming> all = [];
+
+ void _take(List<ui.FrameTiming> timings) {
+ for (final timing in timings) {
+ byNumber[timing.frameNumber] = timing;
+ all.add(timing);
+ }
+ }
+
+ void dispose() => SchedulerBinding.instance.removeTimingsCallback(_take);
+
+ /// A phase of [timing] on the wall clock — the desktop benchmark's join: the
+ /// engine stamps raster finish on both clocks, so their difference moves any
+ /// other phase onto the wall clock.
+ static int wall(ui.FrameTiming timing, ui.FramePhase phase) =>
+ timing.timestampInMicroseconds(ui.FramePhase.rasterFinishWallTime) -
+ timing.timestampInMicroseconds(ui.FramePhase.rasterFinish) +
+ timing.timestampInMicroseconds(phase);
+
+ /// Waits until every frame in [numbers] has its timing. The engine batches
+ /// its reports (every 100 ms or 100 frames outside release), so the last
+ /// frames of a series need a nudge and a moment.
+ Future<void> waitFor(Iterable<int> numbers) async {
+ final wanted = numbers.toSet();
+ for (var attempt = 0; attempt < 40; attempt++) {
+ if (wanted.every(byNumber.containsKey)) return;
+ await nextFrame();
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ final missing = wanted.where((n) => !byNumber.containsKey(n)).toList();
+ throw StateError('No FrameTiming for frames $missing');
+ }
+
+ /// Waits for timings to cover everything up to [untilWall] (wall micros).
+ Future<void> settleUntil(int untilWall) async {
+ for (var attempt = 0; attempt < 40; attempt++) {
+ if (all.isNotEmpty &&
+ wall(all.last, ui.FramePhase.rasterFinish) >= untilWall) {
+ return;
+ }
+ await nextFrame();
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ }
+
+ /// Frames whose build began inside [startWall, endWall).
+ List<ui.FrameTiming> between(int startWall, int endWall) => [
+ for (final timing in all)
+ if (wall(timing, ui.FramePhase.buildStart) >= startWall &&
+ wall(timing, ui.FramePhase.buildStart) < endWall)
+ timing,
+ ];
+}
+
+/// Nearest-rank percentiles over individual observations, in milliseconds —
+/// the same rule as `desktop/tool/native_benchmark/summarize_results.py`.
+Map<String, num> distribution(List<int> micros) {
+ if (micros.isEmpty) return {'samples': 0};
+ final values = [...micros]..sort();
+ double at(double q) => values[(values.length * q).ceil() - 1] / 1000;
+ return {
+ 'samples': values.length,
+ 'p50Ms': at(.5),
+ 'p95Ms': at(.95),
+ 'p99Ms': at(.99),
+ 'maxMs': values.last / 1000,
+ };
+}
+
+/// One refresh at the iPhone 14's 60 Hz — the budget a frame has to fit.
+const int frameBudgetMicros = 16667;
+
+/// Per-frame statistics for a window of frames: build (UI thread), raster,
+/// vsync overhead and total span, as the engine reports them.
+Map<String, Object?> frameStats(
+ List<ui.FrameTiming> frames, {
+ required int windowMicros,
+}) {
+ List<int> pick(int Function(ui.FrameTiming) f) => [
+ for (final t in frames) f(t),
+ ];
+ final build = pick((t) => t.buildDuration.inMicroseconds);
+ final raster = pick((t) => t.rasterDuration.inMicroseconds);
+ final vsync = pick((t) => t.vsyncOverhead.inMicroseconds);
+ final total = pick((t) => t.totalSpan.inMicroseconds);
+ int over(List<int> values) =>
+ values.where((v) => v > frameBudgetMicros).length;
+ return {
+ 'frames': frames.length,
+ 'windowMs': windowMicros / 1000,
+ 'framesPerSecond': frames.length / (windowMicros / 1e6),
+ 'buildMs': distribution(build),
+ 'rasterMs': distribution(raster),
+ 'vsyncOverheadMs': distribution(vsync),
+ 'totalSpanMs': distribution(total),
+ 'framesOverBudget': {
+ 'budgetMs': frameBudgetMicros / 1000,
+ 'build': over(build),
+ 'raster': over(raster),
+ 'totalSpan': over(total),
+ },
+ 'uiBusyShare': build.fold<int>(0, (a, b) => a + b) / windowMicros,
+ 'rasterBusyShare': raster.fold<int>(0, (a, b) => a + b) / windowMicros,
+ // Every frame, so runs can be pooled observation by observation rather
+ // than by averaging percentiles: [frame number, build, raster, vsync
+ // overhead, total span] in microseconds.
+ 'rawColumns': [
+ 'frame',
+ 'buildUs',
+ 'rasterUs',
+ 'vsyncOverheadUs',
+ 'totalSpanUs',
+ ],
+ 'raw': [
+ for (final t in frames)
+ [
+ t.frameNumber,
+ t.buildDuration.inMicroseconds,
+ t.rasterDuration.inMicroseconds,
+ t.vsyncOverhead.inMicroseconds,
+ t.totalSpan.inMicroseconds,
+ ],
+ ],
+ };
+}
+
+/// Every element under the root whose widget matches, skipping offstage
+/// subtrees — the desktop benchmark's `_find`, but collecting.
+List<Element> findElements(bool Function(Widget) matches) {
+ final found = <Element>[];
+ void visit(Element element) {
+ if (element.widget case Offstage(offstage: true)) return;
+ if (matches(element.widget)) found.add(element);
+ element.visitChildElements(visit);
+ }
+
+ WidgetsBinding.instance.rootElement?.visitChildElements(visit);
+ return found;
+}
+
+Element? findElement(bool Function(Widget) matches) {
+ final all = findElements(matches);
+ return all.isEmpty ? null : all.first;
+}
diff --git a/mobile/integration_test/perf/gestures.dart b/mobile/integration_test/perf/gestures.dart
new file mode 100644
index 000000000..2c0bc3953
--- /dev/null
+++ b/mobile/integration_test/perf/gestures.dart
@@ -0,0 +1,134 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'frames.dart';
+import 'perf_binding.dart';
+
+/// Touches delivered the way the engine delivers the phone's own: into
+/// [GestureBinding]'s hit test and dispatch, as device events.
+///
+/// ⚠️ **Not `WidgetTester.tap`/`fling`.** Those are TEST-sourced events, and
+/// the live binding paints a crosshair over the app for each of them and
+/// repaints the root to fade it out — extra paint and raster work inside the
+/// very frames being timed. Device-sourced events go straight to the framework
+/// while [LiveTestWidgetsFlutterBinding.shouldPropagateDevicePointerEvents] is
+/// on, exactly as a finger's would.
+///
+/// ⚠️ **On for each synthetic event only, never across the run.** Left on, the
+/// phone's REAL touches reach the app too — somebody picking the phone up
+/// mid-run scrolls the terminal and the frames it draws are counted as the
+/// benchmark's. Each event here turns it on, is dispatched synchronously, and
+/// turns it off; a real touch, which arrives between them from the engine, is
+/// dropped by the live binding as it always is.
+///
+/// This is the desktop benchmark's boundary moved to touch: **framework
+/// dispatch**. Digitizer sampling, the OS's touch delivery and the engine's
+/// pointer packet conversion are outside it.
+class Touches {
+ Touches(this.binding);
+
+ final PerfBinding binding;
+ final Stopwatch _clock = Stopwatch()..start();
+ int _nextPointer = 100;
+
+ Duration get _stamp => Duration(microseconds: _clock.elapsedMicroseconds);
+
+ void _send(PointerEvent event) {
+ binding.shouldPropagateDevicePointerEvents = true;
+ try {
+ binding.handlePointerEventForSource(
+ event,
+ source: TestBindingEventSource.device,
+ );
+ } finally {
+ binding.shouldPropagateDevicePointerEvents = false;
+ }
+ }
+
+ /// A finger put down at [position]; returns it for moves and the lift.
+ Finger down(Offset position) {
+ final finger = Finger._(this, TestPointer(_nextPointer++), position);
+ _send(finger._pointer.down(position, timeStamp: _stamp));
+ return finger;
+ }
+
+ /// The centre of [element]'s box, in the coordinates hit testing uses —
+ /// checked by hit testing it, so a tap is known to land on what it names.
+ Offset centerOf(Element element, {Offset shift = Offset.zero}) {
+ final box = element.renderObject! as RenderBox;
+ final point = box.localToGlobal(box.size.center(Offset.zero)) + shift;
+ final result = HitTestResult();
+ binding.hitTestInView(
+ result,
+ point,
+ binding.platformDispatcher.implicitView!.viewId,
+ );
+ final hit =
+ result.path.any((entry) => entry.target == box) ||
+ result.path.any(
+ (entry) =>
+ entry.target is RenderObject &&
+ _isDescendant(entry.target as RenderObject, box),
+ );
+ if (!hit) {
+ throw StateError(
+ 'A touch at $point would not reach ${element.widget.runtimeType}',
+ );
+ }
+ return point;
+ }
+
+ static bool _isDescendant(RenderObject node, RenderObject ancestor) {
+ RenderObject? current = node;
+ while (current != null) {
+ if (identical(current, ancestor)) return true;
+ current = current.parent;
+ }
+ return false;
+ }
+}
+
+class Finger {
+ Finger._(this._touches, this._pointer, this._at);
+
+ final Touches _touches;
+ final TestPointer _pointer;
+ Offset _at;
+
+ Offset get position => _at;
+
+ /// Moves by [delta]; answers the wall-clock time just before dispatch.
+ int moveBy(Offset delta) {
+ _at += delta;
+ final began = wallMicros();
+ _touches._send(_pointer.move(_at, timeStamp: _touches._stamp));
+ return began;
+ }
+
+ /// Lifts the finger; answers the wall-clock time just before dispatch.
+ int up() {
+ final began = wallMicros();
+ _touches._send(_pointer.up(timeStamp: _touches._stamp));
+ return began;
+ }
+
+ void cancel() => _touches._send(_pointer.cancel(timeStamp: _touches._stamp));
+}
+
+/// A finger's path at the touch rate: one move every [interval], real time
+/// between them, so frames and gesture recognizers interleave the way they do
+/// under a thumb.
+Future<void> glide(
+ Finger finger,
+ Offset delta, {
+ required int steps,
+ Duration interval = const Duration(milliseconds: 8),
+}) async {
+ final step = delta / steps.toDouble();
+ for (var i = 0; i < steps; i++) {
+ await Future<void>.delayed(interval);
+ finger.moveBy(step);
+ }
+}
diff --git a/mobile/integration_test/perf/perf_binding.dart b/mobile/integration_test/perf/perf_binding.dart
new file mode 100644
index 000000000..55b1313e9
--- /dev/null
+++ b/mobile/integration_test/perf/perf_binding.dart
@@ -0,0 +1,45 @@
+import 'package:integration_test/integration_test.dart';
+
+/// The integration-test binding, drawing frames the way the app's own binding
+/// does: only when the framework asked for one.
+///
+/// ⚠️ **Without this every measurement here would be of a different app.**
+/// [LiveTestWidgetsFlutterBinding] (which [IntegrationTestWidgetsFlutterBinding]
+/// extends) ends every frame by asking the engine for another one, and under
+/// `benchmarkLive`/`fullyLive` it draws each of them — so an idle terminal was
+/// rebuilt, composited and rasterized at 60 Hz for the whole run, and a 20 Hz
+/// output stream measured on top of 40 frames a second nobody asked for.
+///
+/// The fix is to skip a vsync the framework did not schedule. The framework's
+/// own requests set `hasScheduledFrame` before the engine calls back, and it is
+/// cleared inside `handleBeginFrame`, so it is still set when this override
+/// runs. A skipped begin is paired with a skipped draw, which keeps the live
+/// binding's begin/draw bookkeeping intact and — since its `handleDrawFrame`
+/// never runs — stops the self-rescheduling loop. What is left is one idle vsync
+/// callback after each real frame: no build, no scene, no raster.
+class PerfBinding extends IntegrationTestWidgetsFlutterBinding {
+ bool _skipped = false;
+
+ /// Vsyncs the framework did not ask for, and so did not draw.
+ int skippedVsyncs = 0;
+
+ @override
+ void handleBeginFrame(Duration? rawTimeStamp) {
+ if (!hasScheduledFrame) {
+ _skipped = true;
+ skippedVsyncs++;
+ return;
+ }
+ _skipped = false;
+ super.handleBeginFrame(rawTimeStamp);
+ }
+
+ @override
+ void handleDrawFrame() {
+ if (_skipped) {
+ _skipped = false;
+ return;
+ }
+ super.handleDrawFrame();
+ }
+}
diff --git a/mobile/integration_test/perf/scenarios.dart b/mobile/integration_test/perf/scenarios.dart
new file mode 100644
index 000000000..8dbe7aff4
--- /dev/null
+++ b/mobile/integration_test/perf/scenarios.dart
@@ -0,0 +1,910 @@
+import 'dart:io' show Platform;
+import 'dart:ui' as ui;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/phone/find_row.dart';
+import 'package:harness_mobile/phone/terminal_search.dart';
+import 'package:harness_mobile/phone/voice_mic_button.dart';
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+import 'package:harness_mobile/widgets/terminal_panel.dart';
+import 'package:wakelock_plus/wakelock_plus.dart';
+import 'package:xterm/xterm.dart';
+
+import 'claude_output.dart';
+import 'fixture.dart';
+import 'frames.dart';
+import 'gestures.dart';
+import 'perf_binding.dart';
+import 'stream.dart';
+import 'timeline.dart';
+
+/// What to run, from `--dart-define`s — see `integration_test/README.md`.
+class PerfOptions {
+ const PerfOptions({
+ required this.scenarios,
+ required this.samples,
+ required this.warmups,
+ required this.streamSeconds,
+ required this.trace,
+ });
+
+ factory PerfOptions.fromEnvironment() {
+ const only = String.fromEnvironment('PERF_SCENARIOS');
+ return PerfOptions(
+ scenarios: only.isEmpty
+ ? null
+ : only.split(',').map((s) => s.trim()).toSet(),
+ samples: const int.fromEnvironment('PERF_SAMPLES', defaultValue: 35),
+ warmups: const int.fromEnvironment('PERF_WARMUPS', defaultValue: 5),
+ streamSeconds: const int.fromEnvironment(
+ 'PERF_STREAM_SECONDS',
+ defaultValue: 10,
+ ),
+ trace: const bool.fromEnvironment('PERF_TRACE', defaultValue: true),
+ );
+ }
+
+ /// Null runs everything.
+ final Set<String>? scenarios;
+ final int samples;
+ final int warmups;
+ final int streamSeconds;
+ final bool trace;
+
+ bool wants(String name) =>
+ scenarios == null || scenarios!.any((s) => name.startsWith(s));
+}
+
+/// One interaction observation, the desktop benchmark's row: dispatch, the
+/// frame before it, the first frame that shows the result and the frame at
+/// which it has finished arriving.
+class _Observation {
+ _Observation({
+ required this.operation,
+ required this.load,
+ required this.measured,
+ required this.began,
+ required this.dispatched,
+ required this.previousFrame,
+ required this.firstFrame,
+ required this.readyFrame,
+ this.extra = const {},
+ });
+
+ final String operation;
+ final String load;
+ final bool measured;
+ final int began;
+ final int dispatched;
+ final int previousFrame;
+ final int firstFrame;
+ final int readyFrame;
+ final Map<String, Object?> extra;
+ final Map<String, int> derived = {};
+
+ void derive(FrameClock clock, {int? readyBegan}) {
+ final previous = clock.byNumber[previousFrame]!;
+ final first = clock.byNumber[firstFrame]!;
+ final ready = clock.byNumber[readyFrame]!;
+ int rasterWall(ui.FrameTiming t) =>
+ t.timestampInMicroseconds(ui.FramePhase.rasterFinishWallTime);
+ derived['dispatchMicros'] = dispatched - began;
+ derived['firstRasterMicros'] = rasterWall(first) - began;
+ derived['readyRasterMicros'] = rasterWall(ready) - (readyBegan ?? began);
+ derived['buildMicros'] = first.buildDuration.inMicroseconds;
+ derived['rasterMicros'] = first.rasterDuration.inMicroseconds;
+ derived['previousBuildMicros'] = previous.buildDuration.inMicroseconds;
+ derived['dispatchAfterPreviousVsyncMicros'] =
+ began - FrameClock.wall(previous, ui.FramePhase.vsyncStart);
+ derived['waitForBuildMicros'] =
+ FrameClock.wall(first, ui.FramePhase.buildStart) - began;
+ derived['buildStartToRasterMicros'] =
+ first.timestampInMicroseconds(ui.FramePhase.rasterFinish) -
+ first.timestampInMicroseconds(ui.FramePhase.buildStart);
+ derived['framesToReady'] = readyFrame - firstFrame;
+ if (derived['firstRasterMicros']! < 0) {
+ throw StateError('$operation: raster finished before dispatch');
+ }
+ }
+
+ Map<String, Object?> toJson() => {
+ 'operation': operation,
+ 'load': load,
+ 'phase': measured ? 'measured' : 'warmup',
+ 'startedWallMicros': began,
+ 'previousFrame': previousFrame,
+ 'firstFrame': firstFrame,
+ 'readyFrame': readyFrame,
+ ...derived,
+ ...extra,
+ };
+}
+
+/// The phone benchmark: production widgets, a synthetic account, frames timed
+/// by the engine. See `docs/performance/2026-09-26-mobile-baseline.md`.
+class PerfSuite {
+ PerfSuite(this.tester, this.binding, this.options);
+
+ final WidgetTester tester;
+ final PerfBinding binding;
+ final PerfOptions options;
+
+ late final PerfFixture fixture = PerfFixture.create();
+ final FrameClock clock = FrameClock();
+ late final Touches touches = Touches(binding);
+ final GlobalKey<FocusHostState> _host = GlobalKey();
+ final List<NavigatorObserver> _observers = [];
+
+ final Map<String, Object?> scenarios = {};
+ final Map<String, Object?> traces = {};
+ final Map<String, String> failures = {};
+ final List<Map<String, Object?>> observations = [];
+ late final Map<String, ClaudeOutput> _outputs;
+ final Map<String, Object?> terminalInfo = {};
+
+ static const _a = 'agent-a';
+ static const _b = 'agent-b';
+
+ FixtureTerminal get _terminalA => fixture.terminals[_a]!;
+
+ Future<void> run() async {
+ final startedAt = DateTime.now();
+ // Synthetic touches do not reset the idle timer; a lock would suspend the
+ // app mid-run.
+ await WakelockPlus.enable();
+ await _mountFocus();
+ await _seed();
+ await _step('idle', _idle);
+ await _step(
+ 'stream_redraw',
+ () => _stream('stream_redraw', StreamLoad.redraw),
+ );
+ await _step(
+ 'stream_append',
+ () => _stream('stream_append', StreamLoad.append),
+ );
+ await _step('scroll_read', _scroll);
+ // Find opens by a swipe only: a tap on the title is its menu now.
+ await _step('find_open_swipe', _findOpenSwipe);
+ await _step('mic_tap', () => _micTap(idle: true));
+ await _step('mic_tap_streaming', () => _micTap(idle: false));
+ await _step('new_open_swipe', _newOpenSwipe);
+ await _step('find_switch', _findSwitch);
+ if (options.trace) {
+ await _step('trace_idle', _traceIdle);
+ await _step(
+ 'trace_stream_redraw',
+ () => _traceStream('stream_redraw', StreamLoad.redraw),
+ );
+ await _step(
+ 'trace_stream_append',
+ () => _traceStream('stream_append', StreamLoad.append),
+ );
+ await _step('trace_find_open_tap', _traceFindOpen);
+ }
+ await _step('control_panel_redraw', _controlPanel);
+ final finishedAt = DateTime.now();
+ await WakelockPlus.disable();
+ binding.reportData = {
+ 'schema': 1,
+ 'kind': 'mobile_framework_dispatch_to_raster',
+ 'success': failures.isEmpty,
+ 'failures': failures,
+ 'metadata': {
+ ..._metadata(),
+ 'startedAt': startedAt.toIso8601String(),
+ 'finishedAt': finishedAt.toIso8601String(),
+ 'samplesPerOperation': options.samples,
+ 'warmupsPerOperation': options.warmups,
+ 'streamWindowSeconds': options.streamSeconds,
+ 'scenarioFilter': options.scenarios?.toList(),
+ 'terminal': terminalInfo,
+ // After seeding: a steady terminal sends none, and a resize would put
+ // a SIGWINCH and a keyframe into what is being measured.
+ 'resizesSentWhileMeasuring': {
+ for (final t in fixture.terminals.values) t.agentId: t.resizes,
+ },
+ 'skippedUnrequestedVsyncs': binding.skippedVsyncs,
+ },
+ 'scenarios': scenarios,
+ 'traces': traces,
+ 'observations': observations,
+ };
+ clock.dispose();
+ }
+
+ Map<String, Object?> _metadata() {
+ final view = binding.platformDispatcher.implicitView!;
+ return {
+ 'buildMode': kReleaseMode
+ ? 'release'
+ : kProfileMode
+ ? 'profile'
+ : 'debug',
+ 'os': Platform.operatingSystem,
+ 'osVersion': Platform.operatingSystemVersion,
+ 'dart': Platform.version,
+ 'processors': Platform.numberOfProcessors,
+ 'physicalSize': [view.physicalSize.width, view.physicalSize.height],
+ 'devicePixelRatio': view.devicePixelRatio,
+ 'logicalSize': [
+ view.physicalSize.width / view.devicePixelRatio,
+ view.physicalSize.height / view.devicePixelRatio,
+ ],
+ 'displayRefreshRate': view.display.refreshRate,
+ 'terminalFontSize': terminalFontStore.size,
+ 'terminalFontFamily': terminalFontStore.family.label,
+ };
+ }
+
+ Future<void> _step(String name, Future<void> Function() body) async {
+ if (!options.wants(name)) return;
+ debugPrint('[perf] $name');
+ try {
+ await body();
+ } catch (error, stack) {
+ failures[name] = '$error\n$stack';
+ debugPrint('[perf] $name FAILED: $error\n$stack');
+ // Leave the screen as the next scenario expects it.
+ await _recover();
+ }
+ }
+
+ Future<void> _recover() async {
+ try {
+ fixture.voice.clear();
+ await tester.pumpWidget(const SizedBox.shrink());
+ await _settle(frames: 3);
+ await _mountFocus();
+ } catch (error) {
+ debugPrint('[perf] recovery failed: $error');
+ }
+ }
+
+ Future<void> _settle({int frames = 2, Duration pause = Duration.zero}) async {
+ for (var i = 0; i < frames; i++) {
+ await nextFrame();
+ }
+ if (pause > Duration.zero) await Future<void>.delayed(pause);
+ }
+
+ Future<void> _mountFocus([String agentId = _a]) async {
+ await tester.pumpWidget(
+ perfApp(
+ FocusHost(key: _host, fixture: fixture, initialAgentId: agentId),
+ observers: _observers,
+ ),
+ );
+ await _settle(frames: 6, pause: const Duration(milliseconds: 300));
+ await _untilFrame(
+ () => findElement((w) => w is TerminalView) != null,
+ what: 'the terminal to mount',
+ );
+ }
+
+ /// Seeds both terminals the way an attach goes: a first keyframe at the
+ /// machine's size, the phone's `terminal_resize` for the grid its view
+ /// actually has, and a keyframe back at that size carrying the history.
+ ///
+ /// ⚠️ **The grid comes from the resize, not from the emulator.** The phone
+ /// never resizes its xterm locally — it keeps the machine's size until the
+ /// machine redraws at the size asked for — so `terminal.viewWidth` reads the
+ /// FIRST keyframe's 80×24 however narrow the phone is.
+ Future<void> _seed() async {
+ final session = _terminalA.session;
+ await _terminalA.keyframe(
+ ClaudeOutput(cols: 80).keyframe(20),
+ cols: 80,
+ rows: 24,
+ );
+ await _untilFrame(
+ () => _terminalA.lastResize != null,
+ what: 'the phone to ask for its grid',
+ );
+ final (cols, rows) = _terminalA.lastResize!;
+ _outputs = {};
+ for (final id in [_a, _b]) {
+ final output = ClaudeOutput(cols: cols, seed: id.hashCode);
+ await fixture.terminals[id]!.keyframe(
+ output.keyframe(2000),
+ cols: cols,
+ rows: rows,
+ );
+ _outputs[id] = output;
+ }
+ await _settle(frames: 6, pause: const Duration(milliseconds: 800));
+ if (!session.hasRenderedFrame) throw StateError('No keyframe rendered');
+ final initialResizes = {
+ for (final t in fixture.terminals.values) t.agentId: t.resizes,
+ };
+ for (final t in fixture.terminals.values) {
+ t.resizes = 0;
+ }
+ terminalInfo.addAll({
+ 'cols': cols,
+ 'rows': rows,
+ 'seededTranscriptLines': 2000,
+ 'retainedPhysicalRowsAfterSeed': session.terminal.buffer.lines.length,
+ 'resizesWhileSeeding': initialResizes,
+ });
+ }
+
+ Future<int> _untilFrame(
+ bool Function() done, {
+ required String what,
+ Duration limit = const Duration(seconds: 3),
+ }) async {
+ final watch = Stopwatch()..start();
+ while (true) {
+ final frame = await nextFrame();
+ if (done()) return frame;
+ if (watch.elapsed > limit)
+ throw StateError('Timed out waiting for $what');
+ }
+ }
+
+ // ---------------------------------------------------------------- windows
+
+ Future<void> _idle() async {
+ await _settle(frames: 2, pause: const Duration(seconds: 1));
+ final start = wallMicros();
+ await Future<void>.delayed(const Duration(seconds: 3));
+ final end = wallMicros();
+ await clock.settleUntil(end);
+ scenarios['idle'] = {
+ 'description':
+ 'Focus on a rendered terminal, nothing streaming, no input: what the '
+ 'app draws on its own.',
+ 'frames': frameStats(
+ clock.between(start, end),
+ windowMicros: end - start,
+ ),
+ };
+ }
+
+ Future<void> _stream(String name, StreamLoad load) async {
+ final pump = OutputPump(_terminalA, _outputs[_a]!, load)..start();
+ try {
+ await Future<void>.delayed(const Duration(seconds: 2));
+ final start = wallMicros();
+ await Future<void>.delayed(Duration(seconds: options.streamSeconds));
+ final end = wallMicros();
+ await pump.stop();
+ await clock.settleUntil(end);
+ scenarios[name] = {
+ 'description': load == StreamLoad.redraw
+ ? 'Terminal at the bottom while Claude Code\'s 8-row live region is '
+ 'erased and redrawn in place at 20 Hz.'
+ : 'Terminal at the bottom while ~60 long lines/s of prose append '
+ 'above the live region (3 lines per burst at 20 Hz).',
+ 'frames': frameStats(
+ clock.between(start, end),
+ windowMicros: end - start,
+ ),
+ 'output': pump.window(start, end),
+ 'sessionTakeShare':
+ pump.takes
+ .where((t) => t.atWall >= start && t.atWall < end)
+ .fold<int>(0, (a, t) => a + t.micros) /
+ (end - start),
+ 'retainedPhysicalRows': _terminalA.session.terminal.buffer.lines.length,
+ };
+ } finally {
+ await pump.stop();
+ }
+ }
+
+ ScrollableState _terminalScrollable() {
+ final view = findElement((w) => w is TerminalView)!;
+ ScrollableState? found;
+ void visit(Element element) {
+ if (found != null) return;
+ if (element is StatefulElement && element.state is ScrollableState) {
+ found = element.state as ScrollableState;
+ return;
+ }
+ element.visitChildElements(visit);
+ }
+
+ view.visitChildElements(visit);
+ return found!;
+ }
+
+ Future<void> _scroll() async {
+ final pump = OutputPump(_terminalA, _outputs[_a]!, StreamLoad.redraw)
+ ..start();
+ try {
+ await Future<void>.delayed(const Duration(seconds: 1));
+ final scrollable = _terminalScrollable();
+ final position = scrollable.position;
+ final view = findElement((w) => w is TerminalView)!;
+ final box = view.renderObject! as RenderBox;
+ final origin = box.localToGlobal(Offset.zero);
+ final startPixels = position.pixels;
+ var minPixels = startPixels;
+ final start = wallMicros();
+ var flingsBack = 0;
+ var flingsForward = 0;
+ // Back through the scrollback: flicks the way a thumb reads upward — a
+ // flick every quarter second, each carrying the last one's momentum.
+ while (flingsBack < 30 &&
+ position.pixels > position.minScrollExtent + 1) {
+ final finger = touches.down(
+ origin + Offset(box.size.width / 2, box.size.height * 0.3),
+ );
+ await glide(finger, const Offset(0, 360), steps: 8);
+ finger.up();
+ flingsBack++;
+ await Future<void>.delayed(const Duration(milliseconds: 250));
+ if (position.pixels < minPixels) minPixels = position.pixels;
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 600));
+ if (position.pixels < minPixels) minPixels = position.pixels;
+ final reachedTop = position.pixels <= position.minScrollExtent + 1;
+ // Then a slow read forward: drags that follow the finger.
+ for (var i = 0; i < 6; i++) {
+ final finger = touches.down(
+ origin + Offset(box.size.width / 2, box.size.height * 0.7),
+ );
+ await glide(
+ finger,
+ const Offset(0, -300),
+ steps: 30,
+ interval: const Duration(milliseconds: 16),
+ );
+ await Future<void>.delayed(const Duration(milliseconds: 60));
+ finger.up();
+ await Future<void>.delayed(const Duration(milliseconds: 150));
+ }
+ // And back to the bottom, flicking.
+ while (flingsForward < 30 &&
+ position.pixels < position.maxScrollExtent - 1) {
+ final finger = touches.down(
+ origin + Offset(box.size.width / 2, box.size.height * 0.7),
+ );
+ await glide(finger, const Offset(0, -360), steps: 8);
+ finger.up();
+ flingsForward++;
+ await Future<void>.delayed(const Duration(milliseconds: 250));
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 800));
+ final end = wallMicros();
+ await pump.stop();
+ await clock.settleUntil(end);
+ scenarios['scroll_read'] = {
+ 'description':
+ 'Flicks back through the whole scrollback, six slow drags forward, '
+ 'and flicks back to the bottom, while the live region redraws at '
+ '20 Hz.',
+ 'frames': frameStats(
+ clock.between(start, end),
+ windowMicros: end - start,
+ ),
+ 'output': pump.window(start, end),
+ 'scroll': {
+ 'startPixels': startPixels,
+ 'minPixelsReached': minPixels,
+ 'distanceBackPx': startPixels - minPixels,
+ 'reachedTop': reachedTop,
+ 'flicksBack': flingsBack,
+ 'flicksForward': flingsForward,
+ 'endPixels': position.pixels,
+ 'maxScrollExtent': position.maxScrollExtent,
+ 'retainedPhysicalRows':
+ _terminalA.session.terminal.buffer.lines.length,
+ },
+ };
+ } finally {
+ await pump.stop();
+ }
+ // The scroll folded the header away, and only a scroll the other way
+ // brings it back. The next scenarios tap it, so they start from a fresh
+ // page — the same terminal, remounted at the bottom.
+ await tester.pumpWidget(const SizedBox.shrink());
+ await _settle(frames: 2);
+ await _mountFocus();
+ }
+
+ // ----------------------------------------------------------- interactions
+
+ /// Runs [sample] for the warmups and the measured observations, then joins
+ /// their frames to FrameTiming and summarizes.
+ Future<void> _series(
+ String name,
+ String load,
+ Future<_Observation> Function(bool measured) sample, {
+ String? description,
+ }) async {
+ final rows = <_Observation>[];
+ for (var i = -options.warmups; i < options.samples; i++) {
+ rows.add(await sample(i >= 0));
+ }
+ await clock.waitFor([
+ for (final row in rows) ...[
+ row.previousFrame,
+ row.firstFrame,
+ row.readyFrame,
+ ],
+ ]);
+ for (final row in rows) {
+ final readyBegan = row.extra['readyBeganWallMicros'] as int?;
+ row.derive(clock, readyBegan: readyBegan);
+ }
+ final measured = rows.where((r) => r.measured).toList();
+ Map<String, num> dist(String key) =>
+ distribution([for (final r in measured) r.derived[key]!]);
+ scenarios[name] = {
+ 'description': ?description,
+ 'operation': rows.first.operation,
+ 'load': load,
+ 'measured': measured.length,
+ 'warmups': rows.length - measured.length,
+ for (final key in [
+ 'firstRasterMicros',
+ 'readyRasterMicros',
+ 'dispatchMicros',
+ 'buildMicros',
+ 'rasterMicros',
+ 'waitForBuildMicros',
+ 'buildStartToRasterMicros',
+ 'dispatchAfterPreviousVsyncMicros',
+ 'previousBuildMicros',
+ ])
+ key.replaceAll('Micros', 'Ms'): dist(key),
+ 'framesToReady': distribution([
+ for (final r in measured) r.derived['framesToReady']! * 1000,
+ ]),
+ };
+ observations.addAll(rows.map((r) => r.toJson()));
+ }
+
+ Element _find(bool Function(Widget) matches, String what) =>
+ findElement(matches) ?? (throw StateError('No $what on screen'));
+
+ bool _overlayUp() => findElement((w) => w is TerminalSearchOverlay) != null;
+
+ Future<int> _untilOverlayOpen() => _untilFrame(() {
+ final overlay = findElement((w) => w is TerminalSearchOverlay);
+ return overlay != null &&
+ (overlay.widget as TerminalSearchOverlay).animation.status ==
+ AnimationStatus.completed;
+ }, what: 'Find to finish opening');
+
+ /// Opens Find the way a person does — a swipe right on the terminal — and waits for it.
+ Future<void> _openFindBySwipe() async {
+ final view = _find((w) => w is TerminalView, 'terminal');
+ final box = view.renderObject! as RenderBox;
+ final finger = touches.down(
+ box.localToGlobal(Offset(box.size.width * 0.2, box.size.height * 0.5)),
+ );
+ await nextFrame();
+ finger.moveBy(const Offset(30, 0));
+ await nextFrame();
+ finger.moveBy(const Offset(20, 0));
+ await glide(finger, const Offset(220, 0), steps: 11);
+ finger.up();
+ await _untilOverlayOpen();
+ }
+
+ Future<void> _closeFind() async {
+ final overlay = findElement((w) => w is TerminalSearchOverlay);
+ if (overlay == null) return;
+ (overlay.widget as TerminalSearchOverlay).onClose();
+ await _untilFrame(() => !_overlayUp(), what: 'Find to close');
+ await _settle(frames: 2, pause: const Duration(milliseconds: 120));
+ }
+
+ /// A tap: down, one frame, up — timed from the up, which is where a tap
+ /// fires. Answers (previous frame, began, dispatched).
+ Future<(int, int, int)> _tap(Offset point) async {
+ final finger = touches.down(point);
+ await nextFrame();
+ final previous = await nextFrame();
+ final began = finger.up();
+ return (previous, began, wallMicros());
+ }
+
+ Future<void> _findOpenSwipe() async {
+ final dragWindows = <(int, int)>[];
+ await _series(
+ 'find_open_swipe',
+ 'idle',
+ description:
+ 'Swipe right on the terminal: from the move that crosses touch slop '
+ 'to the first frame with Find built under the finger (first), and '
+ 'from the release to the frame its settle animation completes '
+ '(ready).',
+ (measured) async {
+ await _settle(frames: 2, pause: const Duration(milliseconds: 150));
+ final view = _find((w) => w is TerminalView, 'terminal');
+ final box = view.renderObject! as RenderBox;
+ final point = box.localToGlobal(
+ Offset(box.size.width * 0.2, box.size.height * 0.5),
+ );
+ final finger = touches.down(point);
+ await nextFrame();
+ // Past touch slop: the drag is accepted here, and with the default
+ // DragStartBehavior.start acceptance reports a start and NO update —
+ // it is the next move that reaches `_onSwipeUpdate` and opens Find.
+ finger.moveBy(const Offset(30, 0));
+ final previous = await nextFrame();
+ final began = finger.moveBy(const Offset(20, 0));
+ final dispatched = wallMicros();
+ final first = await _untilFrame(
+ _overlayUp,
+ what: 'Find under the finger',
+ );
+ await glide(finger, const Offset(220, 0), steps: 11);
+ final released = finger.up();
+ if (measured) dragWindows.add((began, released));
+ final ready = await _untilOverlayOpen();
+ await _closeFind();
+ return _Observation(
+ operation: 'find_open_swipe',
+ load: 'idle',
+ measured: measured,
+ began: began,
+ dispatched: dispatched,
+ previousFrame: previous,
+ firstFrame: first,
+ readyFrame: ready,
+ extra: {'readyBeganWallMicros': released},
+ );
+ },
+ );
+ final frames = [
+ for (final (start, end) in dragWindows) ...clock.between(start, end),
+ ];
+ final dragMicros = dragWindows.fold<int>(0, (a, w) => a + w.$2 - w.$1);
+ (scenarios['find_open_swipe']!
+ as Map<String, Object?>)['framesWhileDragging'] = frameStats(
+ frames,
+ windowMicros: dragMicros,
+ );
+ }
+
+ Element _mic() =>
+ _find((w) => w is VoiceMicButton && w.onPressed != null, 'live mic');
+
+ Future<void> _micTap({required bool idle}) async {
+ final pump = idle
+ ? null
+ : (OutputPump(_terminalA, _outputs[_a]!, StreamLoad.redraw)..start());
+ try {
+ if (pump != null) await Future<void>.delayed(const Duration(seconds: 1));
+ await _series(
+ idle ? 'mic_tap' : 'mic_tap_streaming',
+ idle ? 'idle' : 'redraw',
+ description:
+ 'Tap on the mic orb: first frame whose mic shows the listening face '
+ '(fake recorder, opens instantly). Ready = the same frame.',
+ (measured) async {
+ await _settle(frames: 2, pause: const Duration(milliseconds: 200));
+ final mic = _mic();
+ final (previous, began, dispatched) = await _tap(
+ touches.centerOf(mic),
+ );
+ bool listening() => findElements((w) => w is VoiceMicButton).any(
+ (e) => (e.widget as VoiceMicButton).face == VoiceMicFace.listening,
+ );
+ final first = await _untilFrame(listening, what: 'the mic to listen');
+ fixture.voice.clear();
+ await _untilFrame(() => !listening(), what: 'the mic to rest');
+ await _settle(frames: 2, pause: const Duration(milliseconds: 250));
+ return _Observation(
+ operation: 'mic_tap',
+ load: idle ? 'idle' : 'redraw',
+ measured: measured,
+ began: began,
+ dispatched: dispatched,
+ previousFrame: previous,
+ firstFrame: first,
+ readyFrame: first,
+ );
+ },
+ );
+ } finally {
+ await pump?.stop();
+ }
+ }
+
+ Future<void> _newOpenSwipe() async {
+ await _series(
+ 'new_open_swipe',
+ 'idle',
+ description:
+ 'Swipe left on the terminal (the release opens it): first frame with '
+ 'NewAgentPage built, and the frame its Cupertino push transition '
+ 'completes.',
+ (measured) async {
+ await _settle(frames: 2, pause: const Duration(milliseconds: 150));
+ final view = _find((w) => w is TerminalView, 'terminal');
+ final box = view.renderObject! as RenderBox;
+ final point = box.localToGlobal(
+ Offset(box.size.width * 0.8, box.size.height * 0.5),
+ );
+ final finger = touches.down(point);
+ await nextFrame();
+ finger.moveBy(const Offset(-30, 0));
+ await glide(finger, const Offset(-90, 0), steps: 5);
+ final previous = await nextFrame();
+ final began = finger.up();
+ final dispatched = wallMicros();
+ bool open() => findElement((w) => w is NewAgentPage) != null;
+ final first = await _untilFrame(open, what: 'the new-agent page');
+ final page = _find((w) => w is NewAgentPage, 'new-agent page');
+ final route = ModalRoute.of(page)!;
+ final ready = await _untilFrame(
+ () => route.animation!.isCompleted,
+ what: 'the new-agent push to finish',
+ );
+ Navigator.of(page).pop();
+ await _untilFrame(() => !open(), what: 'the new-agent page to go');
+ await _settle(frames: 2, pause: const Duration(milliseconds: 200));
+ return _Observation(
+ operation: 'new_open_swipe',
+ load: 'idle',
+ measured: measured,
+ began: began,
+ dispatched: dispatched,
+ previousFrame: previous,
+ firstFrame: first,
+ readyFrame: ready,
+ );
+ },
+ );
+ }
+
+ Future<void> _findSwitch() async {
+ await _series(
+ 'find_switch',
+ 'idle',
+ description:
+ 'With Find open on one agent, tap the other agent\'s row: first frame '
+ 'showing the other agent\'s TerminalPage with its terminal. Both '
+ 'terminals are attached and rendered beforehand; the switch is the '
+ 'shell\'s onOpenAgent rebuilding the home screen in place.',
+ (measured) async {
+ final from = _host.currentState!.agentId;
+ final to = from == _a ? _b : _a;
+ await _settle(frames: 2, pause: const Duration(milliseconds: 150));
+ await _openFindBySwipe();
+ await _settle(frames: 2, pause: const Duration(milliseconds: 150));
+ final row = _find(
+ (w) =>
+ w is FindRow &&
+ w.title == perfAgents.firstWhere((agent) => agent.$1 == to).$2,
+ 'row for $to',
+ );
+ final (previous, began, dispatched) = await _tap(touches.centerOf(row));
+ final target = fixture.terminals[to]!.session;
+ bool switched() =>
+ _host.currentState!.agentId == to &&
+ findElement(
+ (w) =>
+ w is TerminalView &&
+ identical(w.terminal, target.terminal),
+ ) !=
+ null;
+ final first = await _untilFrame(switched, what: 'the switch to $to');
+ await _settle(frames: 2, pause: const Duration(milliseconds: 200));
+ return _Observation(
+ operation: 'find_switch',
+ load: 'idle',
+ measured: measured,
+ began: began,
+ dispatched: dispatched,
+ previousFrame: previous,
+ firstFrame: first,
+ readyFrame: first,
+ extra: {'from': from, 'to': to},
+ );
+ },
+ );
+ if (_host.currentState?.agentId != _a) {
+ _host.currentState!.show(_a);
+ await _settle(frames: 3, pause: const Duration(milliseconds: 300));
+ }
+ }
+
+ // --------------------------------------------------------------- traces
+
+ Future<Map<String, Object?>> _traced(Future<void> Function() action) async {
+ debugProfileBuildsEnabled = true;
+ debugProfileLayoutsEnabled = true;
+ debugProfilePaintsEnabled = true;
+ try {
+ final timeline = await binding.traceTimeline(
+ action,
+ streams: const ['Dart', 'Embedder', 'GC'],
+ );
+ final events = [
+ for (final event in timeline.traceEvents ?? const [])
+ if (event.json != null) Map<String, dynamic>.from(event.json!),
+ ];
+ return summarizeTimeline(events);
+ } finally {
+ debugProfileBuildsEnabled = false;
+ debugProfileLayoutsEnabled = false;
+ debugProfilePaintsEnabled = false;
+ }
+ }
+
+ Future<void> _traceIdle() async {
+ await _settle(frames: 2, pause: const Duration(seconds: 1));
+ traces['idle'] = {
+ 'description':
+ '3 s of the idle page, per-widget events on: anything built or '
+ 'painted here is drawing with nothing to show.',
+ ...await _traced(() => Future<void>.delayed(const Duration(seconds: 3))),
+ };
+ }
+
+ Future<void> _traceStream(String name, StreamLoad load) async {
+ final pump = OutputPump(_terminalA, _outputs[_a]!, load)..start();
+ try {
+ await Future<void>.delayed(const Duration(seconds: 1));
+ traces[name] = {
+ 'description':
+ '3 s of $name with per-widget build, layout and paint events on '
+ '(which cost time themselves — these are rankings, not timings).',
+ ...await _traced(
+ () => Future<void>.delayed(const Duration(seconds: 3)),
+ ),
+ };
+ } finally {
+ await pump.stop();
+ }
+ }
+
+ Future<void> _traceFindOpen() async {
+ await _settle(frames: 2, pause: const Duration(milliseconds: 200));
+ traces['find_open_tap'] = {
+ 'description':
+ 'Five Find opens by tap and their closes, per-widget events on.',
+ ...await _traced(() async {
+ for (var i = 0; i < 5; i++) {
+ await _openFindBySwipe();
+ await _closeFind();
+ }
+ }),
+ };
+ }
+
+ // -------------------------------------------------------------- control
+
+ /// The same redraw load on the bare [TerminalPanel] — no header, no floating
+ /// mic glass, no page — so the page's own share of each frame can be read off
+ /// the difference from `stream_redraw`.
+ Future<void> _controlPanel() async {
+ await tester.pumpWidget(
+ perfApp(
+ Scaffold(
+ body: SafeArea(
+ bottom: false,
+ child: TerminalPanel(
+ notifier: fixture.notifier,
+ session: _terminalA.session,
+ focused: false,
+ showHeader: false,
+ ),
+ ),
+ ),
+ ),
+ );
+ await _settle(frames: 6, pause: const Duration(milliseconds: 500));
+ await _stream('control_panel_redraw', StreamLoad.redraw);
+ (scenarios['control_panel_redraw']!
+ as Map<String, Object?>)['description'] =
+ 'Control: stream_redraw\'s load on a bare TerminalPanel in a Scaffold '
+ '(no TerminalPage chrome: header, mic orb and its blur, swipe layer).';
+ await tester.pumpWidget(const SizedBox.shrink());
+ await _settle(frames: 2);
+ }
+}
diff --git a/mobile/integration_test/perf/stream.dart b/mobile/integration_test/perf/stream.dart
new file mode 100644
index 000000000..7927ff217
--- /dev/null
+++ b/mobile/integration_test/perf/stream.dart
@@ -0,0 +1,122 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'claude_output.dart';
+import 'fixture.dart';
+import 'frames.dart';
+
+/// Which output an agent is producing.
+enum StreamLoad {
+ /// Claude Code's live region (8 rows) erased and redrawn in place at 20 Hz —
+ /// the desktop benchmark's load, in Claude's shape.
+ redraw,
+
+ /// Three long prose lines appended per burst at 20 Hz (~60 lines/s, each
+ /// wrapping several times), with the live region redrawn under them.
+ append,
+}
+
+/// Feeds one terminal at 20 Hz, the desktop benchmark's producer: a periodic
+/// timer, and a burst that is still being taken in when the next is due is
+/// SKIPPED and counted rather than queued. Achieved bytes are what to read.
+///
+/// Every burst is generated and encoded before the pump starts, so the only
+/// work the timer adds to this thread is the app's own: the session taking the
+/// frame in.
+class OutputPump {
+ OutputPump(this.terminal, this.output, this.load, {int seconds = 30})
+ : _bursts = [
+ for (var tick = 0; tick < seconds * 20; tick++)
+ _encoded(
+ load == StreamLoad.redraw
+ ? output.redrawBurst(tick + 1)
+ : output.appendBurst(tick + 1),
+ ),
+ ];
+
+ static ({Uint8List bytes, bool compressed, int plain}) _encoded(String text) {
+ final body = FixtureTerminal.encode(text);
+ return (
+ bytes: body.bytes,
+ compressed: body.compressed,
+ plain: utf8.encode(text).length,
+ );
+ }
+
+ final FixtureTerminal terminal;
+ final ClaudeOutput output;
+ final StreamLoad load;
+ final List<({Uint8List bytes, bool compressed, int plain})> _bursts;
+
+ Timer? _timer;
+ bool _pending = false;
+ int _next = 0;
+
+ /// Encoded bytes handed to the session, as on the wire.
+ int wireBytes = 0;
+ int bursts = 0;
+ int skipped = 0;
+
+ /// Per burst: wall time it was handed over, how long the session took, and
+ /// its size on the wire and decoded.
+ final List<({int atWall, int micros, int wire, int plain})> takes = [];
+
+ void start() {
+ _timer = Timer.periodic(const Duration(milliseconds: 50), (_) async {
+ if (_pending) {
+ skipped++;
+ return;
+ }
+ _pending = true;
+ try {
+ final body = _bursts[_next++ % _bursts.length];
+ final at = wallMicros();
+ final micros = await terminal.output((
+ bytes: body.bytes,
+ compressed: body.compressed,
+ ));
+ takes.add((
+ atWall: at,
+ micros: micros,
+ wire: body.bytes.length,
+ plain: body.plain,
+ ));
+ wireBytes += body.bytes.length;
+ bursts++;
+ } finally {
+ _pending = false;
+ }
+ });
+ }
+
+ Future<void> stop() async {
+ _timer?.cancel();
+ _timer = null;
+ while (_pending) {
+ await Future<void>.delayed(Duration.zero);
+ }
+ }
+
+ /// What was produced in [startWall, endWall): bytes and the session's cost.
+ Map<String, Object?> window(int startWall, int endWall) {
+ final inside = [
+ for (final take in takes)
+ if (take.atWall >= startWall && take.atWall < endWall) take,
+ ];
+ final seconds = (endWall - startWall) / 1e6;
+ final plain = inside.fold<int>(0, (sum, t) => sum + t.plain);
+ final wire = inside.fold<int>(0, (sum, t) => sum + t.wire);
+ return {
+ 'load': load.name,
+ 'decodedBytesPerSecond': plain / seconds,
+ 'wireBytesPerSecond': wire / seconds,
+ 'meanDecodedBytesPerBurst': inside.isEmpty ? 0 : plain / inside.length,
+ 'burstsInWindow': inside.length,
+ 'skippedTotal': skipped,
+ 'burstsPerSecond': inside.length / seconds,
+ 'sessionTakeMs': distribution([for (final t in inside) t.micros]),
+ 'sessionTakeRawUs': [for (final t in inside) t.micros],
+ };
+ }
+}
diff --git a/mobile/integration_test/perf/timeline.dart b/mobile/integration_test/perf/timeline.dart
new file mode 100644
index 000000000..faed30ab0
--- /dev/null
+++ b/mobile/integration_test/perf/timeline.dart
@@ -0,0 +1,144 @@
+import 'dart:math' as math;
+
+/// Folds a VM timeline into its costliest events, by thread.
+///
+/// Complete (`X`) events carry their duration; begin/end (`B`/`E`) pairs are
+/// matched per thread with a stack. Each event is charged both INCLUSIVE time
+/// (all of it) and SELF time (minus the events nested inside it on the same
+/// thread) — with per-widget build and per-render-object layout/paint events on,
+/// a parent's inclusive time repeats all of its children's, so self time is the
+/// one that names where the work actually is.
+///
+/// The raw timeline stays on the phone: a few seconds of every stream runs to
+/// megabytes, and the ranking is what the report needs.
+Map<String, Object?> summarizeTimeline(
+ List<Map<String, dynamic>> events, {
+ int top = 40,
+}) {
+ final threadNames = <Object, String>{};
+ for (final event in events) {
+ if (event['ph'] == 'M' && event['name'] == 'thread_name') {
+ final args = event['args'];
+ if (args is Map && args['name'] != null) {
+ threadNames[event['tid'] as Object] = args['name'].toString();
+ }
+ }
+ }
+ String threadOf(Object? tid) {
+ final name = threadNames[tid] ?? '$tid';
+ if (name.contains('raster')) return 'raster';
+ if (name.contains('.ui') || name.endsWith('ui')) return 'ui';
+ if (name.contains('io.flutter.1.io')) return 'io';
+ if (name.contains('platform') || name.contains('main')) return 'platform';
+ return name;
+ }
+
+ final totals = <String, _Tally>{};
+ void charge(String thread, String name, int inclusive, int self) {
+ final key = '$thread · $name';
+ (totals[key] ??= _Tally(thread, name)).add(inclusive, self);
+ }
+
+ // Per thread: the open B events and, for each, the time its children used.
+ final open = <Object?, List<({String name, int ts, List<int> child})>>{};
+ // Complete events, to be nested by time after the pass.
+ final complete = <Object?, List<({String name, int ts, int dur})>>{};
+ // By time, and by position among equal times: List.sort is not stable, and a
+ // begin and an end stamped alike must keep their order.
+ final indexed =
+ [
+ for (final (index, event) in events.indexed)
+ if (event['ts'] is num) (index: index, event: event),
+ ]..sort((a, b) {
+ final byTime = (a.event['ts'] as num).compareTo(b.event['ts'] as num);
+ return byTime != 0 ? byTime : a.index.compareTo(b.index);
+ });
+ for (final (index: _, :event) in indexed) {
+ final ph = event['ph'];
+ final tid = event['tid'];
+ final ts = (event['ts'] as num?)?.toInt();
+ if (ts == null) continue;
+ final name = event['name']?.toString() ?? '?';
+ switch (ph) {
+ case 'X':
+ final dur = (event['dur'] as num?)?.toInt() ?? 0;
+ (complete[tid] ??= []).add((name: name, ts: ts, dur: dur));
+ case 'B':
+ (open[tid] ??= []).add((name: name, ts: ts, child: [0]));
+ case 'E':
+ final stack = open[tid];
+ if (stack == null || stack.isEmpty) continue;
+ final frame = stack.removeLast();
+ final dur = math.max(0, ts - frame.ts);
+ charge(
+ threadOf(tid),
+ frame.name,
+ dur,
+ math.max(0, dur - frame.child[0]),
+ );
+ if (stack.isNotEmpty) stack.last.child[0] += dur;
+ }
+ }
+ for (final MapEntry(key: tid, value: list) in complete.entries) {
+ list.sort(
+ (a, b) => a.ts != b.ts ? a.ts.compareTo(b.ts) : b.dur.compareTo(a.dur),
+ );
+ final stack = <({int end, List<int> child})>[];
+ final selfOf = List<int>.filled(list.length, 0);
+ final parents = <int>[];
+ for (var i = 0; i < list.length; i++) {
+ final e = list[i];
+ while (stack.isNotEmpty && e.ts >= stack.last.end) {
+ stack.removeLast();
+ parents.removeLast();
+ }
+ if (parents.isNotEmpty) selfOf[parents.last] -= e.dur;
+ selfOf[i] += e.dur;
+ stack.add((end: e.ts + e.dur, child: [0]));
+ parents.add(i);
+ }
+ for (var i = 0; i < list.length; i++) {
+ charge(threadOf(tid), list[i].name, list[i].dur, math.max(0, selfOf[i]));
+ }
+ }
+
+ List<Map<String, Object?>> rank(int Function(_Tally) by) {
+ final sorted = totals.values.toList()
+ ..sort((a, b) => by(b).compareTo(by(a)));
+ return [for (final tally in sorted.take(top)) tally.toJson()];
+ }
+
+ return {
+ 'events': events.length,
+ 'threads': threadNames.values.toSet().toList()..sort(),
+ 'bySelfTime': rank((t) => t.self),
+ 'byInclusiveTime': rank((t) => t.inclusive),
+ };
+}
+
+class _Tally {
+ _Tally(this.thread, this.name);
+
+ final String thread;
+ final String name;
+ int count = 0;
+ int inclusive = 0;
+ int self = 0;
+ int maxInclusive = 0;
+
+ void add(int inclusiveMicros, int selfMicros) {
+ count++;
+ inclusive += inclusiveMicros;
+ self += selfMicros;
+ maxInclusive = math.max(maxInclusive, inclusiveMicros);
+ }
+
+ Map<String, Object?> toJson() => {
+ 'thread': thread,
+ 'name': name,
+ 'count': count,
+ 'selfMs': self / 1000,
+ 'inclusiveMs': inclusive / 1000,
+ 'maxInclusiveMs': maxInclusive / 1000,
+ };
+}
diff --git a/mobile/integration_test/perf_test.dart b/mobile/integration_test/perf_test.dart
new file mode 100644
index 000000000..618b1b41a
--- /dev/null
+++ b/mobile/integration_test/perf_test.dart
@@ -0,0 +1,37 @@
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'perf/perf_binding.dart';
+import 'perf/scenarios.dart';
+
+/// The phone app's on-device performance benchmark.
+///
+/// Production widgets — `TerminalPage`, Find, the mic, the new-agent form —
+/// over a synthetic account whose terminals are fed Claude Code-shaped output
+/// through the production binary path, in a profile build on a real phone.
+/// Every frame is timed by the engine ([FrameTiming]); every interaction is
+/// timed from its framework dispatch to the raster finish of the first frame
+/// that shows its verified result.
+///
+/// Run it with `flutter drive` — see `integration_test/README.md`. Results go
+/// back to the host through the binding's `reportData`, and
+/// `test_driver/perf_driver.dart` writes them under `docs/performance/`.
+void main() {
+ final binding = PerfBinding()
+ ..framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive;
+ final options = PerfOptions.fromEnvironment();
+
+ testWidgets('phone performance baseline', (tester) async {
+ final suite = PerfSuite(tester, binding, options);
+ try {
+ await suite.run();
+ } finally {
+ // Unmounted first: the pages still listen to what is being disposed.
+ await tester.pumpWidget(const SizedBox.shrink());
+ suite.fixture.dispose();
+ }
+ if (suite.failures.isNotEmpty) {
+ fail('Scenarios failed: ${suite.failures.keys.join(', ')}');
+ }
+ }, timeout: const Timeout(Duration(minutes: 20)));
+}
diff --git a/mobile/integration_test/tour_test.dart b/mobile/integration_test/tour_test.dart
new file mode 100644
index 000000000..a3aa8c875
--- /dev/null
+++ b/mobile/integration_test/tour_test.dart
@@ -0,0 +1,161 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+
+import 'package:harness_mobile/main.dart' as app;
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+
+/// Every state of the phone app, in the real app on a simulator, over the offline sample — a
+/// screenshot each, for review. Signed out on a clean install, so nothing reaches a real account.
+///
+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \
+/// --target=integration_test/tour_test.dart
+void main() {
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('a tour of every screen', (tester) async {
+ var step = 0;
+ Future<void> shot(String name) async {
+ await tester.pump(const Duration(milliseconds: 300));
+ 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');
+ }
+
+ Future<bool> tapIf(Finder finder) async {
+ if (finder.evaluate().isEmpty) return false;
+ await tester.tap(finder.first);
+ return true;
+ }
+
+ Future<void> swipeRight() async {
+ await tester.dragFrom(const Offset(40, 450), const Offset(300, 0));
+ await wait(900);
+ }
+
+ Future<void> swipeLeft() async {
+ await tester.dragFrom(const Offset(350, 450), const Offset(-300, 0));
+ await wait(1000);
+ }
+
+ await app.main();
+ await waitFor(find.text('Is Harness on your computer?'));
+ // The sample, behind a long press on the wordmark: kept for these screenshots.
+ await tester.longPress(find.byKey(const ValueKey('welcome-wordmark')));
+ await wait(3000);
+ // It opens on the sessions to pick up, as a new phone does.
+ await shot('pick-up');
+ await tester.tap(find.text('fix-login', findRichText: true).first);
+ await wait(3000);
+ await shot('focus');
+
+ // Typing: only a tap on the prompt's rows, at the foot of the screen, raises the keyboard —
+ // left of the mic, which floats over them.
+ final screen = tester.view.physicalSize / tester.view.devicePixelRatio;
+ await tester.tapAt(Offset(30, screen.height - 60));
+ await wait(1200);
+ await shot('focus-keyboard');
+ await tapIf(find.byKey(const ValueKey('terminal-key-Hide keyboard')));
+ await wait(1000);
+
+ // Talking.
+ if (await tapIf(find.byType(VoiceMicCore))) {
+ await wait(1800);
+ await shot('focus-recording');
+ await tapIf(find.byType(VoiceMicCore));
+ await wait(3500);
+ await shot('focus-sent');
+ }
+
+ // Reading back.
+ await tester.dragFrom(const Offset(200, 300), const Offset(0, 400));
+ await wait(1000);
+ await shot('focus-reading-history');
+ await tester.dragFrom(const Offset(200, 500), const Offset(0, -2000));
+ await wait(1200);
+
+ // The menu.
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await wait(900);
+ await shot('menu');
+ await tester.tapAt(const Offset(200, 150));
+ await wait(700);
+
+ // Find, and each of its modes.
+ await swipeRight();
+ await shot('find');
+ final field = find.byType(TextField).first;
+ await tester.enterText(field, 'ap');
+ await wait(600);
+ await shot('find-typed');
+ await tester.enterText(field, '#');
+ await wait(600);
+ await shot('find-projects');
+ await tester.enterText(field, ':');
+ await wait(1500);
+ await shot('find-models');
+ await tester.enterText(field, '>');
+ await wait(600);
+ await shot('find-commands');
+ await tester.enterText(field, '');
+ await wait(400);
+ FocusManager.instance.primaryFocus?.unfocus();
+ await wait(600);
+
+ // The question.
+ if (await tapIf(find.text('refactor-db'))) {
+ await wait(2200);
+ await shot('focus-asking');
+ } else {
+ await tester.dragFrom(const Offset(350, 450), const Offset(-300, 0));
+ await wait(900);
+ }
+
+ // New.
+ await swipeLeft();
+ await shot('new');
+ if (await tapIf(find.text('options'))) {
+ await wait(600);
+ await shot('new-options');
+ }
+ if (await tapIf(find.text('project'))) {
+ await wait(900);
+ await shot('chooser-project');
+ await tester.tapAt(const Offset(200, 80));
+ await wait(700);
+ }
+ if (await tapIf(find.text('agent'))) {
+ await wait(900);
+ await shot('chooser-agent');
+ await tester.tapAt(const Offset(200, 80));
+ await wait(700);
+ }
+ await tester.dragFrom(const Offset(40, 450), const Offset(300, 0));
+ await wait(1000);
+
+ // Settings and Help, through the menu.
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await wait(900);
+ if (await tapIf(find.text('Settings'))) {
+ await wait(1200);
+ await shot('settings');
+ if (await tapIf(find.text('How Harness works'))) {
+ await wait(1000);
+ await shot('how-it-works');
+ }
+ }
+ });
+}
diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist
index bca31ae23..3ad1bbfdd 100644
--- a/mobile/ios/Runner/Info.plist
+++ b/mobile/ios/Runner/Info.plist
@@ -42,7 +42,7 @@
process and grants nothing, so NSPhotoLibraryUsageDescription would never
be shown and is deliberately absent. -->
<key>NSCameraUsageDescription</key>
- <string>Take a photo to send to an agent in a terminal.</string>
+ <string>Scan the code on your computer to connect, or take a photo to send to an agent.</string>
<!-- Voice input, what tapping a terminal opens. Asked for on the first tap,
not at launch. The microphone alone: the recording is transcribed by
the Harness backend (`/api/voice/stt`, the dial's own path), not by the
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dart
index 6099250eb..fcac59582 100644
--- a/mobile/lib/app_shell.dart
+++ b/mobile/lib/app_shell.dart
@@ -43,6 +43,14 @@ typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);
Future<void> startHarness({
required AuthenticatedScreenBuilder authenticatedScreen,
+ /// The signed-out screen, when the platform has its own — the phone's welcome. Null keeps
+ /// [LoginScreen].
+ AuthenticatedScreenBuilder? signedOutScreen,
+
+ /// The screen while the app starts, when the platform has its own. Null keeps
+ /// [BootstrappingScreen], which speaks of a window and a local service — the desktop's.
+ AuthenticatedScreenBuilder? bootScreen,
+
/// A viewer build's second wire to each machine (see
/// [TerminalTransportPlugin]); the desktop passes none.
TerminalTransportPluginFactory? transportPlugins,
@@ -75,6 +83,8 @@ Future<void> startHarness({
child: HarnessApp(
keymap: keymap,
authenticatedScreen: authenticatedScreen,
+ signedOutScreen: signedOutScreen,
+ bootScreen: bootScreen,
),
),
);
@@ -89,9 +99,17 @@ Future<void> startHarness({
}
class HarnessApp extends StatelessWidget {
- const HarnessApp({super.key, this.keymap, required this.authenticatedScreen});
+ const HarnessApp({
+ super.key,
+ this.keymap,
+ required this.authenticatedScreen,
+ this.signedOutScreen,
+ this.bootScreen,
+ });
final AppKeymap? keymap;
final AuthenticatedScreenBuilder authenticatedScreen;
+ final AuthenticatedScreenBuilder? signedOutScreen;
+ final AuthenticatedScreenBuilder? bootScreen;
@override
Widget build(BuildContext context) {
@@ -133,8 +151,12 @@ class HarnessApp extends StatelessWidget {
// one name, and telling them apart otherwise means reading `dumpsys` over
// a cable — by which point a bug has already been reported against the
// wrong build. Flutter draws it in DEBUG ONLY, so a release ships clean
- // without anyone having to remember to switch this back.
- debugShowCheckedModeBanner: true,
+ // without anyone having to remember to switch this back. Off only for a
+ // recording of the app (`--dart-define=HARNESS_RECORDING=true`), which a
+ // simulator can only make from a debug build.
+ debugShowCheckedModeBanner: !const bool.fromEnvironment(
+ 'HARNESS_RECORDING',
+ ),
// The design system's own `buildAppTheme` — see the note where a second,
// hand-written `ThemeData` used to shadow it, in `lib/theme/app_theme.dart`.
// Harness Desktop is dark-only: one theme, no `darkTheme`/`themeMode` to
@@ -173,7 +195,11 @@ class HarnessApp extends StatelessWidget {
),
),
home: AnalyticsLifecycle(
- child: RootShell(authenticatedScreen: authenticatedScreen),
+ child: RootShell(
+ authenticatedScreen: authenticatedScreen,
+ signedOutScreen: signedOutScreen,
+ bootScreen: bootScreen,
+ ),
),
);
}
@@ -208,9 +234,16 @@ class _GridTokenScope extends StatelessWidget {
const _appMenuChannel = MethodChannel('harness/app_menu');
class RootShell extends ConsumerStatefulWidget {
- const RootShell({super.key, required this.authenticatedScreen});
+ const RootShell({
+ super.key,
+ required this.authenticatedScreen,
+ this.signedOutScreen,
+ this.bootScreen,
+ });
final AuthenticatedScreenBuilder authenticatedScreen;
+ final AuthenticatedScreenBuilder? signedOutScreen;
+ final AuthenticatedScreenBuilder? bootScreen;
@override
ConsumerState<RootShell> createState() => _RootShellState();
@@ -285,6 +318,9 @@ class _RootShellState extends ConsumerState<RootShell>
}
}
+ Widget _signedOut(AppNotifier app) =>
+ widget.signedOutScreen?.call(app) ?? LoginScreen(notifier: app);
+
@override
Widget build(BuildContext context) {
final app = ref.watch(appStateProvider);
@@ -308,8 +344,9 @@ class _RootShellState extends ConsumerState<RootShell>
// the user's own screen away twice per sign-in: once on the click
// and again on success.
screen = app.signingIn
- ? LoginScreen(notifier: app)
- : BootstrappingScreen(statusMessage: app.bootStatusMessage);
+ ? _signedOut(app)
+ : widget.bootScreen?.call(app) ??
+ BootstrappingScreen(statusMessage: app.bootStatusMessage);
case AppStatus.checkingEnvironment:
screen = EnvironmentPreflightScreen(
readiness: app.environmentReadiness,
@@ -317,7 +354,7 @@ class _RootShellState extends ConsumerState<RootShell>
case AppStatus.preparingEnvironment:
screen = EnvironmentSetupScreen(notifier: app);
case AppStatus.unauthenticated:
- screen = LoginScreen(notifier: app);
+ screen = _signedOut(app);
case AppStatus.authenticated:
screen = widget.authenticatedScreen(app);
}
diff --git a/mobile/lib/auth/auth_session.dart b/mobile/lib/auth/auth_session.dart
index cddeaf184..bd15a0591 100644
--- a/mobile/lib/auth/auth_session.dart
+++ b/mobile/lib/auth/auth_session.dart
@@ -3,9 +3,10 @@ import '../core/local_key_value_store.dart';
/// Who issued a session — and therefore who renews it.
///
-/// Both hand out the SAME kind of token, an Autonomous account's access token
-/// (the Harness backend checks either against `apiv2`'s `/me` endpoints), but
-/// their refresh tokens only work where they came from.
+/// The first two hand out the SAME kind of token, an Autonomous account's
+/// access token (the Harness backend checks either against `apiv2`'s `/me`
+/// endpoints), but their refresh tokens only work where they came from. The
+/// third is Harness's own.
enum SessionIssuer {
/// The browser SSO flow, renewed through the Harness backend's `/api/auth/refresh`.
sso,
@@ -13,6 +14,12 @@ enum SessionIssuer {
/// A code emailed to the person, renewed through the Autonomous account API
/// itself — see `viewer/email_code_api.dart`.
emailCode,
+
+ /// The Harness backend itself, for a phone signed in by scanning a signed-in
+ /// computer's Add Phone QR (backend `lib/harnessSession.ts`). Renewed through
+ /// the backend's `/api/auth/refresh`, as [sso] is, and revoked there on sign
+ /// out.
+ harness,
}
/// Persists the SSO access + refresh tokens in the Desktop Harness state file.
@@ -91,10 +98,7 @@ class AuthSession {
/// failure several round-trips later rather than a refresh here.
Future<({String? token, DateTime? expiresAt})> accessTokenWithExpiry() async {
final saved = await _storage.readMany([_access, _expiresAt]);
- return (
- token: saved[_access],
- expiresAt: _expiryFrom(saved[_expiresAt]),
- );
+ return (token: saved[_access], expiresAt: _expiryFrom(saved[_expiresAt]));
}
static DateTime? _expiryFrom(String? raw) {
diff --git a/mobile/lib/auth/cli_link.dart b/mobile/lib/auth/cli_link.dart
index ec9986d5d..ec8e57c80 100644
--- a/mobile/lib/auth/cli_link.dart
+++ b/mobile/lib/auth/cli_link.dart
@@ -150,6 +150,17 @@ class CliLink implements PeerLinkClient {
/// `verifying`) as the handshake proceeds; best-effort UI feedback only, never required for
/// correctness. [displayName], when given, is how the CLI's error messages name the machine —
/// otherwise they show the raw [machineId], which is all a terminal user would have.
+ /// The desktop is the side that SHOWS the code; it never scans one.
+ @override
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ }) async => const CliLinkConnectResult(
+ error: 'Pairing by code is done from the phone.',
+ );
+
@override
Future<CliLinkConnectResult> connect(
String machineId,
diff --git a/mobile/lib/auth/link_errors.dart b/mobile/lib/auth/link_errors.dart
index 9b1080e91..bea48f57c 100644
--- a/mobile/lib/auth/link_errors.dart
+++ b/mobile/lib/auth/link_errors.dart
@@ -17,13 +17,14 @@ String humanizeLinkError(String code, String machineId, {DateTime? retryAt}) {
}
return switch (code) {
'NO_REMOTE_PASSWORD' =>
- 'Machine $machineId has no remote password set. Ask its operator to run '
- '`harness remote-password set` there first.',
+ '$machineId has no phone password yet. On it, run '
+ '`harness remote-password set`, then try again.',
'BAD_INTENT' =>
'The connection request was malformed — this usually means a version mismatch. '
'Update harness on both machines and try again.',
'WRONG_PASSWORD' =>
- 'That password is wrong. Check it against the other machine and try again.',
+ 'That password is wrong. It is the one set on $machineId with '
+ '`harness remote-password set`.',
'BUSY' =>
'Machine $machineId is already handling another link attempt. Wait a moment and try again.',
'TIMEOUT' =>
diff --git a/mobile/lib/auth/peer_link_client.dart b/mobile/lib/auth/peer_link_client.dart
index eb0976fa3..30b6d03ac 100644
--- a/mobile/lib/auth/peer_link_client.dart
+++ b/mobile/lib/auth/peer_link_client.dart
@@ -14,6 +14,16 @@ abstract interface class PeerLinkClient {
String? displayName,
});
+ /// Pairing by the one-time code a desktop app's "Add phone" QR carries (`viewer/code_link.dart`)
+ /// — no remote password. [label] is how the machine lists this device. A build that cannot says
+ /// so in the error.
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ });
+
Future<CliLinkListResult> list();
/// Null on success.
diff --git a/mobile/lib/core/first_task.dart b/mobile/lib/core/first_task.dart
new file mode 100644
index 000000000..4ff3e22f5
--- /dev/null
+++ b/mobile/lib/core/first_task.dart
@@ -0,0 +1,14 @@
+// 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 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`).
+const kFirstTaskEngines = {'claude', 'codex', 'opencode'};
+
+/// Whether a harness on [engine] can start on a first task.
+bool takesFirstTask(String engine) => kFirstTaskEngines.contains(engine);
+
+/// The longest first task a machine accepts, counted after trimming: the CLI's
+/// `MAX_FIRST_PROMPT_CHARS`. Longer is refused (`PROMPT_TOO_LONG`), never cut.
+const kFirstTaskMaxLength = 2000;
diff --git a/mobile/lib/core/fuzzy_match.dart b/mobile/lib/core/fuzzy_match.dart
index 1570f5e29..6dbc8cc57 100644
--- a/mobile/lib/core/fuzzy_match.dart
+++ b/mobile/lib/core/fuzzy_match.dart
@@ -1,5 +1,6 @@
/// The spread of a subsequence match, or null when the query does not match.
-/// Both arguments should already be normalized for case.
+/// Both arguments should already be normalized for case. [from] is where in
+/// [text] the match may begin.
///
/// Ported from the desktop's `core/fuzzy_match.dart` unchanged, so a query that
/// finds an agent there finds the same agent here. The two apps rank the same
@@ -8,10 +9,11 @@
int? subsequenceSpread(
String text,
String query, {
+ int from = 0,
void Function(int start, int end)? onMatch,
}) {
if (query.isEmpty) return 0;
- var at = -1;
+ var at = from - 1;
var first = -1;
for (final rune in query.runes) {
final character = String.fromCharCode(rune);
@@ -23,3 +25,134 @@ int? subsequenceSpread(
}
return at - first;
}
+
+final _wordCharacter = RegExp(r'[\p{L}\p{N}]', unicode: true);
+
+/// Whether [index] begins a word: the start of [text], or just after a
+/// character that is neither a letter nor a digit, as in "fix-auth".
+bool startsWord(String text, int index) {
+ if (index <= 0) return true;
+ final unit = text.codeUnitAt(index - 1);
+ if (unit < 0x80) {
+ return !(unit >= 0x30 && unit <= 0x39 ||
+ unit >= 0x41 && unit <= 0x5a ||
+ unit >= 0x61 && unit <= 0x7a);
+ }
+ // Separators every row carries ("·", "…", "—", no-break space) and emoji
+ // halves, without a regex per character.
+ if (unit == 0xa0 ||
+ unit == 0xb7 ||
+ unit >= 0x2000 && unit <= 0x206f ||
+ unit >= 0xd800 && unit <= 0xdfff) {
+ return true;
+ }
+ return !_wordCharacter.hasMatch(text[index - 1]);
+}
+
+/// The first occurrence of [term] at or after [start] that begins a word, or
+/// -1: "port" is a word in "windows port" and only a fragment of "support".
+int wordStartIndexOf(String text, String term, [int start = 0]) {
+ if (term.isEmpty) return start.clamp(0, text.length);
+ for (
+ var at = text.indexOf(term, start);
+ at >= 0;
+ at = text.indexOf(term, at + 1)
+ ) {
+ if (startsWord(text, at)) return at;
+ }
+ return -1;
+}
+
+/// A scattered-letter match that starts on a word and stays close together:
+/// "ath" finds "fix authentication" and "cmd" finds "command", but "auth" no
+/// longer finds every folder under ".../autonomous-harness/...". Returns the
+/// tightest such spread, or null; [onMatch] receives the letters it used.
+int? wordSubsequenceSpread(
+ String text,
+ String query, {
+ void Function(int start, int end)? onMatch,
+}) {
+ if (query.isEmpty) return 0;
+ final letters = _lettersOf(query);
+ // Two scattered letters match nearly everything ("hn" in every "harness"):
+ // they count only as initials, each starting a word ("ns" for New Split).
+ if (letters.length < 3) return _initials(text, letters, onMatch: onMatch);
+ final first = letters.first;
+ final limit = query.length * 2;
+ int? bestStart, bestSpread;
+ for (
+ var at = text.indexOf(first);
+ at >= 0;
+ at = text.indexOf(first, at + first.length)
+ ) {
+ if (!startsWord(text, at)) continue;
+ final spread = _spreadWithin(text, letters, at, limit);
+ // A later start sees less of the text, so it cannot match either.
+ if (spread == _absent) break;
+ if (spread != null && (bestSpread == null || spread < bestSpread)) {
+ bestStart = at;
+ bestSpread = spread;
+ if (spread == query.length - 1) break;
+ }
+ }
+ if (bestStart != null && onMatch != null) {
+ subsequenceSpread(text, query, from: bestStart, onMatch: onMatch);
+ }
+ return bestSpread;
+}
+
+/// No subsequence at all from here on.
+const _absent = -1;
+
+/// The spread of [query] as a subsequence of [text] starting at [start],
+/// giving up as soon as it passes [limit] (null) rather than scanning on to the
+/// end of a long field; [_absent] when a letter never occurs again.
+int? _spreadWithin(String text, List<String> letters, int start, int limit) {
+ var at = start;
+ for (var index = 1; index < letters.length; index++) {
+ final found = text.indexOf(letters[index], at + 1);
+ if (found < 0) return _absent;
+ if (found - start > limit) return null;
+ at = found;
+ }
+ return at - start;
+}
+
+/// A query's letters, as strings: worked out once per query, not once per
+/// field of every row it is matched against.
+List<String> _lettersOf(String query) {
+ if (identical(query, _lettersQuery) || query == _lettersQuery) {
+ return _letters;
+ }
+ _lettersQuery = query;
+ return _letters = [for (final rune in query.runes) String.fromCharCode(rune)];
+}
+
+String? _lettersQuery;
+List<String> _letters = const [];
+
+int? _initials(
+ String text,
+ List<String> letters, {
+ void Function(int start, int end)? onMatch,
+}) {
+ var at = -1;
+ var first = -1;
+ final found = <(int, int)>[];
+ for (final character in letters) {
+ var next = text.indexOf(character, at + 1);
+ while (next >= 0 && !startsWord(text, next)) {
+ next = text.indexOf(character, next + 1);
+ }
+ if (next < 0) return null;
+ if (first < 0) first = next;
+ at = next;
+ found.add((next, next + character.length));
+ }
+ if (onMatch != null) {
+ for (final (start, end) in found) {
+ onMatch(start, end);
+ }
+ }
+ return at - first;
+}
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index 93acb3b3d..69e207111 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -143,10 +143,28 @@ class Agent {
/// so it is what tells two such agents apart on a phone.
final String? title;
- /// When the conversation was last written — the transcript's mtime, which the
- /// daemon prefers over its own bookkeeping precisely so a client sorting by
- /// recency follows the work. Null from a daemon too old to send it.
+ /// When the conversation was last active — the latest dated record in its
+ /// transcript, which the daemon prefers over its own bookkeeping precisely so
+ /// a client sorting by recency follows the work. Null from a daemon too old
+ /// to send it.
final DateTime? updatedAt;
+
+ /// When any app last opened this agent — the phone, a desktop window, on any
+ /// computer. Stamped by the daemon that owns the agent when an app says so
+ /// (`agent_update {opened: true}`), so every app reads the same moment. Null
+ /// when nobody has, or from a daemon too old to keep it.
+ final DateTime? lastOpenedAt;
+
+ /// What every list of agents sorts by: the later of the last activity and the
+ /// last time an app opened it — one order, the same on the phone and on every
+ /// desktop.
+ DateTime? get lastUsedAt {
+ final activity = updatedAt, opened = lastOpenedAt;
+ if (activity == null) return opened;
+ if (opened == null) return activity;
+ return opened.isAfter(activity) ? opened : activity;
+ }
+
final String? engine;
final String? engineDisplayName;
final String? engineIconHint;
@@ -198,6 +216,7 @@ class Agent {
required this.name,
this.title,
this.updatedAt,
+ this.lastOpenedAt,
this.engine,
this.engineDisplayName,
this.engineIconHint,
@@ -255,6 +274,7 @@ class Agent {
name: j['name'] as String? ?? 'agent',
title: _safeLabel(j['title']),
updatedAt: _safeTime(j['updatedAt']),
+ lastOpenedAt: _safeTime(j['lastOpenedAt']),
engine: _safeEngine(j['engine']),
engineDisplayName: _safeLabel(j['engineDisplayName']),
engineIconHint: _safeLabel(j['engineIconHint']),
@@ -293,6 +313,7 @@ class Agent {
name: name ?? this.name,
title: title,
updatedAt: updatedAt,
+ lastOpenedAt: lastOpenedAt,
engine: engine,
engineDisplayName: engineDisplayName,
engineIconHint: engineIconHint,
diff --git a/mobile/lib/demo/main_sample.dart b/mobile/lib/demo/main_sample.dart
new file mode 100644
index 000000000..a48f10164
--- /dev/null
+++ b/mobile/lib/demo/main_sample.dart
@@ -0,0 +1,75 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/core/startup.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
+
+import 'sample_mode.dart';
+
+/// The phone app in sample mode and nothing else — no sign-in under it, no account, no network:
+///
+/// flutter run -t lib/demo/main_sample.dart
+///
+/// For walking the app the way somebody new to it would, on a phone or a simulator, without a
+/// machine to link. The saved appearance and terminal settings are read (never written), so the
+/// sample looks like the app it stands in for.
+Future<void> main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+ await loadPersistedSettings();
+ runApp(const SampleApp());
+}
+
+class SampleApp extends StatelessWidget {
+ const SampleApp({super.key});
+
+ @override
+ Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
+ valueListenable: appearancePrefsStore,
+ builder: (context, prefs, _) {
+ // What `HarnessApp` does before it builds its theme: the palette and the type settings go
+ // on first, because the theme bakes them in.
+ grid.AppTheme.palette.value = prefs.palette;
+ grid.AppTheme.fonts.apply(
+ uiFamily: prefs.uiFamily,
+ uiScale: prefs.uiSize / grid.AppFont.uiSizeDefault,
+ codeSize: grid.AppFont.codeSize,
+ );
+ grid.AppTheme.brightness.value = Brightness.dark;
+ return MaterialApp(
+ title: 'Harness sample',
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) =>
+ grid.BrightnessScope(child: child ?? const SizedBox.shrink()),
+ home: const _Launcher(),
+ );
+ },
+ );
+}
+
+/// Opens the sample as the app starts, and again from its button after it is left.
+class _Launcher extends StatefulWidget {
+ const _Launcher();
+
+ @override
+ State<_Launcher> createState() => _LauncherState();
+}
+
+class _LauncherState extends State<_Launcher> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) openSampleMode(context);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) => Scaffold(
+ body: Center(
+ child: TextButton(
+ onPressed: () => openSampleMode(context),
+ child: const Text('Open the sample'),
+ ),
+ ),
+ );
+}
diff --git a/mobile/lib/demo/sample_harness.dart b/mobile/lib/demo/sample_harness.dart
new file mode 100644
index 000000000..22f5b665e
--- /dev/null
+++ b/mobile/lib/demo/sample_harness.dart
@@ -0,0 +1,409 @@
+import 'dart:async';
+import 'dart:collection';
+
+import 'sample_screen.dart';
+
+/// One beat of a script: something the harness does, [delay] after the beat before it.
+sealed class SampleStep {
+ const SampleStep(this.delay);
+ final Duration delay;
+}
+
+/// A transcript item appears.
+class EmitStep extends SampleStep {
+ const EmitStep(this.entry, super.delay);
+ final SampleEntry entry;
+}
+
+/// The spinner changes its word.
+class VerbStep extends SampleStep {
+ const VerbStep(this.verb, super.delay);
+ final String verb;
+}
+
+/// The agent stops to ask. [then] is what it does with the answer — the row's index, from 0.
+class AskStep extends SampleStep {
+ const AskStep(this.ask, this.then, super.delay);
+ final SampleAsk ask;
+ final List<SampleStep> Function(int answer) then;
+}
+
+/// The turn ends, having said [reply].
+class DoneStep extends SampleStep {
+ const DoneStep(this.reply, super.delay);
+ final String reply;
+}
+
+/// Work that never ends: the next stretch of it, asked for each time the last one runs out.
+abstract interface class SampleLoop {
+ List<SampleStep> next();
+}
+
+/// What a harness needs from the sample around it: a clock, and somewhere to report to.
+///
+/// Every timer comes from here, so the sample can cancel all of them at once when it is left —
+/// a harness never owns a timer the host does not know about.
+abstract interface class SampleHarnessHost {
+ Timer schedule(Duration delay, void Function() run);
+ Timer every(Duration period, void Function() run);
+
+ /// The transcript grew by [entries].
+ void appended(SampleHarness harness, List<SampleEntry> entries);
+
+ /// The live region changed — typing, the spinner, a dialog opening or closing.
+ void liveChanged(SampleHarness harness);
+
+ void workingChanged(SampleHarness harness, bool working);
+ void askChanged(SampleHarness harness, SampleAsk? ask);
+ void turnEnded(SampleHarness harness, String? reply);
+
+ /// What the harness answers when somebody asks it for [text].
+ List<SampleStep> replyTo(SampleHarness harness, String text);
+}
+
+/// One sample harness: a CLI's screen, driven by a script instead of a model.
+///
+/// It keeps what a real one would have on screen — a transcript and a live region — and moves
+/// them the way Claude Code or Codex would: a turn is a queue of [SampleStep]s played out on the
+/// host's clock, the spinner turns while it works, a permission question stops the queue until it
+/// is answered, and what is typed at it goes into its prompt box and comes back as a reply.
+class SampleHarness {
+ SampleHarness({
+ required this.machineId,
+ required this.agent,
+ required this.host,
+ List<SampleEntry> transcript = const [],
+ this.loop,
+ }) : transcript = [...transcript],
+ look = SampleLook.of(agent['engine'] as String? ?? 'claude');
+
+ final String machineId;
+
+ /// The agent as a machine describes it — what `agents_list` answers with. Edited in place by a
+ /// rename, a use, a turn.
+ final Map<String, dynamic> agent;
+ final SampleHarnessHost host;
+ final SampleLook look;
+ final List<SampleEntry> transcript;
+ final LiveState live = LiveState();
+
+ /// Endless work, for the harness that is always busy. Dropped by an interrupt.
+ SampleLoop? loop;
+
+ /// What the person asked lately and what the turns said, newest first — the machine's
+ /// `agent_recent`, which Find quotes.
+ final List<String> asks = [];
+ final List<String> replies = [];
+
+ String get agentId => agent['id'] as String;
+ String get engine => look.engine;
+ String get cwd => (agent['project'] as Map?)?['cwd'] as String? ?? '~/code';
+
+ /// The oldest items drop off past this — the pane keeps them in its own scrollback, and a
+ /// keyframe does not need a day of history to look like a session.
+ static const maxEntries = 120;
+
+ final Queue<SampleStep> _queue = Queue();
+ Timer? _next;
+ Timer? _spin;
+ List<SampleStep> Function(int answer)? _onAnswer;
+ final List<String> _waiting = [];
+ bool _disposed = false;
+
+ bool get working => live.mode == LiveMode.working;
+ bool get asking => live.mode == LiveMode.asking;
+
+ // ── turns ──────────────────────────────────────────────────────────────────────────────────
+
+ /// Starts it where its script says it is: working through [steps], or asking [ask].
+ void begin({
+ List<SampleStep> steps = const [],
+ String verb = 'Thinking',
+ SampleAsk? ask,
+ List<SampleStep> Function(int answer)? then,
+ }) {
+ if (ask != null) {
+ live
+ ..mode = LiveMode.asking
+ ..ask = ask
+ ..selected = 0;
+ _onAnswer = then;
+ host.askChanged(this, ask);
+ return;
+ }
+ if (steps.isEmpty && loop == null) return;
+ _queue.addAll(steps);
+ _beginWork(verb);
+ _pump();
+ }
+
+ /// Something to do: typed and returned, voiced, or sent as a message. It is echoed into the
+ /// transcript and answered — straight away, or after the step already under way.
+ void submit(String text) {
+ final said = text.trim();
+ if (said.isEmpty || _disposed) return;
+ if (asking) {
+ // A dialog is on screen, and a message is not an answer to it: it waits for the dialog.
+ _waiting.add(said);
+ return;
+ }
+ live.input = '';
+ asks.insert(0, said);
+ if (asks.length > 3) asks.removeLast();
+ agent['title'] ??= said.length <= 60 ? said : '${said.substring(0, 59)}…';
+ _append(UserEntry(said));
+ final steps = host.replyTo(this, said);
+ // Ahead of whatever the loop has queued: a person asking is what happens next.
+ for (final step in steps.reversed) {
+ _queue.addFirst(step);
+ }
+ _beginWork('Thinking');
+ _pump();
+ }
+
+ /// A row of the open question, from 0.
+ void answer(int index) {
+ final ask = live.ask;
+ if (!asking || ask == null || index < 0 || index >= ask.options.length) {
+ return;
+ }
+ final then = _onAnswer;
+ _onAnswer = null;
+ live
+ ..ask = null
+ ..selected = 0
+ ..mode = LiveMode.idle;
+ host.askChanged(this, null);
+ final steps = then?.call(index) ?? const <SampleStep>[];
+ for (final step in steps.reversed) {
+ _queue.addFirst(step);
+ }
+ _beginWork('Thinking');
+ host.liveChanged(this);
+ _pump();
+ }
+
+ /// Esc: a dialog is declined, a turn is stopped.
+ void interrupt() {
+ if (asking) {
+ answer((live.ask?.options.length ?? 1) - 1);
+ return;
+ }
+ if (!working) return;
+ _next?.cancel();
+ _next = null;
+ _queue.clear();
+ loop = null;
+ _append(
+ NoteEntry(
+ engine == 'codex'
+ ? 'Conversation interrupted - tell the model what to do differently'
+ : 'Interrupted by user',
+ ),
+ );
+ _finish(null);
+ }
+
+ /// Everything still to do goes, the endless work included — for a reply that stops it.
+ void dropQueuedWork() {
+ _next?.cancel();
+ _next = null;
+ _queue.clear();
+ loop = null;
+ }
+
+ /// A restart: the engine comes back up in the same pane, as a fresh process would.
+ void restart() {
+ _next?.cancel();
+ _next = null;
+ _queue.clear();
+ if (working) _finish(null);
+ _append(BannerEntry(cwd));
+ }
+
+ // ── keys ───────────────────────────────────────────────────────────────────────────────────
+
+ /// Keystrokes from the pane, as a terminal would deliver them.
+ void keys(String data) {
+ if (_disposed) return;
+ var i = 0;
+ var typed = false;
+ while (i < data.length) {
+ final char = data[i];
+ if (data.startsWith('\x1b[200~', i)) {
+ // A bracketed paste: everything up to its close is text.
+ final end = data.indexOf('\x1b[201~', i + 6);
+ final text = data.substring(i + 6, end < 0 ? data.length : end);
+ if (!asking) {
+ live.input += text.replaceAll(RegExp(r'[\r\n]+'), ' ');
+ typed = true;
+ }
+ i = end < 0 ? data.length : end + 6;
+ continue;
+ }
+ if (char == '\x1b') {
+ final sequence = RegExp(r'^\x1b(\[[0-9;?]*[@-~]|O[@-~])')
+ .matchAsPrefix(data, i);
+ if (sequence == null) {
+ interrupt();
+ i++;
+ continue;
+ }
+ final code = sequence.group(1)!;
+ final key = code.substring(code.length - 1);
+ if (asking && (key == 'A' || key == 'B')) {
+ final count = live.ask!.options.length;
+ live.selected =
+ (live.selected + (key == 'A' ? -1 : 1) + count) % count;
+ host.liveChanged(this);
+ }
+ i += sequence.group(0)!.length;
+ continue;
+ }
+ if (char == '\r' || char == '\n') {
+ if (asking) {
+ answer(live.selected);
+ } else {
+ final text = live.input;
+ live.input = '';
+ if (text.trim().isEmpty) {
+ typed = true;
+ } else {
+ submit(text);
+ }
+ }
+ i++;
+ continue;
+ }
+ if (asking) {
+ final number = int.tryParse(char);
+ if (number != null) answer(number - 1);
+ i++;
+ continue;
+ }
+ switch (char) {
+ case '\x7f' || '\x08':
+ if (live.input.isNotEmpty) {
+ final runes = live.input.runes.toList()..removeLast();
+ live.input = String.fromCharCodes(runes);
+ typed = true;
+ }
+ case '\x15' || '\x03':
+ // Ctrl+U, and Ctrl+C on a prompt: the line goes.
+ if (live.input.isNotEmpty) {
+ live.input = '';
+ typed = true;
+ }
+ case '\t' || '\x05' || '\x01':
+ break;
+ default:
+ if (char.codeUnitAt(0) >= 0x20) {
+ live.input += char;
+ typed = true;
+ }
+ }
+ i++;
+ }
+ if (typed) host.liveChanged(this);
+ }
+
+ // ── the queue ──────────────────────────────────────────────────────────────────────────────
+
+ void _pump() {
+ if (_disposed || _next != null || asking) return;
+ if (_queue.isEmpty) {
+ final more = loop?.next();
+ if (more == null || more.isEmpty) {
+ if (working) _finish(null);
+ return;
+ }
+ _queue.addAll(more);
+ }
+ final step = _queue.removeFirst();
+ _next = host.schedule(step.delay, () {
+ _next = null;
+ _run(step);
+ _pump();
+ });
+ }
+
+ void _run(SampleStep step) {
+ switch (step) {
+ case EmitStep(:final entry):
+ live.tokens += 180 + transcript.length * 7 % 240;
+ _append(entry);
+ case VerbStep(:final verb):
+ live.verb = verb;
+ host.liveChanged(this);
+ case AskStep(:final ask, :final then):
+ _stopSpin();
+ final wasWorking = working;
+ live
+ ..mode = LiveMode.asking
+ ..ask = ask
+ ..selected = 0;
+ _onAnswer = then;
+ if (wasWorking) host.workingChanged(this, false);
+ host.askChanged(this, ask);
+ host.liveChanged(this);
+ case DoneStep(:final reply):
+ replies.insert(0, reply);
+ if (replies.length > 3) replies.removeLast();
+ // A harness that is always busy keeps going; a turn that is done is done.
+ if (loop == null) _finish(reply);
+ }
+ }
+
+ void _append(SampleEntry entry) {
+ transcript.add(entry);
+ if (transcript.length > maxEntries) {
+ transcript.removeRange(0, transcript.length - maxEntries);
+ }
+ host.appended(this, [entry]);
+ }
+
+ void _beginWork(String verb) {
+ live.verb = verb;
+ if (working) {
+ host.liveChanged(this);
+ return;
+ }
+ live
+ ..mode = LiveMode.working
+ ..ticks = 0
+ ..tokens = 0;
+ _spin ??= host.every(sampleSpinnerTick, () {
+ live
+ ..ticks += 1
+ ..tokens += 37;
+ host.liveChanged(this);
+ });
+ host.workingChanged(this, true);
+ host.liveChanged(this);
+ }
+
+ void _finish(String? reply) {
+ _stopSpin();
+ if (!working) return;
+ live.mode = LiveMode.idle;
+ agent['updatedAt'] = DateTime.now().toUtc().toIso8601String();
+ host.workingChanged(this, false);
+ host.turnEnded(this, reply);
+ host.liveChanged(this);
+ // What was said while a dialog was up, now that it is gone.
+ if (_waiting.isNotEmpty) submit(_waiting.removeAt(0));
+ }
+
+ void _stopSpin() {
+ _spin?.cancel();
+ _spin = null;
+ }
+
+ void dispose() {
+ _disposed = true;
+ _next?.cancel();
+ _next = null;
+ _stopSpin();
+ _queue.clear();
+ }
+}
diff --git a/mobile/lib/demo/sample_mode.dart b/mobile/lib/demo/sample_mode.dart
new file mode 100644
index 000000000..3003b7576
--- /dev/null
+++ b/mobile/lib/demo/sample_mode.dart
@@ -0,0 +1,161 @@
+/// Sample mode: the phone app, whole, over mock computers and harnesses — no account, no
+/// network, nothing written anywhere the real app reads.
+///
+/// It is how someone tries Harness before they have a machine to link, and how we walk the app
+/// as a first-time user: two computers, five harnesses in every state a harness can be in — one
+/// working, one finished, one asking a question, two idle — each answering what it is told in a
+/// few scripted lines, and New making more.
+///
+/// ```dart
+/// TextButton(
+/// onPressed: () => openSampleMode(context),
+/// child: const Text('Try a sample'),
+/// )
+/// ```
+///
+/// What keeps it apart from the real app:
+///
+/// - its own [AppNotifier] ([SampleNotifier]), whose machines are in-process
+/// ([SampleConnection]) and whose REST client answers everything itself ([SampleApiClient]);
+/// - no `paneLayoutStore`, so every store the notifier keeps — last agent, project history,
+/// search history, machine cache — remembers for this visit only, and its notices stay out of
+/// the notification centre;
+/// - its session, device keys and counters in memory ([SampleMemoryStore]);
+/// - a microphone that records nothing ([SampleVoiceRecorder]);
+/// - the New form's draft, which is a global, put back as it was when the sample is left.
+library;
+
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/phone/new_agent_draft.dart';
+import 'package:harness_mobile/phone/phone_shell.dart';
+import 'package:harness_mobile/phone/voice_input_scope.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'sample_runtime.dart';
+
+export 'sample_runtime.dart' show SampleConnection, SampleRuntime;
+
+/// Opens sample mode over whatever is on screen, and completes when it is left.
+///
+/// A route of its own on the root navigator, so it is independent of the app under it — signed
+/// out or signed in — and leaving it (Settings → Leave sample, or the system back at its root)
+/// takes all of it away: the harnesses, their timers and its app state.
+/// Opens the sample. Completes when it is left — with [SampleExit.setUp] when it was left to set up
+/// a real computer (the end card's green button), so the caller can go there next.
+Future<String?> openSampleMode(BuildContext context) =>
+ Navigator.of(context, rootNavigator: true).push<String>(
+ MaterialPageRoute<String>(
+ // Full screen, and no edge swipe to leave by: a swipe right on a terminal is Find.
+ fullscreenDialog: true,
+ builder: (_) => const SampleModeScreen(),
+ ),
+ );
+
+/// What a screen inside sample mode can ask of it.
+/// How the sample was left.
+abstract final class SampleExit {
+ /// To set up a real computer.
+ static const setUp = 'set-up';
+}
+
+abstract interface class SampleSession {
+ /// Leaves the sample: back to whatever it was opened over, with everything it ran disposed.
+ /// [result] is what [openSampleMode] completes with — see [SampleExit].
+ void leave([String? result]);
+
+ /// The sample's app state.
+ AppNotifier get notifier;
+
+ /// Whether the end card ("That's Harness") has been shown this visit — it comes once.
+ bool get endCardSeen;
+ set endCardSeen(bool value);
+}
+
+/// Marks everything under it as sample mode — see [maybeOf].
+class SampleMode extends InheritedWidget {
+ const SampleMode({super.key, required this.session, required super.child});
+
+ final SampleSession session;
+
+ /// The sample [context] is in, or null in the real app.
+ ///
+ /// A screen pushed on the ROOT navigator is outside this widget — a sheet, a chooser — and can
+ /// ask [ofNotifier] with the notifier it was handed instead.
+ static SampleSession? maybeOf(BuildContext context) =>
+ context.getInheritedWidgetOfExactType<SampleMode>()?.session;
+
+ /// The sample [notifier] belongs to, or null when it is the real app's.
+ static SampleSession? ofNotifier(AppNotifier notifier) => _open[notifier];
+
+ static final Expando<SampleSession> _open = Expando('sample mode');
+
+ @override
+ bool updateShouldNotify(SampleMode oldWidget) => oldWidget.session != session;
+}
+
+/// Sample mode's screen: the phone shell over [SampleRuntime].
+class SampleModeScreen extends StatefulWidget {
+ const SampleModeScreen({super.key, this.runtime});
+
+ /// The sample to show; a fresh one when null. Disposed with the screen either way.
+ final SampleRuntime? runtime;
+
+ @override
+ State<SampleModeScreen> createState() => _SampleModeScreenState();
+}
+
+class _SampleModeScreenState extends State<SampleModeScreen>
+ implements SampleSession {
+ late final SampleRuntime _runtime = widget.runtime ?? SampleRuntime();
+
+ /// The real app's New form, as it was — see [newAgentDraft]. The sample's form must neither
+ /// open on it nor leave its own behind.
+ NewAgentDraft? _realDraft;
+
+ bool _leaving = false;
+
+ @override
+ bool endCardSeen = false;
+
+ @override
+ AppNotifier get notifier => _runtime.notifier;
+
+ @override
+ void initState() {
+ super.initState();
+ _realDraft = newAgentDraft;
+ newAgentDraft = null;
+ SampleMode._open[_runtime.notifier] = this;
+ }
+
+ @override
+ void leave([String? result]) {
+ if (_leaving || !mounted) return;
+ final route = ModalRoute.of(context);
+ final navigator = route?.navigator;
+ if (route == null || navigator == null) return;
+ _leaving = true;
+ // Anything the sample put over itself on the root navigator — a sheet, a chooser — goes
+ // first, then the sample.
+ navigator.popUntil((candidate) => candidate == route);
+ navigator.pop(result);
+ }
+
+ @override
+ void dispose() {
+ SampleMode._open[_runtime.notifier] = null;
+ _runtime.dispose();
+ newAgentDraft = _realDraft;
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => SampleMode(
+ session: this,
+ child: VoiceInputScope(
+ create: _runtime.voiceController,
+ child: PhoneShell(notifier: _runtime.notifier),
+ ),
+ );
+}
diff --git a/mobile/lib/demo/sample_notifier.dart b/mobile/lib/demo/sample_notifier.dart
new file mode 100644
index 000000000..752b3ff84
--- /dev/null
+++ b/mobile/lib/demo/sample_notifier.dart
@@ -0,0 +1,196 @@
+import 'dart:typed_data';
+
+import 'package:harness_mobile/api/api_client.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/core/snapshot_store.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/stats/harness_stats.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+import 'package:harness_mobile/viewer/viewer_services.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+/// Where sample mode points everything that could reach a server, should anything try: a name
+/// that is reserved never to resolve (RFC 6761). Nothing in the sample is meant to get this far —
+/// the machines answer in-process and [SampleApiClient] answers the rest — so this is the floor
+/// under that, not the mechanism.
+const sampleConfig = AppConfig(
+ apiBaseUrl: 'https://sample.invalid',
+ autonomousEnv: 'sample',
+ localCliBaseUrl: 'http://sample.invalid',
+);
+
+/// A key-value store that forgets everything when the sample is left.
+///
+/// What the sample's session, links and preferences are kept in, so none of them is ever read
+/// from — or written over — the real app's `~/.harness` files.
+class SampleMemoryStore implements LocalKeyValueStore {
+ final Map<String, String> _values = {};
+
+ @override
+ Future<String?> read(String key) async => _values[key];
+
+ @override
+ Future<void> write(String key, String value) async => _values[key] = value;
+
+ @override
+ Future<void> delete(String key) async => _values.remove(key);
+}
+
+class _MemorySnapshot implements SnapshotStore {
+ String? _contents;
+
+ @override
+ Future<String?> read() async => _contents;
+
+ @override
+ Future<void> write(String contents) async => _contents = contents;
+
+ @override
+ Future<void> clear() async => _contents = null;
+}
+
+/// The backend's REST calls, answered without one.
+///
+/// Every call the app makes of its [ApiClient] is overridden, so none of them reaches `Dio` —
+/// and [sampleConfig] points `Dio` at nothing in case a call added later is not.
+class SampleApiClient extends ApiClient {
+ SampleApiClient({
+ required super.session,
+ required this.machinesOnFile,
+ required this.transcribe,
+ }) : super(config: sampleConfig);
+
+ /// The sample's computers, as `/api/machines` would list them.
+ final List<Machine> Function() machinesOnFile;
+
+ /// What a voice take said — see `sample_voice.dart`.
+ final Future<String> Function() transcribe;
+
+ @override
+ Future<Map<String, dynamic>?> me() async => null;
+
+ @override
+ Future<List<Machine>> machines() async => machinesOnFile();
+
+ @override
+ Future<String?> renameMachine({
+ required String machineId,
+ required String name,
+ }) async => name;
+
+ @override
+ Future<void> deleteMachine({required String machineId}) async {}
+
+ /// No desk: the sample's harnesses are in no tabs, and the phone then swipes the whole
+ /// account — which is how a new account looks too.
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async =>
+ null;
+
+ @override
+ Future<String> transcribeVoice(Uint8List wav, {required String lang}) =>
+ transcribe();
+}
+
+/// The app's state for sample mode: the ordinary [AppNotifier], fed by machines that answer
+/// in-process, with every store it keeps held in memory.
+///
+/// ⚠️ **No `paneLayoutStore`, on purpose.** It is what gives a notifier its files — the last
+/// agent opened, the project history, search history, the machine cache — and its absence makes
+/// every one of them a store that remembers for this run only. It is also what would put the
+/// sample's notices in the phone's notification centre; [SilentSystemNotices] keeps them in the
+/// app, as unread marks.
+class SampleNotifier extends AppNotifier {
+ SampleNotifier._({
+ required AuthSession session,
+ required ViewerServices viewer,
+ required WsConn Function(String machineId) connections,
+ }) : super(
+ config: sampleConfig,
+ authSession: session,
+ configStore: null,
+ viewer: viewer,
+ systemNotices: SilentSystemNotices(),
+ connectionForTest: connections,
+ );
+
+ factory SampleNotifier({
+ required WsConn Function(String machineId) connections,
+ required List<Machine> Function() machinesOnFile,
+ required Future<String> Function() transcribe,
+ }) {
+ final storage = SampleMemoryStore();
+ final session = AuthSession(storage: storage);
+ final notifier = SampleNotifier._(
+ session: session,
+ viewer: ViewerServices(
+ config: sampleConfig,
+ session: session,
+ keys: ViewerKeyStore(storage: storage),
+ ),
+ connections: connections,
+ );
+ notifier.api = SampleApiClient(
+ session: session,
+ machinesOnFile: machinesOnFile,
+ transcribe: transcribe,
+ );
+ return notifier;
+ }
+
+ /// The sample's own counters — see [AppNotifier.stats].
+ final HarnessStats _stats = HarnessStats(store: _MemorySnapshot());
+
+ @override
+ HarnessStats get stats => _stats;
+
+ /// Tells every screen the sample's state moved.
+ void changed() => notifyListeners();
+
+ // Everything below would start real work — a sign-in, a sign-out, a fetch of the account's
+ // machines, a link with a password — and the sample has none of it to do.
+
+ @override
+ Future<void> bootstrap() async {}
+
+ @override
+ Future<void> logout() async {}
+
+ @override
+ Future<void> refreshMachines() async => notifyListeners();
+
+ @override
+ Future<void> retryMachines() async => notifyListeners();
+
+ /// The sample's computers are always reached, and their agents are already here: there is
+ /// nothing to dial or re-ask when Find opens.
+ @override
+ Future<void> reachAllMachines() async {}
+
+ @override
+ Future<void> reloadMachineData(String machineId) async {}
+
+ @override
+ Future<String?> connectWithPassword(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ }) async => 'Sample computers are already linked.';
+
+ @override
+ Future<String?> unlinkMachine(String machineId) async =>
+ 'Sample computers stay linked.';
+
+ @override
+ void dispose() {
+ _stats.dispose();
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/demo/sample_runtime.dart b/mobile/lib/demo/sample_runtime.dart
new file mode 100644
index 000000000..252cc09b1
--- /dev/null
+++ b/mobile/lib/demo/sample_runtime.dart
@@ -0,0 +1,809 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:math';
+
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/notify/agent_notice.dart' show NoticeKind;
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pending_question.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+import 'sample_harness.dart';
+import 'sample_notifier.dart';
+import 'sample_screen.dart';
+import 'sample_scripts.dart';
+import 'sample_text.dart';
+import 'sample_voice.dart';
+
+/// Everything sample mode runs: its app state, the two computers answering it, the harnesses on
+/// them, and every timer any of it holds.
+///
+/// It plays the part of the harness daemon on each computer. A terminal opened on a sample
+/// harness is answered with a stream — `terminal_ready`, then a keyframe of what that harness has
+/// on screen, then its output as it happens — through the same [TerminalSession] a real machine
+/// would reach, so the phone draws it with the same code. What is typed comes back the same way,
+/// as input frames, and becomes keystrokes in the harness.
+///
+/// [dispose] ends all of it at once: every timer the sample started is on [_timers], so leaving
+/// cannot leave one running.
+class SampleRuntime implements SampleHarnessHost {
+ SampleRuntime({DateTime? now}) {
+ notifier = SampleNotifier(
+ connections: _connectionFor,
+ machinesOnFile: () => machines,
+ transcribe: () => transcriber.transcribe(),
+ );
+ _seed(now ?? DateTime.now());
+ }
+
+ late final SampleNotifier notifier;
+
+ late final SampleTranscriber transcriber = SampleTranscriber(
+ after: schedule,
+ answering: _focusedIsAsking,
+ );
+
+ final Map<String, SampleConnection> _connections = {};
+ final Map<String, SampleHarness> _harnesses = {};
+ final Map<String, _Stream> _streams = {};
+ final Map<String, Map<String, dynamic>> _creations = {};
+ final Set<Timer> _timers = {};
+ final Random _random = Random();
+ int _created = 0;
+ int _questions = 0;
+ bool _disposed = false;
+
+ /// The sample's computers, as the account lists them.
+ List<Machine> get machines => [
+ for (final computer in sampleComputers)
+ Machine(
+ machineId: computer.id,
+ authMode: MachineAuthMode.remote,
+ name: computer.name,
+ hostname: computer.name,
+ status: 'online',
+ ),
+ ];
+
+ /// Every harness in the sample, keyed `machineId/agentId`.
+ @visibleForTesting
+ Map<String, SampleHarness> get harnesses => Map.unmodifiable(_harnesses);
+
+ SampleHarness? harnessOf(String machineId, String agentId) =>
+ _harnesses['$machineId/$agentId'];
+
+ /// The connection to one sample computer — what the notifier dials.
+ SampleConnection connectionFor(String machineId) => _connectionFor(machineId);
+
+ /// Voice input for the sample's pager: a microphone that records nothing, heard as
+ /// [transcriber] says.
+ VoiceInputController voiceController() => VoiceInputController(
+ transcriber: (_, _) => transcriber.transcribe(),
+ recorder: SampleVoiceRecorder(every: every),
+ );
+
+ // ── the clock ──────────────────────────────────────────────────────────────────────────────
+
+ @override
+ Timer schedule(Duration delay, void Function() run) {
+ late final Timer timer;
+ timer = Timer(delay, () {
+ _timers.remove(timer);
+ if (!_disposed) run();
+ });
+ _track(timer);
+ return timer;
+ }
+
+ @override
+ Timer every(Duration period, void Function() run) {
+ final timer = Timer.periodic(period, (_) {
+ if (!_disposed) run();
+ });
+ _track(timer);
+ return timer;
+ }
+
+ void _track(Timer timer) {
+ if (_disposed) {
+ timer.cancel();
+ return;
+ }
+ _timers
+ ..removeWhere((held) => !held.isActive)
+ ..add(timer);
+ }
+
+ // ── the starting state ─────────────────────────────────────────────────────────────────────
+
+ void _seed(DateTime now) {
+ notifier.machines = machines;
+ for (final machine in notifier.machines) {
+ notifier.machineStates[machine.machineId] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..terminalCapabilityLoaded = true
+ ..terminalCapabilityAvailable = true
+ ..terminalNoTakeoverAvailable = true
+ ..projectFolderAvailable = true;
+ }
+ final seeds = sampleSeeds(now);
+ for (final seed in seeds) {
+ final harness = SampleHarness(
+ machineId: seed.computer.id,
+ agent: seed.agent,
+ host: this,
+ transcript: seed.transcript,
+ loop: seed.loop,
+ );
+ _harnesses['${harness.machineId}/${harness.agentId}'] = harness;
+ _publish(harness);
+ for (final entry in seed.transcript) {
+ if (entry is UserEntry) harness.asks.insert(0, entry.text);
+ }
+ if (seed.finished case final reply?) {
+ harness.replies.insert(0, reply);
+ // News nobody has read: marked without the chime a live turn ending would make.
+ notifier.agentNotices.unread.mark((
+ machineId: harness.machineId,
+ agentId: harness.agentId,
+ ), NoticeKind.done);
+ }
+ }
+ for (final seed in seeds) {
+ final harness = harnessOf(seed.computer.id, seed.agent['id'] as String)!;
+ if (seed.ask != null) {
+ harness.begin(ask: seed.ask, then: seed.then);
+ } else if (seed.loop != null) {
+ harness.begin(verb: 'Tracing');
+ }
+ }
+ }
+
+ // ── what the harnesses report ─────────────────────────────────────────────────────────────
+
+ @override
+ void appended(SampleHarness harness, List<SampleEntry> entries) {
+ for (final stream in _streamsOf(harness)) {
+ _write(stream, entries);
+ }
+ }
+
+ @override
+ void liveChanged(SampleHarness harness) {
+ for (final stream in _streamsOf(harness)) {
+ _write(stream, const []);
+ }
+ }
+
+ @override
+ void workingChanged(SampleHarness harness, bool working) {
+ final machine = notifier.stateOf(harness.machineId);
+ if (machine == null) return;
+ if (working) {
+ machine.processingAgentIds.add(harness.agentId);
+ } else {
+ machine.processingAgentIds.remove(harness.agentId);
+ }
+ machine.agentActivityAt[harness.agentId] = DateTime.now();
+ _publish(harness);
+ notifier.changed();
+ }
+
+ @override
+ void askChanged(SampleHarness harness, SampleAsk? ask) {
+ final machine = notifier.stateOf(harness.machineId);
+ if (machine == null) return;
+ final ref = (machineId: harness.machineId, agentId: harness.agentId);
+ if (ask == null) {
+ machine.blockedAgents.remove(harness.agentId);
+ notifier.agentNotices.unread.clear(ref, kind: NoticeKind.question);
+ } else {
+ machine.blockedAgents[harness.agentId] = PendingQuestion(
+ machineId: harness.machineId,
+ agentId: harness.agentId,
+ requestId: 'sample-question-${++_questions}',
+ answerKey: ask.question,
+ prompt: ask.question,
+ options: ask.options,
+ multi: false,
+ since: DateTime.now(),
+ );
+ if (!_watching(ref)) {
+ notifier.agentNotices.unread.mark(ref, NoticeKind.question);
+ }
+ }
+ notifier.changed();
+ }
+
+ @override
+ void turnEnded(SampleHarness harness, String? reply) {
+ _publish(harness);
+ final machine = notifier.stateOf(harness.machineId);
+ if (reply != null && machine != null) {
+ final ref = (machineId: harness.machineId, agentId: harness.agentId);
+ notifier.agentNotices.turnEnded(
+ (
+ ref: ref,
+ name: harness.agent['name'] as String? ?? 'harness',
+ machine: machine.machine.displayName,
+ ),
+ (aborted: false, replay: false, subagent: false, reply: reply),
+ watching: () => _watching(ref),
+ );
+ }
+ notifier.changed();
+ }
+
+ @override
+ List<SampleStep> replyTo(SampleHarness harness, String text) =>
+ sampleReply(harness, text);
+
+ bool _watching(({String machineId, String agentId}) ref) {
+ final pane = notifier.focusedPane;
+ return pane != null &&
+ pane.machineId == ref.machineId &&
+ pane.agentId == ref.agentId;
+ }
+
+ bool _focusedIsAsking() {
+ final pane = notifier.focusedPane;
+ final agentId = pane?.agentId;
+ if (pane == null || agentId == null) return false;
+ return harnessOf(pane.machineId, agentId)?.asking ?? false;
+ }
+
+ /// [harness]'s agent, as its machine now describes it, into the notifier's list.
+ void _publish(SampleHarness harness) {
+ final machine = notifier.stateOf(harness.machineId);
+ if (machine == null) return;
+ final agent = Agent.fromJson(Map<String, dynamic>.from(harness.agent));
+ final agents = [...machine.agents];
+ final at = agents.indexWhere((known) => known.id == agent.id);
+ if (at < 0) {
+ agents.add(agent);
+ } else {
+ agents[at] = agent;
+ }
+ machine.agents = agents;
+ }
+
+ // ── the machines' side of the wire ────────────────────────────────────────────────────────
+
+ SampleConnection _connectionFor(String machineId) => _connections.putIfAbsent(
+ machineId,
+ () => SampleConnection._(this, machineId),
+ );
+
+ Future<Map<String, dynamic>> _request(
+ String machineId,
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ if (_disposed) {
+ throw WsRequestFailure(responseType: '${type}_result', code: 'CLOSED');
+ }
+ final agentId = payload['agentId'] as String?;
+ final harness = agentId == null ? null : harnessOf(machineId, agentId);
+ switch (type) {
+ case 'agents_list':
+ return {
+ 'agents': [
+ for (final harness in _harnesses.values)
+ if (harness.machineId == machineId) {...harness.agent},
+ ],
+ };
+ case 'terminal_capabilities':
+ return {
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'backend': 'tmux',
+ 'available': true,
+ 'features': {'noTakeover': true, 'projectFolder': true},
+ };
+ case 'engines_probe':
+ final asked = payload['engines'];
+ return {
+ 'engines': [
+ for (final engine
+ in asked is List ? asked : const ['claude', 'codex'])
+ {
+ 'engine': engine,
+ 'installed': engine == 'claude' || engine == 'codex',
+ 'installable': true,
+ 'command': engine,
+ },
+ ],
+ };
+ case 'codex_profiles_list':
+ return {'profiles': const []};
+ case 'fs_list_dir':
+ return _listDir(payload['path']);
+ case 'git_project_info':
+ return _gitInfo(payload['path']);
+ case 'agent_create':
+ return _create(machineId, payload);
+ case 'agent_create_status':
+ return _creations[payload['creationId']] ??
+ {'creationId': payload['creationId'], 'state': 'missing'};
+ case 'agent_update':
+ if (harness == null) break;
+ if (payload['name'] case final String name
+ when name.trim().isNotEmpty) {
+ harness.agent['name'] = name.trim();
+ }
+ if (payload['opened'] == true) {
+ harness.agent['lastOpenedAt'] = DateTime.now()
+ .toUtc()
+ .toIso8601String();
+ }
+ _publish(harness);
+ notifier.changed();
+ return {};
+ case 'agent_delete':
+ if (harness == null) break;
+ _forget(harness);
+ return {};
+ case 'agent_restart':
+ case 'agent_resume':
+ if (harness == null) break;
+ harness.restart();
+ return {
+ 'agent': {...harness.agent},
+ 'resumed': true,
+ };
+ case 'agent_recent':
+ if (harness == null) break;
+ return {
+ 'agentId': harness.agentId,
+ 'asks': [...harness.asks],
+ 'events': [
+ for (final reply in harness.replies)
+ {'kind': 'summary', 'text': reply},
+ ],
+ };
+ case 'usage_read':
+ return {};
+ case 'grid_models_list':
+ // Find's `:` — the models a sample harness could run on: this computer's own, as a
+ // real machine lists them.
+ return {
+ 'gridName': 'home',
+ 'localModelEngines': ['claude', 'codex', 'opencode'],
+ 'grids': [
+ {
+ 'name': 'home',
+ 'own': true,
+ 'models': [
+ {'id': 'qwen3-coder-30b', 'node': machineId},
+ {'id': 'gpt-oss-20b', 'node': machineId},
+ {'id': 'devstral-small', 'node': 'laptop'},
+ ],
+ },
+ ],
+ };
+ }
+ throw WsRequestFailure(
+ responseType: '${type}_result',
+ code: harness == null && agentId != null
+ ? 'AGENT_NOT_FOUND'
+ : 'UNSUPPORTED',
+ detail: 'Not part of the sample.',
+ );
+ }
+
+ /// `agent_create`: a new harness on [machineId], started on its first task when it was given one.
+ Map<String, dynamic> _create(String machineId, Map<String, dynamic> payload) {
+ final creationId = payload['creationId'];
+ final engine = payload['engine'] as String? ?? 'claude';
+ if (engine != 'claude' && engine != 'codex') {
+ throw const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'INVALID_ENGINE',
+ detail: 'The sample runs Claude Code and Codex.',
+ );
+ }
+ final number = ++_created;
+ final cwd = _cwdFor(payload, number);
+ final project = cwd.split('/').where((part) => part.isNotEmpty).last;
+ final branchRef = payload['branchRef'] as String?;
+ final branch =
+ payload['branchName'] as String? ??
+ branchRef?.replaceFirst(RegExp(r'^refs/(heads|remotes/[^/]+)/'), '') ??
+ 'main';
+ final task = (payload['prompt'] as String?)?.trim();
+ final agent = sampleAgentJson(
+ id: 'sample-new-$number',
+ // Named for its task the way the others are named — `dark-mode-toggle` — or numbered.
+ name: (task == null ? null : sampleSlug(task)) ?? 'harness-${number + 5}',
+ engine: engine,
+ project: project,
+ branch: branch,
+ updatedAt: DateTime.now(),
+ );
+ (agent['project'] as Map)['cwd'] = cwd;
+ (agent['project'] as Map)['root'] = cwd;
+ final harness = SampleHarness(
+ machineId: machineId,
+ agent: agent,
+ host: this,
+ transcript: [BannerEntry(cwd)],
+ );
+ _harnesses['$machineId/${harness.agentId}'] = harness;
+ // Every app hears about a new harness, not only the one that asked for it.
+ _publish(harness);
+ notifier.changed();
+ if (task != null && task.isNotEmpty) {
+ // The engine starts, and the task is typed into it.
+ schedule(const Duration(milliseconds: 900), () => harness.submit(task));
+ }
+ final reply = {
+ 'creationId': creationId,
+ 'state': 'created',
+ 'agent': {...agent},
+ };
+ if (creationId is String) _creations[creationId] = reply;
+ return reply;
+ }
+
+ String _cwdFor(Map<String, dynamic> payload, int number) {
+ final cwd = payload['cwd'];
+ if (cwd is String && cwd.trim().isNotEmpty) return cwd.trim();
+ final source = payload['gitSource'];
+ if (source is String && source.isNotEmpty) return source;
+ final url = payload['repositoryUrl'];
+ if (url is String && url.isNotEmpty) {
+ final name = url
+ .split(RegExp(r'[/:]'))
+ .where((part) => part.isNotEmpty)
+ .last
+ .replaceFirst(RegExp(r'\.git$'), '');
+ return '~/code/$name';
+ }
+ return '~/code/new-project-$number';
+ }
+
+ void _forget(SampleHarness harness) {
+ harness.dispose();
+ _harnesses.remove('${harness.machineId}/${harness.agentId}');
+ _streams.removeWhere((_, stream) => identical(stream.harness, harness));
+ final machine = notifier.stateOf(harness.machineId);
+ machine?.processingAgentIds.remove(harness.agentId);
+ machine?.blockedAgents.remove(harness.agentId);
+ }
+
+ static const _folders = <String, List<String>>{
+ '~': ['code', 'Desktop', 'Documents', 'Downloads'],
+ '~/code': ['api', 'docs', 'mobile', 'web', 'scratch'],
+ '~/code/api': ['db', 'src', 'tests'],
+ '~/code/docs': ['public', 'src'],
+ '~/code/mobile': ['android', 'ios', 'lib', 'test'],
+ '~/code/web': ['public', 'src', 'test'],
+ '~/code/scratch': [],
+ };
+
+ Map<String, dynamic> _listDir(Object? raw) {
+ var path = raw is String ? raw.trim() : '';
+ if (path.endsWith('/') && path.length > 1) {
+ path = path.substring(0, path.length - 1);
+ }
+ // Somewhere the sample has no folder for is the home folder — including `.`, which is
+ // where going up from `~` leads.
+ if (!_folders.containsKey(path) && !path.startsWith('~/code/')) path = '~';
+ return {
+ 'path': path,
+ 'entries': [
+ for (final name in _folders[path] ?? const <String>[])
+ {'name': name, 'isDir': true},
+ ],
+ 'truncated': false,
+ };
+ }
+
+ Map<String, dynamic> _gitInfo(Object? raw) {
+ final path = raw is String ? raw : '';
+ final project = RegExp(r'^~/code/([^/]+)$').firstMatch(path)?.group(1);
+ if (project == null || project == 'scratch') return {'isGit': false};
+ return {
+ 'isGit': true,
+ 'branch': 'main',
+ 'defaultRef': 'refs/remotes/origin/main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/dev', 'name': 'dev'},
+ {
+ 'ref': 'refs/remotes/origin/main',
+ 'name': 'origin/main',
+ 'remote': true,
+ },
+ ],
+ };
+ }
+
+ // ── terminals ─────────────────────────────────────────────────────────────────────────────
+
+ bool _terminalFrame(
+ String machineId,
+ String type,
+ Map<String, dynamic> payload,
+ ) {
+ if (_disposed) return false;
+ final stream = _streams[payload['streamId']];
+ switch (type) {
+ case 'terminal_open':
+ _open(machineId, payload);
+ case 'terminal_resize':
+ if (stream == null) break;
+ stream
+ ..cols = (payload['cols'] as num?)?.toInt() ?? stream.cols
+ ..rows = (payload['rows'] as num?)?.toInt() ?? stream.rows;
+ _keyframe(stream);
+ case 'terminal_resync':
+ if (stream != null) _keyframe(stream);
+ case 'terminal_close':
+ _streams.remove(payload['streamId']);
+ case 'message':
+ final agentId = payload['agentId'];
+ final content = payload['content'];
+ if (agentId is String && content is String) {
+ harnessOf(machineId, agentId)?.submit(content);
+ }
+ }
+ return true;
+ }
+
+ bool _terminalBinary(Uint8List bytes) {
+ if (_disposed) return false;
+ final frame = decodeTerminalLocal(bytes);
+ if (frame == null) return true;
+ final stream = _streams[frame.streamId];
+ if (stream == null) return true;
+ if (frame.kind == TerminalBinaryKind.input ||
+ frame.kind == TerminalBinaryKind.paste) {
+ stream.harness.keys(utf8.decode(frame.bytes, allowMalformed: true));
+ }
+ return true;
+ }
+
+ void _open(String machineId, Map<String, dynamic> payload) {
+ final agentId = payload['agentId'];
+ final requestId = payload['requestId'];
+ final harness = agentId is String ? harnessOf(machineId, agentId) : null;
+ // A beat, as a real attach takes one — and after `send` has returned, as a reply would.
+ schedule(const Duration(milliseconds: 160), () {
+ if (harness == null) {
+ _toSessions(machineId, 'terminal_error', {
+ 'requestId': requestId,
+ 'code': 'AGENT_NOT_FOUND',
+ 'message': 'That harness is not in the sample.',
+ });
+ return;
+ }
+ final stream = _Stream(
+ id: _streamId(),
+ harness: harness,
+ cols: (payload['cols'] as num?)?.toInt() ?? 80,
+ rows: (payload['rows'] as num?)?.toInt() ?? 24,
+ );
+ _streams[stream.id] = stream;
+ _toSessions(machineId, 'terminal_ready', {
+ 'protocolVersion': TerminalSession.protocolVersion,
+ 'requestId': requestId,
+ 'agentId': agentId,
+ 'streamId': stream.id,
+ });
+ _keyframe(stream);
+ });
+ }
+
+ /// A JSON frame, to every session on [machineId] — each one matches its own request, as it does
+ /// with a real machine's.
+ void _toSessions(
+ String machineId,
+ String type,
+ Map<String, dynamic> payload,
+ ) {
+ for (final pane in notifier.panesFor(machineId).toList()) {
+ final session = pane.session;
+ if (session != null) unawaited(session.handleFrame(type, payload));
+ }
+ }
+
+ Iterable<_Stream> _streamsOf(SampleHarness harness) => _streams.values
+ .where((stream) => identical(stream.harness, harness))
+ .toList();
+
+ /// Everything [stream]'s harness has on screen, at [stream]'s width — after the modes both
+ /// CLIs set: the cursor hidden (they draw their own caret) and bracketed paste on, so a paste
+ /// arrives as one piece rather than as lines that each press Return.
+ void _keyframe(_Stream stream) {
+ final width = SampleText.fit(stream.cols);
+ final harness = stream.harness;
+ final live = harness.look.live(harness.live, width);
+ final lines = [
+ ...harness.look.transcript(harness.transcript, width),
+ ...live,
+ ];
+ stream.live = live.length;
+ _send(
+ stream,
+ TerminalBinaryKind.keyframe,
+ '\x1b[?25l\x1b[?2004h${lines.join('\r\n')}',
+ );
+ }
+
+ /// [entries] added above the live region, and the live region drawn again under them — the
+ /// cursor walks back up to where the live region starts, clears to the end of the screen, and
+ /// writes.
+ void _write(_Stream stream, List<SampleEntry> entries) {
+ final width = SampleText.fit(stream.cols);
+ final harness = stream.harness;
+ final live = harness.look.live(harness.live, width);
+ // A live region taller than the pane cannot be walked back over: the top of it has scrolled
+ // off. A keyframe says the same thing in one go.
+ if (stream.live >= stream.rows || live.length >= stream.rows) {
+ _keyframe(stream);
+ return;
+ }
+ final lines = [
+ for (final entry in entries) ...[...harness.look.entry(entry, width), ''],
+ ...live,
+ ];
+ final back = stream.live > 1 ? '\x1b[${stream.live - 1}A' : '';
+ stream.live = live.length;
+ _send(
+ stream,
+ TerminalBinaryKind.output,
+ '\r$back\x1b[J${lines.join('\r\n')}',
+ );
+ }
+
+ void _send(_Stream stream, TerminalBinaryKind kind, String text) {
+ final holders = [
+ for (final pane in notifier.panesFor(stream.harness.machineId))
+ if (pane.session case final session? when session.streamId == stream.id)
+ session,
+ ];
+ if (holders.isEmpty) {
+ // Nobody reads it any more — the page reopened, or went.
+ _streams.remove(stream.id);
+ return;
+ }
+ final keyframe = kind == TerminalBinaryKind.keyframe;
+ final frame = TerminalBinaryFrame(
+ kind: kind,
+ streamId: stream.id,
+ seq: stream.seq++,
+ bytes: utf8.encode(text),
+ compressed: false,
+ cols: keyframe ? stream.cols : null,
+ rows: keyframe ? stream.rows : null,
+ );
+ for (final session in holders) {
+ unawaited(session.handleBinary(frame));
+ }
+ }
+
+ /// Stream ids are UUIDs: the binary frames carry them as 16 bytes.
+ String _streamId() {
+ final hex = [
+ for (var i = 0; i < 16; i++)
+ _random.nextInt(256).toRadixString(16).padLeft(2, '0'),
+ ].join();
+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-'
+ '${hex.substring(16, 20)}-${hex.substring(20)}';
+ }
+
+ void dispose() {
+ if (_disposed) return;
+ _disposed = true;
+ for (final timer in _timers) {
+ timer.cancel();
+ }
+ _timers.clear();
+ for (final harness in _harnesses.values) {
+ harness.dispose();
+ }
+ _streams.clear();
+ notifier.dispose();
+ }
+}
+
+class _Stream {
+ _Stream({
+ required this.id,
+ required this.harness,
+ required this.cols,
+ required this.rows,
+ });
+
+ final String id;
+ final SampleHarness harness;
+ int cols;
+ int rows;
+ int seq = 0;
+
+ /// How many lines of live region the pane is showing — how far a redraw walks back up.
+ int live = 0;
+}
+
+/// One sample computer's end of the wire: everything the app sends a machine is answered here,
+/// in-process, and nothing is sent anywhere.
+class SampleConnection extends WsConn {
+ SampleConnection._(this._runtime, String machineId)
+ : super(
+ wsBaseUrl: 'wss://sample.invalid',
+ autonomousEnv: 'sample',
+ machineId: machineId,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final SampleRuntime _runtime;
+
+ @override
+ bool get isReady => !_runtime._disposed;
+
+ @override
+ Future<void> connect() async {}
+
+ @override
+ void reconnectNow() {}
+
+ @override
+ Future<void> forceReconnect() async {}
+
+ @override
+ Future<void> close() async {}
+
+ // ⚠️ Every answer comes back on a LATER microtask, never inside the call. A machine's reply
+ // always arrives after the send returns, and the app is written for that: an answer given
+ // synchronously lands in the middle of whatever asked — a widget's `initState`, a build — and
+ // its notification rebuilds a tree that is still being built.
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ await Future<void>.value();
+ return _runtime._request(machineId, type, payload);
+ }
+
+ @override
+ void sendRaw(String type, Map<String, dynamic> payload) =>
+ unawaited(sendTerminalFrame(type, payload));
+
+ @override
+ Future<void> sendFrame(Map<String, dynamic> frame) async {
+ await Future<void>.value();
+ final type = frame['type'];
+ final payload = frame['payload'];
+ if (type is String && payload is Map<String, dynamic>) {
+ _runtime._terminalFrame(machineId, type, payload);
+ }
+ }
+
+ @override
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ await Future<void>.value();
+ return _runtime._terminalFrame(machineId, type, payload);
+ }
+
+ @override
+ Future<bool> sendTerminalBinary(Uint8List bytes) async {
+ await Future<void>.value();
+ return _runtime._terminalBinary(bytes);
+ }
+}
diff --git a/mobile/lib/demo/sample_screen.dart b/mobile/lib/demo/sample_screen.dart
new file mode 100644
index 000000000..0b6a0a887
--- /dev/null
+++ b/mobile/lib/demo/sample_screen.dart
@@ -0,0 +1,592 @@
+/// What a sample harness has on screen, and how each CLI draws it.
+///
+/// A harness's screen is two parts, the way Claude Code and Codex both lay theirs out: the
+/// TRANSCRIPT, which only ever grows and scrolls up into history, and the LIVE REGION under it —
+/// the prompt box, the spinner while working, a permission dialog while asking — which is redrawn
+/// in place every time it changes. [SampleLook] turns both into lines for one pane width.
+library;
+
+import 'sample_text.dart';
+
+/// One item of a transcript.
+sealed class SampleEntry {
+ const SampleEntry();
+}
+
+/// What the person asked, echoed the way the CLI echoes it.
+class UserEntry extends SampleEntry {
+ const UserEntry(this.text);
+ final String text;
+}
+
+/// The agent talking. `code` in backticks is drawn as code.
+class SayEntry extends SampleEntry {
+ const SayEntry(this.text);
+ final String text;
+}
+
+enum ToolOutcome { ok, failed, declined }
+
+/// A tool call and what it printed — `⏺ Bash(npm test)` / ` ⎿ 12 passed`.
+class ToolEntry extends SampleEntry {
+ const ToolEntry(
+ this.tool,
+ this.arg, [
+ this.out = const [],
+ this.outcome = ToolOutcome.ok,
+ ]);
+ final String tool;
+ final String arg;
+ final List<String> out;
+ final ToolOutcome outcome;
+}
+
+/// One line of a diff: its number in the file, `-`, `+` or a space, and the code.
+class DiffLine {
+ const DiffLine(this.number, this.sign, this.code);
+ final int number;
+ final String sign;
+ final String code;
+}
+
+/// An edit to a file, with the lines it changed.
+class DiffEntry extends SampleEntry {
+ const DiffEntry(this.file, this.lines);
+ final String file;
+ final List<DiffLine> lines;
+
+ int get added => lines.where((line) => line.sign == '+').length;
+ int get removed => lines.where((line) => line.sign == '-').length;
+}
+
+class Todo {
+ const Todo(this.text, {this.done = false});
+ final String text;
+ final bool done;
+}
+
+/// The agent's plan, as its todo tool prints it.
+class TodoEntry extends SampleEntry {
+ const TodoEntry(this.items);
+ final List<Todo> items;
+}
+
+/// What the CLI prints as it starts.
+class BannerEntry extends SampleEntry {
+ const BannerEntry(this.cwd);
+ final String cwd;
+}
+
+/// A line the CLI adds about the turn itself — an interrupt, a restart.
+class NoteEntry extends SampleEntry {
+ const NoteEntry(this.text);
+ final String text;
+}
+
+/// A permission question: the command, what it is for, and the answers on offer.
+class SampleAsk {
+ const SampleAsk({
+ required this.title,
+ required this.command,
+ required this.purpose,
+ required this.options,
+ });
+
+ /// `Bash command`.
+ final String title;
+ final String command;
+ final String purpose;
+
+ /// The rows, in order — `1.` is the first.
+ final List<String> options;
+
+ String get question => 'Do you want to proceed?';
+}
+
+enum LiveMode { idle, working, asking }
+
+/// The live region's state: what is typed, what the spinner says, what is being asked.
+class LiveState {
+ LiveMode mode = LiveMode.idle;
+ String input = '';
+
+ /// The spinner's word, `Thinking`.
+ String verb = 'Thinking';
+
+ /// Spinner ticks since the turn started — the frame and the seconds both come from it.
+ int ticks = 0;
+ int tokens = 0;
+ SampleAsk? ask;
+ int selected = 0;
+}
+
+/// How often the spinner moves.
+const sampleSpinnerTick = Duration(milliseconds: 700);
+
+/// One CLI's way of drawing things.
+abstract class SampleLook {
+ const SampleLook();
+
+ /// The engine id this look is — `claude` or `codex`.
+ String get engine;
+
+ List<String> entry(SampleEntry entry, int width);
+ List<String> live(LiveState state, int width);
+
+ /// The transcript as lines: each entry, then the blank line both CLIs leave after one.
+ List<String> transcript(Iterable<SampleEntry> entries, int width) => [
+ for (final item in entries) ...[...entry(item, width), ''],
+ ];
+
+ static SampleLook of(String engine) =>
+ engine == 'codex' ? const CodexLook() : const ClaudeLook();
+}
+
+/// `code` in backticks, as its own style.
+List<Span> _inline(String text, {String style = '', String code = '38;5;153'}) {
+ final spans = <Span>[];
+ final parts = text.split('`');
+ for (var i = 0; i < parts.length; i++) {
+ if (parts[i].isEmpty) continue;
+ spans.add(Span(parts[i], i.isOdd ? code : style));
+ }
+ return spans;
+}
+
+String _seconds(LiveState state) =>
+ '${(state.ticks * sampleSpinnerTick.inMilliseconds / 1000).floor()}s';
+
+String _tokens(int tokens) =>
+ tokens < 1000 ? '$tokens' : '${(tokens / 1000).toStringAsFixed(1)}k';
+
+/// A box drawn to [width]: the border dim, the rows as given.
+List<String> _box(List<List<Span>> rows, int width, {String border = Sgr.dim}) {
+ final inner = width - 4;
+ return [
+ SampleText.ansi([Span('╭${'─' * (width - 2)}╮', border)]),
+ for (final row in rows)
+ SampleText.ansi([
+ Span('│', border),
+ const Span(' '),
+ ...SampleText.pad(row, inner),
+ const Span(' '),
+ Span('│', border),
+ ]),
+ SampleText.ansi([Span('╰${'─' * (width - 2)}╯', border)]),
+ ];
+}
+
+/// The prompt's text laid into rows [room] wide, with the caret after it — at most [maxRows], the
+/// last ones, as a prompt box scrolls its own text.
+List<List<Span>> _promptRows(
+ String input,
+ int room, {
+ required String placeholder,
+ int maxRows = 4,
+}) {
+ const caret = Span(' ', '7');
+ if (input.isEmpty) {
+ return [
+ [caret, Span(SampleText.clip(placeholder, room - 1), Sgr.dim)],
+ ];
+ }
+ final runes = input.runes.toList();
+ final rows = <List<Span>>[];
+ for (var at = 0; at < runes.length; at += room) {
+ final end = at + room < runes.length ? at + room : runes.length;
+ rows.add([Span(String.fromCharCodes(runes.sublist(at, end)))]);
+ }
+ final last = rows.last;
+ final lastWidth = SampleText.widthOf(last);
+ if (lastWidth < room) {
+ rows[rows.length - 1] = [...last, caret];
+ } else {
+ rows.add([caret]);
+ }
+ return rows.length <= maxRows ? rows : rows.sublist(rows.length - maxRows);
+}
+
+/// Claude Code, as its terminal UI draws.
+class ClaudeLook extends SampleLook {
+ const ClaudeLook();
+
+ @override
+ String get engine => 'claude';
+
+ static const _glyphs = ['·', '✢', '✳', '✶', '✻', '✽'];
+
+ @override
+ List<String> entry(SampleEntry entry, int width) => switch (entry) {
+ UserEntry(:final text) => SampleText.wrap(
+ [Span(text, Sgr.gray)],
+ width,
+ first: const [Span('> ', Sgr.gray)],
+ rest: const [Span(' ')],
+ ),
+ SayEntry(:final text) => SampleText.wrap(
+ _inline(text),
+ width,
+ first: const [Span('⏺', '97'), Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ ToolEntry() => _tool(entry, width),
+ DiffEntry() => _diff(entry, width),
+ TodoEntry(:final items) => [
+ SampleText.ansi(const [
+ Span('⏺', Sgr.green),
+ Span(' '),
+ Span('Update Todos', Sgr.bold),
+ ]),
+ for (var i = 0; i < items.length; i++)
+ ...SampleText.wrap(
+ [
+ Span(
+ '${items[i].done ? '☒' : '☐'} ${items[i].text}',
+ items[i].done ? '2;9' : '',
+ ),
+ ],
+ width,
+ first: [Span(i == 0 ? ' ⎿ ' : ' ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ ],
+ BannerEntry(:final cwd) => _box(
+ [
+ const [
+ Span('✻', Sgr.claude),
+ Span(' Welcome to '),
+ Span('Claude Code', Sgr.bold),
+ Span('!'),
+ ],
+ const [],
+ const [
+ Span(' /help for help, /status for your current setup', Sgr.dim),
+ ],
+ const [],
+ [Span(' cwd: $cwd', Sgr.dim)],
+ ],
+ width < 52 ? width : 52,
+ border: Sgr.claude,
+ ),
+ NoteEntry(:final text) => SampleText.wrap(
+ [Span(text, Sgr.red)],
+ width,
+ first: const [Span(' ⎿ ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ };
+
+ List<String> _tool(ToolEntry tool, int width) {
+ final mark = switch (tool.outcome) {
+ ToolOutcome.ok => Sgr.green,
+ ToolOutcome.failed || ToolOutcome.declined => Sgr.red,
+ };
+ return [
+ ...SampleText.wrap(
+ [Span(tool.tool, Sgr.bold), Span('(${tool.arg})')],
+ width,
+ first: [Span('⏺', mark), const Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ for (var i = 0; i < tool.out.length; i++)
+ ...SampleText.wrap(
+ [
+ Span(
+ tool.out[i],
+ tool.outcome == ToolOutcome.declined ? Sgr.red : '',
+ ),
+ ],
+ width,
+ first: [Span(i == 0 ? ' ⎿ ' : ' ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ ];
+ }
+
+ List<String> _diff(DiffEntry diff, int width) {
+ String plural(int n, String word) => '$n $word${n == 1 ? '' : 's'}';
+ return [
+ ...SampleText.wrap(
+ [const Span('Update', Sgr.bold), Span('(${diff.file})')],
+ width,
+ first: const [Span('⏺', Sgr.green), Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ ...SampleText.wrap(
+ [
+ Span(
+ 'Updated ${diff.file} with ${plural(diff.added, 'addition')} and '
+ '${plural(diff.removed, 'removal')}',
+ ),
+ ],
+ width,
+ first: const [Span(' ⎿ ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ for (final line in diff.lines)
+ ...SampleText.wrap(
+ [
+ Span('${line.sign} ${line.code}', switch (line.sign) {
+ '-' => Sgr.removed,
+ '+' => Sgr.added,
+ _ => '',
+ }),
+ ],
+ width,
+ first: [
+ const Span(' '),
+ Span(line.number.toString().padLeft(3), Sgr.dim),
+ const Span(' '),
+ ],
+ rest: const [Span(' ')],
+ ),
+ ];
+ }
+
+ @override
+ List<String> live(LiveState state, int width) {
+ if (state.mode == LiveMode.asking && state.ask != null) {
+ return _dialog(state.ask!, state.selected, width);
+ }
+ final box = _box([
+ for (final (i, row) in _promptRows(
+ state.input,
+ width - 6,
+ // Claude Code's own kind of nudge, and true of any project: not one project's file name
+ // on every harness.
+ placeholder: 'Try "run the tests and fix what fails"',
+ ).indexed)
+ [Span(i == 0 ? '> ' : ' '), ...row],
+ ], width);
+ final status = SampleText.ansi(
+ SampleText.clipSpans(const [
+ Span(' ⏵⏵ accept edits on', Sgr.magenta),
+ Span(' (shift+tab to cycle)', Sgr.dim),
+ ], width),
+ );
+ if (state.mode != LiveMode.working) return [...box, status];
+ final glyph = _glyphs[state.ticks % _glyphs.length];
+ final spinner = SampleText.ansi(
+ SampleText.clipSpans([
+ Span('$glyph ${state.verb}…', Sgr.claude),
+ Span(
+ ' (${_seconds(state)} · ↓ ${_tokens(state.tokens)} tokens · esc to interrupt)',
+ Sgr.dim,
+ ),
+ ], width),
+ );
+ return [spinner, '', ...box, status];
+ }
+
+ /// The permission dialog, as Claude Code draws it over its prompt box.
+ List<String> _dialog(SampleAsk ask, int selected, int width) => [
+ SampleText.ansi([Span('─' * width, Sgr.dim)]),
+ SampleText.ansi([const Span(' '), Span(ask.title, Sgr.bold)]),
+ '',
+ ...SampleText.wrap(
+ [Span(ask.command)],
+ width,
+ first: const [Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ ...SampleText.wrap(
+ [Span(ask.purpose, Sgr.dim)],
+ width,
+ first: const [Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ '',
+ SampleText.ansi([Span(' ${ask.question}')]),
+ for (var i = 0; i < ask.options.length; i++)
+ ...SampleText.wrap(
+ [Span(ask.options[i], i == selected ? Sgr.cyan : '')],
+ width,
+ first: [
+ Span(
+ i == selected ? ' ❯ ${i + 1}. ' : ' ${i + 1}. ',
+ i == selected ? Sgr.cyan : '',
+ ),
+ ],
+ rest: const [Span(' ')],
+ ),
+ '',
+ SampleText.ansi([const Span(' Esc to cancel · Enter to confirm', Sgr.dim)]),
+ ];
+}
+
+/// Codex, as its terminal UI draws.
+class CodexLook extends SampleLook {
+ const CodexLook();
+
+ @override
+ String get engine => 'codex';
+
+ @override
+ List<String> entry(SampleEntry entry, int width) => switch (entry) {
+ UserEntry(:final text) => SampleText.wrap(
+ [Span(text)],
+ width,
+ first: const [Span('›', Sgr.bold), Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ SayEntry(:final text) => SampleText.wrap(
+ _inline(text, code: Sgr.cyan),
+ width,
+ first: const [Span('• ')],
+ rest: const [Span(' ')],
+ ),
+ ToolEntry() => _tool(entry, width),
+ DiffEntry() => _diff(entry, width),
+ TodoEntry(:final items) => [
+ SampleText.ansi(const [Span('• '), Span('Updated Plan', Sgr.bold)]),
+ for (var i = 0; i < items.length; i++)
+ ...SampleText.wrap(
+ [
+ Span(
+ '${items[i].done ? '✔' : '□'} ${items[i].text}',
+ items[i].done ? '2;9' : '',
+ ),
+ ],
+ width,
+ first: [Span(i == 0 ? ' └ ' : ' ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ ],
+ BannerEntry(:final cwd) => _box([
+ const [
+ Span('>_ ', Sgr.dim),
+ Span('OpenAI Codex', Sgr.bold),
+ Span(' (v0.46.0)', Sgr.dim),
+ ],
+ const [],
+ const [Span('model: ', Sgr.dim), Span('gpt-5-codex high')],
+ [const Span('directory: ', Sgr.dim), Span(cwd)],
+ ], width < 48 ? width : 48),
+ NoteEntry(:final text) => SampleText.wrap(
+ [Span(text)],
+ width,
+ first: const [Span('■', Sgr.red), Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ };
+
+ List<String> _tool(ToolEntry tool, int width) {
+ final (title, lines) = switch (tool.tool) {
+ 'Bash' => ('Ran', <String>[]),
+ 'Read' => ('Explored', ['Read ${tool.arg}']),
+ 'Grep' || 'Search' => ('Explored', ['Search ${tool.arg}']),
+ _ => (tool.tool, <String>[]),
+ };
+ final out = [...lines, ...tool.out];
+ final mark = tool.outcome == ToolOutcome.ok ? '' : Sgr.red;
+ return [
+ ...SampleText.wrap(
+ [Span(title, Sgr.bold), if (tool.tool == 'Bash') Span(' ${tool.arg}')],
+ width,
+ first: [Span('•', mark), const Span(' ')],
+ rest: const [Span(' ')],
+ ),
+ for (var i = 0; i < out.length; i++)
+ ...SampleText.wrap(
+ [Span(out[i], Sgr.dim)],
+ width,
+ first: [Span(i == 0 ? ' └ ' : ' ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ ];
+ }
+
+ List<String> _diff(DiffEntry diff, int width) => [
+ ...SampleText.wrap(
+ [
+ const Span('Edited', Sgr.bold),
+ Span(' ${diff.file} '),
+ const Span('('),
+ Span('+${diff.added}', Sgr.green),
+ const Span(' '),
+ Span('-${diff.removed}', Sgr.red),
+ const Span(')'),
+ ],
+ width,
+ first: const [Span('• ')],
+ rest: const [Span(' ')],
+ ),
+ for (final line in diff.lines)
+ ...SampleText.wrap(
+ [
+ Span('${line.sign}${line.code}', switch (line.sign) {
+ '-' => Sgr.red,
+ '+' => Sgr.green,
+ _ => Sgr.dim,
+ }),
+ ],
+ width,
+ first: [
+ const Span(' '),
+ Span(line.number.toString().padLeft(3), Sgr.dim),
+ const Span(' '),
+ ],
+ rest: const [Span(' ')],
+ ),
+ ];
+
+ @override
+ List<String> live(LiveState state, int width) {
+ if (state.mode == LiveMode.asking && state.ask != null) {
+ return _approval(state.ask!, state.selected, width);
+ }
+ final rows = _promptRows(
+ state.input,
+ width - 2,
+ placeholder: 'Ask Codex to do anything',
+ );
+ final composer = [
+ for (final (i, row) in rows.indexed)
+ SampleText.ansi([Span(i == 0 ? '› ' : ' ', Sgr.bold), ...row]),
+ ];
+ final footer = SampleText.ansi(
+ SampleText.clipSpans(const [
+ Span(' 92% context left · ? for shortcuts', Sgr.dim),
+ ], width),
+ );
+ if (state.mode != LiveMode.working) return [...composer, '', footer];
+ final working = SampleText.ansi(
+ SampleText.clipSpans([
+ const Span('• '),
+ const Span('Working', Sgr.bold),
+ Span(' (${_seconds(state)} • esc to interrupt)', Sgr.dim),
+ ], width),
+ );
+ return [working, '', ...composer, '', footer];
+ }
+
+ List<String> _approval(SampleAsk ask, int selected, int width) => [
+ SampleText.ansi([
+ const Span(' Would you like to run the following command?', Sgr.bold),
+ ]),
+ '',
+ ...SampleText.wrap(
+ [Span(ask.command)],
+ width,
+ first: const [Span(' \$ ', Sgr.dim)],
+ rest: const [Span(' ')],
+ ),
+ '',
+ for (var i = 0; i < ask.options.length; i++)
+ ...SampleText.wrap(
+ [Span(ask.options[i], i == selected ? Sgr.cyan : '')],
+ width,
+ first: [
+ Span(
+ i == selected ? '› ${i + 1}. ' : ' ${i + 1}. ',
+ i == selected ? Sgr.cyan : '',
+ ),
+ ],
+ rest: const [Span(' ')],
+ ),
+ '',
+ SampleText.ansi([
+ const Span(' Press enter to confirm or esc to cancel', Sgr.dim),
+ ]),
+ ];
+}
diff --git a/mobile/lib/demo/sample_scripts.dart b/mobile/lib/demo/sample_scripts.dart
new file mode 100644
index 000000000..2db6215fa
--- /dev/null
+++ b/mobile/lib/demo/sample_scripts.dart
@@ -0,0 +1,773 @@
+/// What the sample's harnesses say: the sessions they open on, the work the busy one never
+/// finishes, and the replies any of them gives to whatever it is asked.
+///
+/// Paths are `~/code/…` throughout — a sample has no home folder of its own, and a real one
+/// written here would be somebody's.
+library;
+
+import 'sample_harness.dart';
+import 'sample_screen.dart';
+
+Duration _ms(int milliseconds) => Duration(milliseconds: milliseconds);
+
+EmitStep say(String text, [int ms = 1100]) => EmitStep(SayEntry(text), _ms(ms));
+
+EmitStep tool(
+ String name,
+ String arg,
+ List<String> out, {
+ int ms = 1500,
+ ToolOutcome outcome = ToolOutcome.ok,
+}) => EmitStep(ToolEntry(name, arg, out, outcome), _ms(ms));
+
+EmitStep diff(String file, List<DiffLine> lines, [int ms = 1600]) =>
+ EmitStep(DiffEntry(file, lines), _ms(ms));
+
+EmitStep todos(List<Todo> items, [int ms = 900]) =>
+ EmitStep(TodoEntry(items), _ms(ms));
+
+VerbStep verb(String word, [int ms = 300]) => VerbStep(word, _ms(ms));
+
+/// The last words of a turn: said, then the turn ends on them.
+List<SampleStep> finish(String reply, [int ms = 1000]) => [
+ say(reply, ms),
+ DoneStep(reply, _ms(250)),
+];
+
+// ── the five harnesses ─────────────────────────────────────────────────────────────────────────
+
+/// A computer in the sample.
+typedef SampleComputer = ({String id, String name});
+
+const sampleStudio = (id: 'sample-studio', name: 'studio');
+const sampleLaptop = (id: 'sample-laptop', name: 'laptop');
+const sampleComputers = [sampleStudio, sampleLaptop];
+
+/// How a harness starts: which computer, what the machine says about it, what is on its screen,
+/// and what it is doing.
+class SampleSeed {
+ const SampleSeed({
+ required this.computer,
+ required this.agent,
+ required this.transcript,
+ this.loop,
+ this.ask,
+ this.then,
+ this.finished,
+ });
+
+ final SampleComputer computer;
+ final Map<String, dynamic> agent;
+ final List<SampleEntry> transcript;
+
+ /// Busy forever.
+ final SampleLoop? loop;
+
+ /// Stopped on a question, and what it does with the answer.
+ final SampleAsk? ask;
+ final List<SampleStep> Function(int answer)? then;
+
+ /// Its last turn just ended, saying this — news nobody has read yet.
+ final String? finished;
+}
+
+Map<String, dynamic> sampleAgentJson({
+ required String id,
+ required String name,
+ required String engine,
+ required String project,
+ required String branch,
+ required DateTime updatedAt,
+ String? title,
+}) => {
+ 'id': id,
+ 'name': name,
+ 'engine': engine,
+ 'engineDisplayName': engine == 'codex' ? 'Codex' : 'Claude Code',
+ 'sessionId': 'session-$id',
+ 'status': 'active',
+ 'title': ?title,
+ 'updatedAt': updatedAt.toUtc().toIso8601String(),
+ 'project': {
+ 'name': project,
+ 'cwd': '~/code/$project',
+ 'root': '~/code/$project',
+ 'branch': branch,
+ },
+ 'terminal': {'available': true},
+};
+
+List<SampleSeed> sampleSeeds(DateTime now) => [
+ SampleSeed(
+ computer: sampleStudio,
+ agent: sampleAgentJson(
+ id: 'sample-fix-login',
+ name: 'fix-login',
+ engine: 'claude',
+ project: 'web',
+ branch: 'fix/login-refresh',
+ title: 'Sessions log out after an hour',
+ updatedAt: now.subtract(const Duration(seconds: 5)),
+ ),
+ transcript: const [
+ UserEntry(
+ 'sessions log users out after exactly an hour — fix it and add a test',
+ ),
+ SayEntry(
+ "I'll reproduce it first. An hour is the access token's lifetime, so "
+ 'the refresh path is the first suspect.',
+ ),
+ ToolEntry('Read', 'src/auth/session.ts', ['Read 142 lines']),
+ ToolEntry('Search', 'pattern: "refreshToken", path: "src"', [
+ 'Found 6 files',
+ ]),
+ ],
+ loop: _FixLoginLoop(),
+ ),
+ SampleSeed(
+ computer: sampleStudio,
+ agent: sampleAgentJson(
+ id: 'sample-refactor-db',
+ name: 'refactor-db',
+ engine: 'claude',
+ project: 'api',
+ branch: 'refactor/db-sessions',
+ title: 'Split the sessions table',
+ updatedAt: now.subtract(const Duration(minutes: 2)),
+ ),
+ transcript: const [
+ UserEntry('split the sessions table so tokens live in their own table'),
+ SayEntry(
+ "I'll split `sessions` into `sessions` and `session_tokens`, keep a "
+ 'view so current queries still work, then move the repository layer '
+ 'over.',
+ ),
+ ToolEntry('Read', 'db/schema.sql', ['Read 311 lines']),
+ ToolEntry('Write', 'db/migrations/0042_split_sessions.sql', [
+ 'Wrote 38 lines to db/migrations/0042_split_sessions.sql',
+ ]),
+ SayEntry(
+ 'The migration is written. Next it runs against the dev database.',
+ ),
+ ],
+ ask: migrationAsk,
+ then: _afterMigrationAnswer,
+ ),
+ SampleSeed(
+ computer: sampleStudio,
+ agent: sampleAgentJson(
+ id: 'sample-api-tests',
+ name: 'api-tests',
+ engine: 'codex',
+ project: 'api',
+ branch: 'main',
+ title: 'Fix the flaky API tests',
+ updatedAt: now.subtract(const Duration(minutes: 9)),
+ ),
+ transcript: const [
+ BannerEntry('~/code/api'),
+ UserEntry('run the API tests and fix anything flaky'),
+ SayEntry("I'll run the suite first to see what fails."),
+ ToolEntry('Bash', 'npm test -- api', [
+ 'FAIL tests/rate-limit.test.ts',
+ ' ● resets the window after 60s',
+ 'Tests: 1 failed, 57 passed, 58 total',
+ ], ToolOutcome.failed),
+ ToolEntry('Read', 'tests/rate-limit.test.ts', [
+ 'Read src/middleware/rateLimit.ts',
+ ]),
+ SayEntry(
+ 'The test sleeps on a real 60s timer and races the clock. Switching it '
+ 'to fake timers.',
+ ),
+ DiffEntry('tests/rate-limit.test.ts', [
+ DiffLine(18, '-', ' await sleep(60_000);'),
+ DiffLine(18, '+', ' jest.useFakeTimers();'),
+ DiffLine(19, '+', ' jest.advanceTimersByTime(60_000);'),
+ ]),
+ ToolEntry('Bash', 'for i in 1 2 3 4 5; do npm test -- api; done', [
+ 'Tests: 58 passed, 58 total (×5)',
+ ]),
+ SayEntry(_apiTestsReply),
+ ],
+ finished: _apiTestsReply,
+ ),
+ SampleSeed(
+ computer: sampleLaptop,
+ agent: sampleAgentJson(
+ id: 'sample-docs-site',
+ name: 'docs-site',
+ engine: 'claude',
+ project: 'docs',
+ branch: 'main',
+ title: 'Dark mode toggle in the docs header',
+ updatedAt: now.subtract(const Duration(minutes: 34)),
+ ),
+ transcript: const [
+ UserEntry('add a dark-mode toggle to the docs header'),
+ SayEntry("I'll add the toggle to the header and remember the choice."),
+ DiffEntry('src/components/Header.astro', [
+ DiffLine(12, ' ', '<nav class="links">'),
+ DiffLine(13, '+', ' <ThemeToggle />'),
+ DiffLine(14, ' ', '</nav>'),
+ ]),
+ ToolEntry('Bash', 'npm run build', ['✓ 214 pages built in 6.1s']),
+ SayEntry(
+ 'Done — the header has a sun/moon toggle, the choice is saved in '
+ '`localStorage`, and it follows the system setting until someone '
+ 'picks.',
+ ),
+ ],
+ ),
+ SampleSeed(
+ computer: sampleLaptop,
+ agent: sampleAgentJson(
+ id: 'sample-mobile-ui',
+ name: 'mobile-ui',
+ engine: 'codex',
+ project: 'mobile',
+ branch: 'feat/find-rows',
+ title: 'Machine names in Find',
+ updatedAt: now.subtract(const Duration(hours: 2)),
+ ),
+ transcript: const [
+ BannerEntry('~/code/mobile'),
+ UserEntry('make the Find list show the machine name under each harness'),
+ DiffEntry('lib/phone/find_row.dart', [
+ DiffLine(41, '-', ' Text(agent.name),'),
+ DiffLine(41, '+', ' Column(children: ['),
+ DiffLine(42, '+', ' Text(agent.name),'),
+ DiffLine(43, '+', ' Text(machine.name, style: dim),'),
+ DiffLine(44, '+', ' ]),'),
+ ]),
+ ToolEntry('Bash', 'flutter test test/find_test.dart', [
+ '00:03 +18: All tests passed!',
+ ]),
+ SayEntry(
+ 'Each row in Find now shows its machine under the name, dimmed, and '
+ 'the tests cover it.',
+ ),
+ ],
+ ),
+];
+
+const _apiTestsReply =
+ 'All 58 API tests pass, five runs in a row. The flake was the rate-limit '
+ 'test sleeping on a real clock; it uses fake timers now.';
+
+/// The question `refactor-db` is stopped on.
+const migrationAsk = SampleAsk(
+ title: 'Bash command',
+ command: 'psql "\$DATABASE_URL" -f db/migrations/0042_split_sessions.sql',
+ purpose: 'Apply the sessions split to the dev database',
+ options: [
+ 'Yes',
+ "Yes, and don't ask again for psql commands in ~/code/api",
+ 'No, and tell Claude what to do differently (esc)',
+ ],
+);
+
+List<SampleStep> _afterMigrationAnswer(int answer) {
+ const command =
+ 'psql "\$DATABASE_URL" -f db/migrations/0042_split_sessions.sql';
+ if (answer >= 2) {
+ return [
+ tool(
+ 'Bash',
+ command,
+ ['User declined to run this command'],
+ ms: 500,
+ outcome: ToolOutcome.declined,
+ ),
+ ...finish(
+ "Okay — I won't touch the database. What should I do instead? I can "
+ 'run it against a throwaway copy first, or leave the migration for you '
+ 'to review.',
+ ),
+ ];
+ }
+ return [
+ tool('Bash', command, [
+ 'BEGIN',
+ 'CREATE TABLE',
+ 'INSERT 0 18244',
+ 'ALTER TABLE',
+ 'CREATE VIEW',
+ 'COMMIT',
+ ], ms: 1200),
+ verb('Refactoring'),
+ say(
+ 'Migration applied: 18,244 tokens moved into `session_tokens`, and the '
+ '`sessions_v1` view keeps old queries working.',
+ 1300,
+ ),
+ diff('src/db/sessions.ts', const [
+ DiffLine(27, '-', " return db.one('sessions', id);"),
+ DiffLine(27, '+', " const row = await db.one('sessions', id);"),
+ DiffLine(28, '+', " row.tokens = await db.many('session_tokens',"),
+ DiffLine(29, '+', ' { sessionId: id });'),
+ ]),
+ verb('Testing'),
+ tool('Bash', 'npm test -- db', [
+ 'PASS src/db/sessions.test.ts (14 tests)',
+ 'Tests: 14 passed, 14 total',
+ ], ms: 1800),
+ ...finish(
+ 'Split done: tokens live in `session_tokens`, the repository reads the '
+ 'new tables, and all 14 db tests pass.',
+ ),
+ ];
+}
+
+/// `fix-login`'s work, which never runs out: four stretches of it, round and round.
+class _FixLoginLoop implements SampleLoop {
+ int _chapter = 0;
+
+ @override
+ List<SampleStep> next() {
+ final chapter = _chapters[_chapter % _chapters.length];
+ _chapter++;
+ return chapter();
+ }
+
+ static final _chapters = <List<SampleStep> Function()>[
+ () => [
+ verb('Tracing', 900),
+ say(
+ 'Found it: `ensureSession` checks `expiresAt` but never refreshes, so '
+ 'an expired access token signs the user out instead of being renewed.',
+ 1800,
+ ),
+ todos(const [
+ Todo('Reproduce the one-hour logout', done: true),
+ Todo('Refresh the token before it expires'),
+ Todo('Retry a 401 once after refreshing'),
+ Todo('Cover both with tests'),
+ ]),
+ diff('src/auth/session.ts', const [
+ DiffLine(41, '-', ' if (expired(session)) return signOut();'),
+ DiffLine(41, '+', ' if (expiresSoon(session)) {'),
+ DiffLine(42, '+', ' session = await refresh(session);'),
+ DiffLine(43, '+', ' }'),
+ ], 2200),
+ diff('src/api/client.ts', const [
+ DiffLine(88, '+', ' if (res.status === 401 && !retried) {'),
+ DiffLine(89, '+', ' await session.refresh();'),
+ DiffLine(90, '+', ' return send(req, { retried: true });'),
+ DiffLine(91, '+', ' }'),
+ ], 2000),
+ verb('Testing', 600),
+ tool(
+ 'Bash',
+ 'npm test -- auth',
+ [
+ 'FAIL src/auth/session.test.ts',
+ ' ● refreshes a token about to expire',
+ ' Expected: 200 Received: 401',
+ ],
+ ms: 2600,
+ outcome: ToolOutcome.failed,
+ ),
+ say(
+ "One failure — the test's fake clock never fires the refresh timer. "
+ 'Fixing the helper, not the code.',
+ 1600,
+ ),
+ diff('test/helpers/clock.ts', const [
+ DiffLine(12, ' ', ' now += ms;'),
+ DiffLine(13, '+', ' jest.runOnlyPendingTimers();'),
+ ]),
+ tool('Bash', 'npm test -- auth', [
+ 'PASS src/auth/session.test.ts (12 tests)',
+ 'PASS src/api/client.test.ts (9 tests)',
+ 'Tests: 21 passed, 21 total',
+ ], ms: 2600),
+ todos(const [
+ Todo('Reproduce the one-hour logout', done: true),
+ Todo('Refresh the token before it expires', done: true),
+ Todo('Retry a 401 once after refreshing', done: true),
+ Todo('Cover both with tests', done: true),
+ ]),
+ say(
+ 'Sessions now refresh five minutes before they expire, and a 401 '
+ 'retries once after a refresh. All 21 auth tests pass.',
+ 1400,
+ ),
+ const DoneStep(
+ 'Sessions refresh before they expire; all 21 auth tests pass.',
+ Duration(milliseconds: 100),
+ ),
+ ],
+ () => [
+ verb('Reading', 2400),
+ say(
+ 'Next: "Remember me" still loses the session after a browser restart. '
+ 'Checking the cookie flags.',
+ 1500,
+ ),
+ tool('Read', 'src/auth/cookies.ts', ['Read 64 lines']),
+ say(
+ 'The refresh cookie has no `Max-Age`, so it dies with the browser. It '
+ 'gets the refresh token\'s 30 days when "Remember me" is on.',
+ 1800,
+ ),
+ diff('src/auth/cookies.ts', const [
+ DiffLine(23, '-', " res.cookie('rt', token, { httpOnly: true });"),
+ DiffLine(23, '+', " res.cookie('rt', token, { httpOnly: true,"),
+ DiffLine(24, '+', ' maxAge: remember ? THIRTY_DAYS : undefined });'),
+ ]),
+ verb('Testing', 500),
+ tool('Bash', 'npm test -- cookies', [
+ 'PASS src/auth/cookies.test.ts (7 tests)',
+ ], ms: 2200),
+ tool('Bash', 'npx playwright test login.spec.ts', [
+ 'Running 4 tests using 2 workers',
+ '4 passed (9.8s)',
+ ], ms: 2800),
+ say(
+ '"Remember me" now survives a restart, and the Playwright login flow '
+ 'passes end to end.',
+ 1300,
+ ),
+ ],
+ () => [
+ verb('Tidying', 2000),
+ tool('Bash', 'npm run lint -- src/auth', ['✓ No problems'], ms: 1600),
+ tool('Bash', 'git diff --stat', [
+ 'src/api/client.ts | 6 ++++-',
+ 'src/auth/cookies.ts | 3 +-',
+ 'src/auth/session.ts | 11 +++++---',
+ 'test/helpers/clock.ts | 2 +-',
+ '4 files changed, 17 insertions(+), 5 deletions(-)',
+ ], ms: 1400),
+ say('Running the whole suite once more before handing this back.', 1300),
+ verb('Testing', 400),
+ tool('Bash', 'npm test', [
+ 'Test Suites: 38 passed, 38 total',
+ 'Tests: 412 passed, 412 total',
+ 'Time: 21.4 s',
+ ], ms: 3000),
+ ],
+ () => [
+ verb('Pondering', 1800),
+ say(
+ 'One more case: two tabs refreshing at once. The second refresh would '
+ 'spend a token the first already rotated.',
+ 1700,
+ ),
+ diff('src/auth/session.ts', const [
+ DiffLine(58, '+', ' // One refresh at a time, shared by every tab.'),
+ DiffLine(59, '+', ' return (inflight ??= doRefresh(session)'),
+ DiffLine(60, '+', ' .finally(() => (inflight = null)));'),
+ ]),
+ verb('Testing', 500),
+ tool('Bash', 'npm test -- auth --testNamePattern tabs', [
+ 'PASS src/auth/session.test.ts',
+ ' ✓ two tabs share one refresh (41 ms)',
+ ], ms: 2400),
+ say('Covered. Going round once more to re-check the whole flow.', 1300),
+ ],
+ ];
+}
+
+// ── replies ────────────────────────────────────────────────────────────────────────────────────
+
+/// Where each sample project's work happens — what a reply reads, edits and runs, and what the
+/// run prints.
+class _Place {
+ const _Place({
+ required this.file,
+ required this.testFile,
+ required this.test,
+ required this.passed,
+ required this.failed,
+ required this.edit,
+ required this.passes,
+ });
+
+ final String file;
+ final String testFile;
+
+ /// The command that checks the work.
+ final String test;
+
+ /// What that command prints when all is well, and when it is not.
+ final String passed;
+ final List<String> failed;
+
+ /// A small edit to [file].
+ final List<DiffLine> edit;
+
+ /// "All is well", in words: `all 21 tests pass`.
+ final String passes;
+}
+
+const _places = <String, _Place>{
+ 'web': _Place(
+ file: 'src/auth/session.ts',
+ testFile: 'src/auth/session.test.ts',
+ test: 'npm test -- auth',
+ passed: 'Tests: 21 passed, 21 total',
+ failed: [
+ 'FAIL src/auth/session.test.ts',
+ ' ● keeps the session across a reload',
+ 'Tests: 1 failed, 20 passed, 21 total',
+ ],
+ edit: [
+ DiffLine(64, '-', ' const ttl = 60 * 60;'),
+ DiffLine(64, '+', ' const ttl = options.ttl ?? 60 * 60;'),
+ ],
+ passes: 'all 21 tests pass',
+ ),
+ 'api': _Place(
+ file: 'src/db/sessions.ts',
+ testFile: 'tests/sessions.test.ts',
+ test: 'npm test -- api',
+ passed: 'Tests: 58 passed, 58 total',
+ failed: [
+ 'FAIL tests/sessions.test.ts',
+ ' ● returns null for an unknown id',
+ 'Tests: 1 failed, 57 passed, 58 total',
+ ],
+ edit: [
+ DiffLine(33, '-', ' const limit = 20;'),
+ DiffLine(33, '+', ' const limit = options.limit ?? 20;'),
+ ],
+ passes: 'all 58 tests pass',
+ ),
+ 'docs': _Place(
+ file: 'src/components/Header.astro',
+ testFile: 'tests/header.test.ts',
+ test: 'npm run build',
+ passed: '✓ 214 pages built in 6.2s',
+ failed: [
+ '✗ src/pages/search.astro',
+ ' Cannot read properties of undefined',
+ 'Build failed in 3.4s',
+ ],
+ edit: [
+ DiffLine(13, ' ', ' <ThemeToggle />'),
+ DiffLine(14, '+', ' <SearchBox />'),
+ ],
+ passes: 'the build passes',
+ ),
+ 'mobile': _Place(
+ file: 'lib/phone/find_row.dart',
+ testFile: 'test/find_test.dart',
+ test: 'flutter test',
+ passed: '00:04 +19: All tests passed!',
+ failed: [
+ '00:03 +18 -1: a row shows its machine [E]',
+ ' Expected: "studio" Actual: null',
+ '00:03 +18 -1: Some tests failed.',
+ ],
+ edit: [
+ DiffLine(43, '-', ' Text(machine.name, style: dim),'),
+ DiffLine(43, '+', ' Text(machine.displayName, style: dim),'),
+ ],
+ passes: 'all 19 tests pass',
+ ),
+};
+
+const _anywhere = _Place(
+ file: 'src/index.ts',
+ testFile: 'test/index.test.ts',
+ test: 'npm test',
+ passed: 'Tests: 7 passed, 7 total',
+ failed: [
+ 'FAIL test/index.test.ts',
+ ' ● starts with no arguments',
+ 'Tests: 1 failed, 6 passed, 7 total',
+ ],
+ edit: [
+ DiffLine(12, '-', 'const port = 3000;'),
+ DiffLine(12, '+', 'const port = Number(process.env.PORT ?? 3000);'),
+ ],
+ passes: 'all 7 tests pass',
+);
+
+_Place _placeOf(SampleHarness harness) {
+ final project = (harness.agent['project'] as Map?)?['name'] as String?;
+ return _places[project] ?? _anywhere;
+}
+
+/// A task's name as a harness would be named for it — `Add a dark mode toggle` → `dark-mode-toggle`:
+/// its first three words that say what, lowercased. Null when nothing is left.
+String? sampleSlug(String task) {
+ const skip = {
+ 'a',
+ 'an',
+ 'the',
+ 'to',
+ 'and',
+ 'of',
+ 'for',
+ 'in',
+ 'on',
+ 'with',
+ 'my',
+ 'our',
+ 'this',
+ 'that',
+ 'please',
+ 'add',
+ 'make',
+ 'create',
+ 'build',
+ 'write',
+ 'implement',
+ 'fix',
+ 'update',
+ 'change',
+ 'find',
+ 'run',
+ 'explain',
+ 'show',
+ 'me',
+ 'it',
+ 'some',
+ 'new',
+ };
+ final words = [
+ for (final word in task.toLowerCase().split(RegExp(r'[^a-z0-9]+')))
+ if (word.isNotEmpty && !skip.contains(word)) word,
+ ];
+ if (words.isEmpty) return null;
+ return words.take(3).join('-');
+}
+
+bool _mentions(String text, List<String> words) =>
+ words.any((word) => RegExp('\\b$word\\b').hasMatch(text));
+
+/// What any sample harness does when asked [text]: it says what it is on, in its own style,
+/// then does a little work that fits the words, and says what came of it.
+List<SampleStep> sampleReply(SampleHarness harness, String text) {
+ final place = _placeOf(harness);
+ final lower = text.toLowerCase();
+ final branch =
+ (harness.agent['project'] as Map?)?['branch'] as String? ?? 'main';
+ final onIt = [verb('Thinking', 200), say('On it — ${text.trim()}', 900)];
+
+ if (_mentions(lower, ['stop', 'wait', 'pause', 'cancel', 'hold'])) {
+ // Asked to stop, the busy harness stops being busy too.
+ harness.dropQueuedWork();
+ return [
+ verb('Stopping', 200),
+ ...finish(
+ 'Stopped — nothing is running now. Say when to pick it back up.',
+ 700,
+ ),
+ ];
+ }
+ if (_mentions(lower, ['diff', 'changes', 'changed'])) {
+ return [
+ ...onIt,
+ tool('Bash', 'git diff --stat', [
+ '${place.file} | 9 ++++++---',
+ '${place.testFile} | 14 ++++++++++++++',
+ '2 files changed, 20 insertions(+), 3 deletions(-)',
+ ]),
+ diff(place.file, const [
+ DiffLine(41, '-', ' return cached;'),
+ DiffLine(41, '+', ' if (cached && !cached.stale) return cached;'),
+ DiffLine(42, '+', ' return (cached = await load());'),
+ ]),
+ ...finish(
+ 'That is the whole diff: `${place.file}` and a new test beside it. '
+ 'Nothing is committed yet.',
+ ),
+ ];
+ }
+ if (_mentions(lower, ['commit', 'push'])) {
+ return [
+ ...onIt,
+ tool('Bash', 'git add -A && git commit -m "Refresh before expiry"', [
+ '[$branch 3f9c2e1] Refresh before expiry',
+ '2 files changed, 20 insertions(+), 3 deletions(-)',
+ ]),
+ ...finish('Committed as `3f9c2e1` on `$branch`. Not pushed.'),
+ ];
+ }
+ if (_mentions(lower, ['left', 'status', 'remaining', 'progress', 'next'])) {
+ return [
+ ...onIt,
+ todos(const [
+ Todo('Reproduce the bug', done: true),
+ Todo('Fix it', done: true),
+ Todo('Add a regression test'),
+ Todo('Update the changelog'),
+ ]),
+ ...finish(
+ 'Two things left: a regression test and the changelog entry. Both '
+ 'are small.',
+ ),
+ ];
+ }
+ if (_mentions(lower, ['tests?', 'fails?', 'failing', 'broken', 'fix'])) {
+ final adding = _mentions(lower, ['add', 'write', 'new']);
+ if (adding) {
+ return [
+ ...onIt,
+ tool('Read', place.file, ['Read 96 lines']),
+ tool('Write', place.testFile, ['Wrote 34 lines to ${place.testFile}']),
+ verb('Testing', 300),
+ tool('Bash', place.test, [place.passed], ms: 2000),
+ ...finish('Added three tests in `${place.testFile}`; ${place.passes}.'),
+ ];
+ }
+ return [
+ ...onIt,
+ verb('Testing', 300),
+ tool(
+ 'Bash',
+ place.test,
+ place.failed,
+ ms: 1800,
+ outcome: ToolOutcome.failed,
+ ),
+ tool('Read', place.file, ['Read 96 lines']),
+ diff(place.file, place.edit),
+ tool('Bash', place.test, [place.passed], ms: 1800),
+ ...finish(
+ 'Fixed the one failure, in `${place.file}` — ${place.passes} now.',
+ ),
+ ];
+ }
+ // Something new to build: a file named for it, wired in where the project's work lives.
+ if (sampleSlug(text) case final slug?) {
+ final ext = place.file.contains('.') ? place.file.split('.').last : 'ts';
+ // At the project's top level (`src/`, `lib/`), not in whatever folder the project's usual
+ // work happens to live: a new feature is not a database file.
+ final dir = place.file.contains('/') ? place.file.split('/').first : 'src';
+ final file = '$dir/$slug.$ext';
+ final camel = slug
+ .split('-')
+ .indexed
+ .map(
+ (part) => part.$1 == 0
+ ? part.$2
+ : '${part.$2[0].toUpperCase()}${part.$2.substring(1)}',
+ )
+ .join();
+ return [
+ ...onIt,
+ tool('Read', place.file, ['Read 96 lines']),
+ tool('Write', file, ['Wrote 42 lines to $file']),
+ diff(place.file, [DiffLine(3, '+', "import { $camel } from './$slug';")]),
+ verb('Testing', 300),
+ tool('Bash', place.test, [place.passed], ms: 1700),
+ ...finish(
+ 'Done — added `$file` and wired it into `${place.file}`; '
+ '${place.passes}.',
+ ),
+ ];
+ }
+ return [
+ ...onIt,
+ tool('Read', place.file, ['Read 96 lines']),
+ diff(place.file, place.edit),
+ verb('Testing', 300),
+ tool('Bash', place.test, [place.passed], ms: 1700),
+ ...finish('Done — changed `${place.file}`, and ${place.passes}.'),
+ ];
+}
diff --git a/mobile/lib/demo/sample_text.dart b/mobile/lib/demo/sample_text.dart
new file mode 100644
index 000000000..69dcf9599
--- /dev/null
+++ b/mobile/lib/demo/sample_text.dart
@@ -0,0 +1,203 @@
+/// Styled text for sample mode's terminals: runs of characters with an SGR style, wrapped to a
+/// pane's width and written out as the escape sequences a real CLI would send.
+///
+/// ⚠️ **Wrapped HERE, never by the terminal.** Every screen a sample harness draws is redrawn in
+/// place — the cursor walks back up over its live region and repaints it — and that walk counts
+/// lines. A line the emulator wrapped by itself would be two rows where the count says one, and the
+/// repaint would land a row low. So nothing longer than [SampleText.fit] columns is ever written.
+library;
+
+/// One run of text in one style. [style] is the SGR parameter list (`1`, `2;36`, `38;5;174`),
+/// empty for the terminal's default.
+class Span {
+ const Span(this.text, [this.style = '']);
+
+ final String text;
+ final String style;
+
+ /// Columns this run takes. Every glyph the sample writes is one column wide; a person's own
+ /// words may not be, and then a line is only wrapped a little early.
+ int get width => text.runes.length;
+}
+
+/// SGR parameter lists the samples use, named for what they draw.
+abstract final class Sgr {
+ static const bold = '1';
+ static const dim = '2';
+ static const red = '31';
+ static const green = '32';
+ static const yellow = '33';
+ static const magenta = '35';
+ static const cyan = '36';
+ static const gray = '38;5;246';
+
+ /// Claude Code's own orange — its spinner and its mark.
+ static const claude = '38;5;174';
+
+ /// A diff's removed and added lines: the colour on a tinted ground, as Claude Code draws them.
+ static const removed = '38;5;217;48;5;52';
+ static const added = '38;5;151;48;5;22';
+}
+
+abstract final class SampleText {
+ /// The widest line ever written to a pane [cols] wide — one short of it, so a line never sits
+ /// in the last column, where an emulator holds a pending wrap that a repaint has to reason about.
+ static int fit(int cols) => cols < 2 ? 1 : cols - 1;
+
+ /// [spans] as one physical line: each run in its style, and the style reset after it.
+ static String ansi(List<Span> spans) {
+ final out = StringBuffer();
+ for (final span in spans) {
+ if (span.text.isEmpty) continue;
+ if (span.style.isEmpty) {
+ out.write(span.text);
+ } else {
+ out
+ ..write('\x1b[${span.style}m')
+ ..write(span.text)
+ ..write('\x1b[0m');
+ }
+ }
+ return out.toString();
+ }
+
+ static int widthOf(List<Span> spans) =>
+ spans.fold(0, (total, span) => total + span.width);
+
+ /// [text] cut to [width] columns, ending in `…` when it was cut.
+ static String clip(String text, int width) {
+ final runes = text.runes.toList();
+ if (runes.length <= width) return text;
+ if (width <= 1) return '…';
+ return '${String.fromCharCodes(runes.take(width - 1))}…';
+ }
+
+ /// [spans] cut to [width] columns — for a line that must stay ONE line, like a box's border.
+ static List<Span> clipSpans(List<Span> spans, int width) {
+ final out = <Span>[];
+ var left = width;
+ for (final span in spans) {
+ if (left <= 0) break;
+ if (span.width <= left) {
+ out.add(span);
+ left -= span.width;
+ } else {
+ out.add(Span(clip(span.text, left), span.style));
+ left = 0;
+ }
+ }
+ return out;
+ }
+
+ /// [spans] padded with spaces to exactly [width] columns (cut when longer).
+ static List<Span> pad(List<Span> spans, int width) {
+ final clipped = clipSpans(spans, width);
+ final gap = width - widthOf(clipped);
+ return gap <= 0 ? clipped : [...clipped, Span(' ' * gap)];
+ }
+
+ /// Word-wraps [spans] into lines no wider than [width], the first starting with [first] and
+ /// every later one with [rest] — a CLI's bullet, then the hanging indent under it.
+ ///
+ /// A word longer than a whole line is broken where the line ends, as a terminal would.
+ static List<String> wrap(
+ List<Span> spans,
+ int width, {
+ List<Span> first = const [],
+ List<Span> rest = const [],
+ }) {
+ final lines = <String>[];
+ var line = <Span>[...first];
+ var used = widthOf(first);
+ var lineStart = used;
+ final restWidth = widthOf(rest);
+ // A line that the indent alone fills would never take a character.
+ if (width <= restWidth || width <= used) width = restWidth + used + 8;
+ // Whether the line being filled is a wrapped one, whose leading spaces are the wrap's.
+ var continued = false;
+
+ void breakLine() {
+ lines.add(ansi(line));
+ line = <Span>[...rest];
+ used = restWidth;
+ lineStart = used;
+ continued = true;
+ }
+
+ // Spaces wait for the word after them: a line never ends in the spaces a break swallowed.
+ Span? gap;
+
+ for (final (blank, word) in _words(spans)) {
+ if (blank) {
+ if (continued && used == lineStart) continue;
+ final space = word.single;
+ gap = Span(
+ '${gap?.text ?? ''}${space.text}',
+ gap?.style ?? space.style,
+ );
+ continue;
+ }
+ final length = widthOf(word);
+ final spaces = gap?.width ?? 0;
+ if (used + spaces + length <= width) {
+ if (gap != null) line.add(gap);
+ used += spaces;
+ gap = null;
+ line.addAll(word);
+ used += length;
+ continue;
+ }
+ if (used > lineStart && length <= width - restWidth) {
+ gap = null;
+ breakLine();
+ line.addAll(word);
+ used += length;
+ continue;
+ }
+ // Too long for any line: broken wherever the line runs out — after the space before it,
+ // which stays where there is room for it and a character after it.
+ if (gap != null && used + spaces < width) {
+ line.add(gap);
+ used += spaces;
+ }
+ gap = null;
+ for (final piece in word) {
+ var runes = piece.text.runes.toList();
+ while (runes.isNotEmpty) {
+ final room = width - used;
+ if (room <= 0) {
+ breakLine();
+ continue;
+ }
+ final take = runes.length < room ? runes.length : room;
+ line.add(Span(String.fromCharCodes(runes.take(take)), piece.style));
+ used += take;
+ runes = runes.sublist(take);
+ }
+ }
+ }
+ if (used > lineStart || lines.isEmpty) lines.add(ansi(line));
+ return lines;
+ }
+
+ static final _tokenPattern = RegExp(r'\s+|\S+');
+
+ /// [spans] as runs of spaces and words, each word whole even where its styles change inside
+ /// it — `(+4 -1)` drawn in three colours is still two words, and neither is broken.
+ static List<(bool, List<Span>)> _words(List<Span> spans) {
+ final words = <(bool, List<Span>)>[];
+ for (final span in spans) {
+ for (final match in _tokenPattern.allMatches(span.text)) {
+ final token = match.group(0)!;
+ final blank = token.trim().isEmpty;
+ final piece = Span(token, span.style);
+ if (!blank && words.isNotEmpty && !words.last.$1) {
+ words.last.$2.add(piece);
+ } else {
+ words.add((blank, [piece]));
+ }
+ }
+ }
+ return words;
+ }
+}
diff --git a/mobile/lib/demo/sample_voice.dart b/mobile/lib/demo/sample_voice.dart
new file mode 100644
index 000000000..7a40d8991
--- /dev/null
+++ b/mobile/lib/demo/sample_voice.dart
@@ -0,0 +1,100 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/phone/voice_recorder.dart';
+
+/// A microphone that records nothing.
+///
+/// Sample mode has no speech service to send audio to, so there is no reason to open the real
+/// microphone — or to ask for it. A take here is a moving meter and a few bytes; what it "said"
+/// is [SampleTranscriber]'s to decide.
+class SampleVoiceRecorder implements VoiceRecorder, VoiceLevelMeter {
+ SampleVoiceRecorder({required this.every});
+
+ /// Where the meter's clock comes from — the sample's, so leaving it stops the meter.
+ final Timer Function(Duration period, void Function() run) every;
+
+ final ValueNotifier<double> _level = ValueNotifier(0);
+ final Random _random = Random(7);
+ Timer? _meter;
+ int _beats = 0;
+
+ @override
+ ValueListenable<double> get level => _level;
+
+ @override
+ Future<bool> allowed() async => true;
+
+ @override
+ Future<void> start() async {
+ _beats = 0;
+ _meter?.cancel();
+ _meter = every(const Duration(milliseconds: 90), () {
+ _beats++;
+ // Speech-shaped: a syllable's rise and fall, with some breath in it.
+ final syllable = (sin(_beats * 0.9) + 1) / 2;
+ _level.value = 0.15 + 0.6 * syllable * (0.6 + 0.4 * _random.nextDouble());
+ });
+ }
+
+ @override
+ Future<VoiceTake?> stop() async {
+ _halt();
+ final length = Duration(milliseconds: max(1200, _beats * 90));
+ return (wav: Uint8List(44), length: length, peak: 12000);
+ }
+
+ @override
+ Future<void> cancel() async => _halt();
+
+ void _halt() {
+ _meter?.cancel();
+ _meter = null;
+ _level.value = 0;
+ }
+
+ @override
+ Future<void> dispose() async {
+ _halt();
+ _level.dispose();
+ }
+}
+
+/// What the sample's voice takes are heard to say: believable things to tell a coding agent, in
+/// turn — or an answer, when the harness on screen is asking something.
+class SampleTranscriber {
+ SampleTranscriber({required this.after, required this.answering});
+
+ /// The sample's clock: [transcribe] answers a moment later, the way a real upload would.
+ final Timer Function(Duration delay, void Function() run) after;
+
+ /// Whether the harness on screen has a question open.
+ final bool Function() answering;
+
+ static const phrases = [
+ 'run the tests and fix whatever fails',
+ 'show me the diff',
+ "what's left on this branch?",
+ 'add a test for the expired token case',
+ 'commit this with a good message',
+ ];
+
+ static const answers = ['yes', 'no, run it against a copy first'];
+
+ int _phrase = 0;
+ int _answer = 0;
+
+ /// How long a take takes to come back.
+ static const delay = Duration(milliseconds: 700);
+
+ Future<String> transcribe() {
+ final done = Completer<String>();
+ final words = answering()
+ ? answers[_answer++ % answers.length]
+ : phrases[_phrase++ % phrases.length];
+ after(delay, () => done.complete(words));
+ return done.future;
+ }
+}
diff --git a/mobile/lib/e2ee/code_pake.dart b/mobile/lib/e2ee/code_pake.dart
new file mode 100644
index 000000000..27d08661d
--- /dev/null
+++ b/mobile/lib/e2ee/code_pake.dart
@@ -0,0 +1,31 @@
+import 'bytes.dart';
+import 'ristretto.dart';
+
+/// core.ts's live-code pairing — the generator and channel binding of the one-time code the desktop
+/// app shows in its "Add phone" QR. The same CPace as the remote password ([password_pake.dart]),
+/// over the code itself: it is random and used once, so there is nothing to stretch.
+
+const _cpaceDsi = 'e2e-cpace-ristretto255-v1';
+
+/// core.ts `pairContext`. The joiner is a `web` client — a full viewer, as a browser was, which is
+/// what the daemon pins it as (`addPaired(…, 'web')`), exactly like a password link.
+String pairContext(String machineId, {String role = 'web'}) =>
+ 'autonomous-e2e-pair|agent:$machineId|a:adapter|b:$role';
+
+/// core.ts `normalizeCode`, exactly: case and separators do not matter, and the letters a person
+/// misreads for digits are folded (I and L to 1, O to 0, U to V). ⚠️ Every mapping must match the
+/// daemon's, or a code holding one of those letters fails as a wrong code.
+String normalizePairCode(String code) => code
+ .toUpperCase()
+ .replaceAll(RegExp(r'[\s\-·_]'), '')
+ .replaceAll('I', '1')
+ .replaceAll('L', '1')
+ .replaceAll('O', '0')
+ .replaceAll('U', 'V');
+
+/// core.ts `cpaceGenerator`: g = hashToGroup(DSI, code, sid, ci).
+RistrettoPoint codeCpaceGenerator(String code, List<int> sid, String ci) =>
+ hashToRistretto255(
+ lvCat([_cpaceDsi, normalizePairCode(code), sid, ci]),
+ utf8Bytes(_cpaceDsi),
+ );
diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart
index 505d71e98..0745e6572 100644
--- a/mobile/lib/main.dart
+++ b/mobile/lib/main.dart
@@ -7,6 +7,9 @@ import 'package:flutter/widgets.dart';
import 'app_shell.dart';
import 'p2p/phone_terminal_p2p.dart';
import 'phone/phone_shell.dart';
+import 'demo/sample_mode.dart';
+import 'phone/welcome/phone_boot.dart';
+import 'phone/welcome/phone_welcome.dart';
/// Harness for iOS and Android: a viewer onto the machines this device has
/// linked, one agent at a time.
@@ -30,6 +33,9 @@ Future<void> main() {
_drawEdgeToEdgeOnEveryAndroid();
return startHarness(
authenticatedScreen: (app) => PhoneShell(notifier: app),
+ signedOutScreen: (app) =>
+ PhoneWelcome(notifier: app, onTrySample: openSampleMode),
+ bootScreen: (_) => const PhoneBoot(),
transportPlugins: phoneTerminalP2p.create,
);
}
diff --git a/mobile/lib/phone/agent_context_line.dart b/mobile/lib/phone/agent_context_line.dart
index 158506572..325ed6299 100644
--- a/mobile/lib/phone/agent_context_line.dart
+++ b/mobile/lib/phone/agent_context_line.dart
@@ -40,7 +40,8 @@ class AgentContextLine extends StatelessWidget {
final machineName = this.machineName;
final place = <InlineSpan>[
if (project != null) TextSpan(text: project!.label),
- if (project != null && branch != null) _separator,
+ // No `·` before the branch: its icon is the separator, as everywhere.
+ if (project != null && branch != null) const TextSpan(text: ' '),
if (branch != null) ...[_branchMark, TextSpan(text: branch)],
];
return Row(
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dart
index a789bd749..282af807a 100644
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@ -2,11 +2,10 @@ import 'dart:async';
import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/logging/startup_trace.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/widgets/empty_state.dart';
+import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
@@ -14,10 +13,17 @@ import 'agent_swipe.dart';
import 'agent_swipe_list.dart';
import 'agents_page.dart' show openNewAgent;
import 'desk_groups.dart';
+import 'link_page.dart';
import 'machines_tab.dart';
-import 'phone_fab.dart';
+import 'tty_controls.dart';
+import 'tty.dart';
+import 'welcome/connect_computer.dart';
+import 'welcome/pairing_with_code.dart';
+import 'welcome/pick_up_page.dart';
+
+import 'package:harness_mobile/demo/sample_mode.dart';
+
import 'phone_header.dart';
-import 'phone_search_button.dart';
import 'phone_status.dart';
/// The phone's home: one agent's terminal, at the ROOT of the stack rather than pushed over a list.
@@ -185,11 +191,16 @@ class _AgentHomeState extends State<AgentHome> {
/// the machine's agent list, and dropping the request then would leave the screen on the old one.
({String machineId, String agentId})? _requestedAgent;
+ /// The welcome ([PickUpPage]) in place of a guessed session: set when this phone has nothing to
+ /// remember, or a computer was just linked; spent the moment a session is picked.
+ bool _welcome = false;
+
void _onAgentRequested() {
final requested = widget.openAgent?.value;
// Null is the shell resetting before it writes, not a request.
if (requested == null) return;
setState(() {
+ _welcome = false;
_requestedAgent = requested;
// A choice made by hand supersedes a jump still pending for a machine.
_awaitingMachine = null;
@@ -203,7 +214,12 @@ class _AgentHomeState extends State<AgentHome> {
// Null is the notifier at rest, not a request to stop waiting for anything — a jump already
// pending stands.
if (requested == null || requested == _awaitingMachine) return;
- setState(() => _awaitingMachine = requested);
+ // A computer just linked: its sessions, and every other, to pick from — not one of them opened
+ // for you.
+ setState(() {
+ _awaitingMachine = requested;
+ _welcome = true;
+ });
}
Future<void> _readLast() async {
@@ -226,6 +242,15 @@ class _AgentHomeState extends State<AgentHome> {
// the screen gave up waiting and opened an agent on its own. Taking the record then would move
// somebody off a terminal they are already looking at, seconds after it opened.
if (last != null && _neighboursFor == null) _showing = last;
+ // Nothing remembered on this phone, not even a tab: open on the sessions to pick from, not a
+ // guessed one. A phone that remembers its tab has been used here before, and gets that tab's
+ // first agent as it always has ([_firstOfLastTab]).
+ if (last == null &&
+ tabId == null &&
+ _neighboursFor == null &&
+ _requestedAgent == null) {
+ _welcome = true;
+ }
});
_restoreDeadline = Timer(_restoreTimeout, () {
if (!mounted) return;
@@ -607,6 +632,19 @@ class _AgentHomeState extends State<AgentHome> {
listenable: widget.notifier,
builder: (context, _) {
AppTheme.watch(context);
+ // Signed in from a scanned "Add phone" QR: once its computer is here and locked, pair with
+ // the QR's code — no password. See `welcome/connect_code.dart`.
+ if (widget.notifier.pendingPairing case final pending?) {
+ final machine = widget.notifier.machineStates[pending.machineId];
+ if (machine != null && machine.needsLink) {
+ return PairingWithCode(
+ key: ValueKey('pairing-${pending.machineId}'),
+ notifier: widget.notifier,
+ machineId: pending.machineId,
+ code: pending.code,
+ );
+ }
+ }
final entries = visibleAgents(agentIndex(widget.notifier));
_openNewAgentIfUnlockedMachineIsEmpty(entries);
_dropPagerIfShownAgentWasDeleted(entries);
@@ -637,12 +675,41 @@ class _AgentHomeState extends State<AgentHome> {
// The Machines TAB itself is untouched and still reachable by every other route; this just
// borrows its body rather than growing a second, drifting copy of the same list.
if (!_anyMachineReady()) {
+ // No computer at all: how to set one up, watching for it to appear. One that is there
+ // but locked or asleep: the machines list, with its password form.
+ if (widget.notifier.machines.isEmpty &&
+ !widget.notifier.machinesLoading) {
+ return ConnectComputerPage(
+ notifier: widget.notifier,
+ onTrySample: openSampleMode,
+ );
+ }
+ // The one computer there is, awake and waiting for its phone password: the unlock
+ // itself, not a list of one to tap through — the moment setup pays off.
+ final only = widget.notifier.machineStates.values
+ .where(
+ (state) => state.machine.authMode == MachineAuthMode.remote,
+ )
+ .toList();
+ if (only.length == 1 &&
+ only.single.needsLink &&
+ only.single.nodeOnline != false) {
+ return LinkPage(
+ notifier: widget.notifier,
+ machineId: only.single.machine.machineId,
+ embedded: true,
+ );
+ }
return MachinesTab(notifier: widget.notifier);
}
_openNewAgentAfterLastOneWent();
return _AgentHomeEmpty(notifier: widget.notifier);
}
- var chosen = (machineId: target.machineId, agentId: target.agent.id);
+ // Nothing remembered, nothing picked: the sessions, each a tap from its terminal.
+ if (_welcome && _neighboursFor == null && _requestedAgent == null) {
+ return PickUpPage(notifier: widget.notifier);
+ }
+ final chosen = (machineId: target.machineId, agentId: target.agent.id);
// ⚠️ **A swipe stays inside one tab, and this is where that happens.** The
// account's tabs are the desk's (`state/phone_desk.dart`); [deskGroups]
// fills each one with the agents of it this phone can reach, and the tab
@@ -672,52 +739,6 @@ class _AgentHomeState extends State<AgentHome> {
final group = isUntabbed(widget.notifier, here)
? untabbedGroup(onScreen ?? target)
: activeDeskGroup(widget.notifier, groups, here);
- // ⚠️ **The swipe list is a snapshot, so it is retaken when the SET of agents changes.** It is
- // taken as the pager opens, and on launch that is as soon as one machine answers — a second
- // machine's agents arriving a moment later never reached it, and a pager built around one
- // agent has no neighbours: nothing to swipe to until the app was restarted. Order changes do
- // not count (see [_neighbours] for why they must not), only agents joining or leaving.
- //
- // ⚠️ The set is the TAB's now, so a tab changing on another computer
- // retakes it too — an agent added to this tab in a window is one swipe
- // away here a moment later, and one closed there stops being reachable.
- //
- // Retaken around the agent ON SCREEN, not the one the pager opened on — the person stays
- // where they are, now with every agent of the tab beside them.
- final snapshot = _neighbours;
- if (snapshot != null &&
- // ⚠️ **Not while the agent on screen is mid-verification.** Its tab's entries are the
- // openable ones, so an agent whose pane is still being looked at is missing from them —
- // the sets differ for that alone, and the retake would rebuild the pager around a list
- // that no longer holds the agent it is showing, landing it on the list's first page.
- _pendingEntryFor(entries, chosen) == null &&
- // ⚠️ **Only while the pager is STAYING where it is.** `target` is the
- // agent the pager opened on for as long as that agent is openable, so
- // anything else means the screen is being moved on purpose — a tab
- // tapped on the strip, an agent picked in search, a machine just
- // unlocked. The set of agents differs from the snapshot then by
- // definition (it is another tab's), and holding onto the agent on
- // screen below would quietly undo the move: the tab would light for
- // a frame and the terminal would stay where it was.
- _neighboursFor == chosen &&
- !_sameAgents(snapshot, group.entries)) {
- final retaken = AgentSwipeList(group.entries);
- // ⚠️ **Handed to the pager already up, not a new pager.** A new list used to mean a new
- // key: the pager and every page in it disposed and built again, the terminal on screen
- // included. On a cold start that happened on EVERY launch — the pager opens on last run's
- // agents before the desk has answered, and the tabs arriving a second or two later cut its
- // list down to one tab's — so the header and the skeleton loaded, then jerked and loaded
- // again. The pager takes the list in place, keeping the page on screen (see
- // `AgentSwipeHost`'s `didUpdateWidget`); a new pager is built only for a list it cannot.
- if (onScreen != null && _pagerTakesInPlace(snapshot, retaken, here)) {
- _neighbours = retaken;
- } else {
- chosen = here;
- _neighboursFor = null;
- _neighbours = null;
- _pagerGeneration++;
- }
- }
// What the phone is in, recorded for the paths that cannot derive it: an
// agent created here joins this tab (`PhoneDesk.adopt`).
widget.notifier.noteDeskTab(group.id);
@@ -773,9 +794,13 @@ class _AgentHomeState extends State<AgentHome> {
notifier: widget.notifier,
machineId: opened.machineId,
agentId: opened.agentId,
- // The tab's agents, so a swipe walks the tab and stops at its ends —
- // see the note above [groups].
- neighbours: _neighbours,
+ // ⚠️ **No neighbours: Focus holds ONE agent, and there is no sideways swipe.** The person
+ // moves with Find, the sheet the handle at the foot of the terminal brings up (see
+ // `docs/plans/2026-09-26-001-mobile-zero-questions.md`). A swipe was hidden — nothing said
+ // it was there or what came next — and it fired by accident while scrolling or typing.
+ // [_neighbours] is still taken for the tab, but only to pick where to land when the agent
+ // on screen is deleted.
+ neighbours: null,
// Told where it has swiped to, so [_showing] follows the pager rather than the pager being
// dragged back to where this screen last put it.
onAgentChanged: _onAgentChanged,
@@ -783,34 +808,6 @@ class _AgentHomeState extends State<AgentHome> {
},
);
- /// Whether [snapshot] holds exactly the openable agents in [entries], in any order.
- static bool _sameAgents(AgentSwipeList snapshot, List<AgentEntry> entries) {
- Set<String> keys(Iterable<AgentEntry> list) => {
- for (final entry in list)
- if (entry.agent.terminalAvailable)
- '${entry.machineId}/${entry.agent.id}',
- };
- final before = keys(snapshot.entries);
- final now = keys(entries);
- return before.length == now.length && before.containsAll(now);
- }
-
- /// Whether the pager already up can take [retaken] in place — keep the page on screen, [here], and
- /// change only the agents beside it — rather than be rebuilt.
- ///
- /// It can while the agent on screen is still in the list and the list pages the same way: a pager
- /// that does not wrap (one agent) numbers its pages differently, so a change of shape needs a
- /// pager of its own. The pager applies the same test and leaves alone a list that fails it — see
- /// `AgentSwipeHost`'s `didUpdateWidget`.
- static bool _pagerTakesInPlace(
- AgentSwipeList snapshot,
- AgentSwipeList retaken,
- ({String machineId, String agentId}) here,
- ) =>
- snapshot.wraps &&
- retaken.wraps &&
- retaken.indexOf(here.machineId, here.agentId) != null;
-
/// Bumped whenever the pager is thrown away and rebuilt, and part of its key.
int _pagerGeneration = 0;
@@ -1081,35 +1078,43 @@ class _AgentHomeEmpty extends StatelessWidget {
// test and this one. Falling back to the machines screen keeps the two in step rather than
// drawing a `+` that cannot fire.
if (ready.isEmpty) return MachinesTab(notifier: notifier);
+ final tty = Tty.of(context);
+ final machine = ready.first.machine;
+ // A computer, and nothing running on it: say so in a line, and the one thing to do — start one.
return Scaffold(
- backgroundColor: AppPalette.windowBg,
- floatingActionButton: PhoneFab(
- icon: LucideIcons.plus300,
- tooltip: 'New Harness',
- // The first machine that can host one. Which machine is the form's first question, and it
- // is changed there.
- onPressed: () =>
- openNewAgent(context, notifier, ready.first.machine.machineId),
- ),
+ backgroundColor: tty.ground,
body: SafeArea(
- bottom: false,
- child: Column(
- children: [
- PhoneHeader(
- large: true,
- title: 'Harnesses',
- trailing: [PhoneSearchButton(notifier: notifier)],
- ),
- const Expanded(
- child: EmptyState(
- icon: LucideIcons.squareTerminal300,
- title: 'No harnesses yet',
- message:
- 'Tap + to start one, or launch a harness from Harness on a '
- 'machine and it will appear here.',
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 16, Tty.origin, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ TtyText(
+ machine.displayName,
+ size: TtySize.meta,
+ color: tty.green,
+ ),
+ const Spacer(),
+ TtyText(
+ 'Nothing running yet.',
+ size: 24,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'Start a harness — an agent on a project on your computer — and '
+ 'watch it work from here. Swipe right any time to find one '
+ 'started elsewhere.',
+ style: tty.style(size: TtySize.row, color: tty.faint),
),
- ),
- ],
+ const Spacer(),
+ TtyPrimaryButton(
+ label: 'Start a harness',
+ onPressed: () =>
+ openNewAgent(context, notifier, machine.machineId),
+ ),
+ ],
+ ),
),
),
);
diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dart
index e54030af6..443559576 100644
--- a/mobile/lib/phone/agent_index.dart
+++ b/mobile/lib/phone/agent_index.dart
@@ -43,8 +43,7 @@ class AgentEntry {
/// of them to the bottom of every list and made them untappable — which,
/// before the app asked for them at all, was invisible. It is visible now.
bool get isOpenable =>
- agent.terminalAvailable ||
- (agent.isStopped && agent.canPauseAndResume);
+ agent.terminalAvailable || (agent.isStopped && agent.canPauseAndResume);
/// When its conversation last moved: the machine's own [Agent.updatedAt], or
/// a turn this app saw since ([MachineState.agentActivityAt]) — whichever is
@@ -132,6 +131,9 @@ List<AgentEntry> recentAgents(List<AgentEntry> entries) => _stableSorted(
/// Then the desktop's tie-breaks: its own focus history (which a phone does not have, so it is
/// skipped), the name as drawn in natural order, and finally the id so two rows never swap.
int compareMonitorOrder(AgentEntry a, AgentEntry b) {
+ // When the conversation last MOVED — the true time (the owner: "use conversation last move, not
+ // last open"). Opening a harness on some app is not work on it, and sorting it up for that put a
+ // glance above the harness that actually just did something.
final activity = (b.agent.updatedAt?.millisecondsSinceEpoch ?? 0).compareTo(
a.agent.updatedAt?.millisecondsSinceEpoch ?? 0,
);
diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dart
index efa7f6e81..91872e064 100644
--- a/mobile/lib/phone/agent_swipe.dart
+++ b/mobile/lib/phone/agent_swipe.dart
@@ -15,6 +15,7 @@ import 'phone_search_catalog.dart' show phoneAgentId;
import 'agent_swipe_list.dart';
import 'terminal_page.dart';
import 'voice_input_controller.dart';
+import 'voice_input_scope.dart';
/// One agent's terminal, with the agents beside it a swipe away.
///
@@ -186,10 +187,15 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
///
/// Transcribes through `notifier.api` read at CALL time, not captured here: the notifier replaces
/// its client when the session changes, and a captured one would sign with a token that is gone.
- late final VoiceInputController _voice = VoiceInputController(
- transcriber: (wav, lang) =>
- widget.notifier.api.transcribeVoice(wav, lang: lang),
- );
+ ///
+ /// A [VoiceInputScope] above the pager makes it instead — sample mode's, which records nothing
+ /// and hears scripted words. Read on first use, in [build], where the scope can be looked up.
+ late final VoiceInputController _voice =
+ VoiceInputScope.maybeOf(context)?.create() ??
+ VoiceInputController(
+ transcriber: (wav, lang) =>
+ widget.notifier.api.transcribeVoice(wav, lang: lang),
+ );
/// Tell the search this agent was reached.
///
@@ -200,9 +206,15 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
/// meant the history stayed nearly empty no matter how much the app was used,
/// and the box kept falling through to its last-resort ordering. A swipe
/// between agents is this app's focus change; this is where it belongs.
- void _rememberVisit(AgentRef agent) => widget.notifier.searchHistory.remember(
- phoneAgentId(agent.machineId, agent.agentId),
- );
+ ///
+ /// And the machine that owns it is told too (`touchAgent`), so the visit is the ACCOUNT'S, not
+ /// only this phone's: every desktop's ⌘P and this phone's Find sort by the same last use.
+ void _rememberVisit(AgentRef agent) {
+ widget.notifier.searchHistory.remember(
+ phoneAgentId(agent.machineId, agent.agentId),
+ );
+ widget.notifier.touchAgent(agent.machineId, agent.agentId);
+ }
@override
void initState() {
@@ -416,6 +428,8 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
voice: _voice,
// Exactly one mounted page, by page number — see [_page].
isActive: i == _page,
+ // The sideways axis is this pager's — see [TerminalPage.sideSwipes].
+ sideSwipes: false,
),
);
},
diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dart
index cbfe77295..29b44f27f 100644
--- a/mobile/lib/phone/agents_page.dart
+++ b/mobile/lib/phone/agents_page.dart
@@ -15,6 +15,7 @@ import 'link_page.dart';
import 'phone_card.dart';
import 'phone_fab.dart';
import 'new_agent_page.dart';
+import 'voice_input_controller.dart';
import 'phone_header.dart';
import 'phone_navigation.dart';
import 'phone_sheet.dart';
@@ -303,7 +304,16 @@ Future<void> showAgentActions(
Future<void> openNewAgent(
BuildContext context,
AppNotifier notifier,
- String machineId,
-) => Navigator.of(context).push(
- phoneRoute((_) => NewAgentPage(notifier: notifier, machineId: machineId)),
+ String machineId, {
+ String? folder,
+ VoiceInputController? voice,
+}) => Navigator.of(context).push(
+ phoneRoute(
+ (_) => NewAgentPage(
+ notifier: notifier,
+ machineId: machineId,
+ folder: folder,
+ voice: voice,
+ ),
+ ),
);
diff --git a/mobile/lib/phone/desk_add_agent_sheet.dart b/mobile/lib/phone/desk_add_agent_sheet.dart
deleted file mode 100644
index 3e3a29e71..000000000
--- a/mobile/lib/phone/desk_add_agent_sheet.dart
+++ /dev/null
@@ -1,476 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/widgets/engine_identity.dart';
-
-import 'agent_context_line.dart';
-import 'agent_index.dart';
-import 'phone_status.dart';
-import 'status_pill.dart';
-
-/// What joins a tab: an agent the account already has, or one made now.
-///
-/// ```
-/// ──────────────────────────────────
-/// New tab
-/// ▭ Macbook Pro 2 harnesses
-/// ┌──────────────────────────────┐
-/// │ ✳ api-3 │
-/// │ ◌ Working… · app ⑂ main │
-/// │ ────────────────────────── │
-/// │ ✳ docs │
-/// │ ● Claude Code · site │
-/// └──────────────────────────────┘
-/// ──────────────────────────────────
-/// [ + New Harness ]
-/// ```
-///
-/// ⚠️ **Grouped under a heading per machine, and the machine is not on the
-/// rows.** A row that carried its machine at the end of the context line lost
-/// it to the ellipsis first — `claude-2026-09-2… · Macbook Pro - …` — which
-/// is the one fact that tells two agents of the same folder apart. On the
-/// heading it is written once, in full, and the row's second line goes to what
-/// it is doing and where.
-///
-/// ⚠️ **"New Harness" is pinned under the list, not the first row of it.**
-/// Both `+`s on the tabs panel land here, and the common move is to put
-/// something already running into the tab — so the agents keep the scrolling
-/// space, and making one is a button that is in the same place under the thumb
-/// however far the list has been scrolled.
-///
-/// [choices] is what this sheet may offer: for a tab, the agents it does not
-/// already hold. An empty list is drawn as a sentence rather than as a hole —
-/// an account whose every agent is already in the tab has nothing to pick, and
-/// the "New Harness" button under it still works.
-///
-/// [onCreate] is null where no machine can host one (all asleep, or wanting a
-/// password), which leaves the button out rather than drawn dead.
-Future<void> showDeskAddAgentSheet(
- BuildContext context, {
- required String title,
- required List<AgentEntry> choices,
- required void Function(AgentEntry entry) onPick,
- required VoidCallback? onCreate,
-}) => showModalBottomSheet<void>(
- context: context,
- useRootNavigator: true,
- showDragHandle: true,
- backgroundColor: AppPalette.panelBg,
- isScrollControlled: true,
- builder: (sheetContext) => _AddAgentSheet(
- title: title,
- choices: choices,
- // Closed first, then acted on — the same order every row in the tabs panel
- // takes, so a terminal this opens never arrives under a sheet still on its
- // way out.
- onPick: (entry) {
- Navigator.of(sheetContext).pop();
- onPick(entry);
- },
- onCreate: onCreate == null
- ? null
- : () {
- Navigator.of(sheetContext).pop();
- onCreate();
- },
- ),
-);
-
-/// The rows' side inset: `phoneListPadding`'s 16, the measure the tabs panel
-/// gives its own rows.
-const double _sideInset = 16;
-
-/// A row's inner padding, left and right.
-const double _rowInset = 14;
-
-/// The box the engine mark sits in, and the gap after it — together with
-/// [_rowInset], where a row's text starts and so where the hairline between two
-/// rows starts too.
-const double _markBox = 22;
-const double _markGap = 12;
-
-/// "Working…" as ink on a row, not [phoneToneColor]'s busy tone.
-///
-/// That tone is [AppPalette.accent], which is made to be a FILL under white
-/// text: on the dark row fill (#202020) it is 2.95:1 as a 12.5pt label, under
-/// the 4.5:1 floor. Lightened in dark to 6.9:1, still the same indigo; light
-/// keeps the accent, which already clears it there (5.0:1 on #F3F3F2).
-Color get _busyInk => AppTheme.pick(AppPalette.accent, const Color(0xFF8AA4FF));
-
-class _AddAgentSheet extends StatelessWidget {
- const _AddAgentSheet({
- required this.title,
- required this.choices,
- required this.onPick,
- required this.onCreate,
- });
-
- final String title;
- final List<AgentEntry> choices;
- final void Function(AgentEntry entry) onPick;
- final VoidCallback? onCreate;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final onCreate = this.onCreate;
- return SafeArea(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(_sideInset, 2, _sideInset, 14),
- child: Text(
- title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 17,
- fontWeight: FontWeight.w600,
- ),
- ),
- ),
- // One height, as the tabs panel keeps one, and for the same reason:
- // the sheet must not stand up and sit down as one account's three
- // agents give way to another's dozen.
- SizedBox(
- height: MediaQuery.sizeOf(context).height * 0.5,
- child: choices.isEmpty ? const _Empty() : _machineList(),
- ),
- if (onCreate != null) _NewHarnessBar(onTap: onCreate),
- ],
- ),
- );
- }
-
- Widget _machineList() {
- final groups = _byMachine(choices);
- return ListView(
- padding: const EdgeInsets.fromLTRB(_sideInset, 0, _sideInset, 16),
- children: [
- for (final (index, group) in groups.indexed) ...[
- if (index > 0) const SizedBox(height: 20),
- _MachineHeading(name: group.first.machineName, count: group.length),
- _MachineGroup(entries: group, onPick: onPick),
- ],
- ],
- );
- }
-}
-
-/// [entries] split by machine, the machines in the order their first agent
-/// comes and each machine's agents in the order they came.
-///
-/// [choices] arrives in [visibleAgents] order — waiting, then working, then the
-/// rest — so the machine with an agent waiting on the person heads the sheet,
-/// and inside every group that same order still holds.
-List<List<AgentEntry>> _byMachine(List<AgentEntry> entries) {
- final groups = <String, List<AgentEntry>>{};
- for (final entry in entries) {
- (groups[entry.machineId] ??= []).add(entry);
- }
- return groups.values.toList();
-}
-
-/// The line over one machine's agents: the machine, named in full, and how many
-/// of its agents this sheet offers.
-class _MachineHeading extends StatelessWidget {
- const _MachineHeading({required this.name, required this.count});
-
- final String name;
- final int count;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(4, 0, 4, 8),
- child: Row(
- children: [
- Icon(
- LucideIcons.laptopMinimal300,
- size: 15,
- color: AppPalette.textSecondary,
- ),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 13,
- fontWeight: FontWeight.w600,
- ),
- ),
- ),
- const SizedBox(width: 8),
- Text(
- count == 1 ? '1 harness' : '$count harnesses',
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 12.5,
- fontWeight: FontWeight.w500,
- fontFeatures: AppFont.tabularFigures,
- ),
- ),
- ],
- ),
- );
- }
-}
-
-/// One machine's agents as a single rounded group, a hairline between rows —
-/// one object per machine rather than a card per agent, so the list reads as
-/// machines holding agents.
-class _MachineGroup extends StatelessWidget {
- const _MachineGroup({required this.entries, required this.onPick});
-
- final List<AgentEntry> entries;
- final void Function(AgentEntry entry) onPick;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final radius = BorderRadius.circular(AppCard.radius);
- return Container(
- clipBehavior: Clip.antiAlias,
- decoration: BoxDecoration(color: AppGlass.rowFill, borderRadius: radius),
- // The rim drawn OVER the rows, so a pressed row's fill runs to the
- // group's edge without covering it.
- foregroundDecoration: BoxDecoration(
- borderRadius: radius,
- border: Border.all(color: AppGlass.hair),
- ),
- child: Column(
- children: [
- for (final (index, entry) in entries.indexed) ...[
- if (index > 0)
- Padding(
- padding: const EdgeInsets.only(
- left: _rowInset + _markBox + _markGap,
- ),
- child: Container(height: 1, color: AppPalette.divider),
- ),
- _AgentRow(
- key: deskAddAgentRowKey(entry.agent.id),
- entry: entry,
- onTap: () => onPick(entry),
- ),
- ],
- ],
- ),
- );
- }
-}
-
-/// The key of [agentId]'s row in this sheet — what a test finds it by, since
-/// the row itself is private.
-Key deskAddAgentRowKey(String agentId) => ValueKey('desk-add-agent:$agentId');
-
-/// One agent: its engine, its name, and — on one line — what it is doing, the
-/// folder and the branch. Its machine is the heading above it.
-///
-/// An agent with no terminal is drawn dimmed and does not open, as
-/// `AgentTile` draws one — the tabs panel only offers agents that have one, so
-/// this is the rule kept, not a state the sheet expects to show.
-class _AgentRow extends StatefulWidget {
- const _AgentRow({super.key, required this.entry, required this.onTap});
-
- final AgentEntry entry;
- final VoidCallback onTap;
-
- @override
- State<_AgentRow> createState() => _AgentRowState();
-}
-
-class _AgentRowState extends State<_AgentRow> {
- bool _pressed = false;
-
- bool get _openable => widget.entry.agent.terminalAvailable;
-
- void _press(bool pressed) {
- if (!_openable || _pressed == pressed) return;
- setState(() => _pressed = pressed);
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final agent = widget.entry.agent;
- return GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTapDown: (_) => _press(true),
- onTapUp: (_) => _press(false),
- onTapCancel: () => _press(false),
- onTap: _openable ? widget.onTap : null,
- child: AnimatedContainer(
- duration: AppMotion.press,
- curve: AppMotion.curve,
- color: _pressed ? AppGlass.rowHoverFill : AppGlass.rowFill,
- padding: const EdgeInsets.symmetric(
- horizontal: _rowInset,
- vertical: 10,
- ),
- child: Opacity(
- opacity: _openable ? 1 : 0.55,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- // Down a point, so the mark sits on the name's line rather than
- // above it.
- Padding(
- padding: const EdgeInsets.only(top: 1),
- child: SizedBox.square(
- dimension: _markBox,
- child: Center(
- child: EngineMark(
- engine: agent.engine,
- displayName: agent.engineDisplayName,
- size: 20,
- ),
- ),
- ),
- ),
- const SizedBox(width: _markGap),
- Expanded(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- agent.displayName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 15.5,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- _StatusLine(entry: widget.entry),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
-
-/// `◌ Working… · harness ⑂ main` — the status first, then [AgentContextLine]
-/// without its machine.
-///
-/// ⚠️ **The label keeps its width and the place gives way.** The label is one
-/// of a few short words, and it is the part a glance at the sheet is for; the
-/// folder and branch ellipsise inside what is left, the branch first — see
-/// [AgentContextLine]. The label is still capped, so an engine with a long name
-/// cannot push the place off the row entirely.
-class _StatusLine extends StatelessWidget {
- const _StatusLine({required this.entry});
-
- final AgentEntry entry;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final summary = entry.summary;
- final project = entry.project;
- final (color, weight) = switch (summary.tone) {
- PhoneTone.busy => (_busyInk, FontWeight.w500),
- PhoneTone.attention => (AppPalette.warn, FontWeight.w600),
- PhoneTone.quiet => (AppPalette.textSecondary, FontWeight.w500),
- PhoneTone.good ||
- PhoneTone.bad => (phoneToneColor(summary.tone), FontWeight.w500),
- };
- return Row(
- children: [
- StatusDot(
- summary: summary,
- spinnerColor: summary.tone == PhoneTone.busy ? _busyInk : null,
- ),
- const SizedBox(width: 6),
- ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 150),
- child: Text(
- summary.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(color: color, fontSize: 12.5, fontWeight: weight),
- ),
- ),
- if (project != null) ...[
- Text(
- ' · ',
- style: TextStyle(color: AppPalette.textFaint, fontSize: 12.5),
- ),
- Flexible(child: AgentContextLine(project: project)),
- ],
- ],
- );
- }
-}
-
-/// Nothing left to offer: every agent this phone can open is in the tab
-/// already. Said in the list's own space, so the button under it stays where it
-/// always is.
-class _Empty extends StatelessWidget {
- const _Empty();
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(_sideInset + 4, 8, _sideInset + 4, 0),
- child: Text(
- 'Every harness this phone can open is already here.',
- style: TextStyle(color: AppPalette.textSecondary, fontSize: 13.5),
- ),
- );
- }
-}
-
-/// "New Harness", the sheet's one filled button — the app's primary action,
-/// drawn as the form it opens draws "Create Harness": the same fill, radius and
-/// 44pt height, so the two read as one flow.
-class _NewHarnessBar extends StatelessWidget {
- const _NewHarnessBar({required this.onTap});
-
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return DecoratedBox(
- decoration: BoxDecoration(
- border: Border(top: BorderSide(color: AppPalette.divider)),
- ),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(_sideInset, 12, _sideInset, 8),
- child: SizedBox(
- height: 44,
- child: FilledButton.icon(
- style: FilledButton.styleFrom(
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AppCard.radius),
- ),
- ),
- onPressed: onTap,
- icon: const Icon(LucideIcons.plus, size: 18),
- label: const Text(
- 'New Harness',
- style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/desk_tab_rename_dialog.dart b/mobile/lib/phone/desk_tab_rename_dialog.dart
deleted file mode 100644
index 509027fc1..000000000
--- a/mobile/lib/phone/desk_tab_rename_dialog.dart
+++ /dev/null
@@ -1,89 +0,0 @@
-import 'package:flutter/material.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/widgets/app_dialog.dart';
-import 'package:harness_mobile/state/app_state.dart';
-
-/// Rename a tab, from a double tap on its name in the tabs panel.
-///
-/// ⚠️ **It writes and closes; it does not wait to be told it worked.** A tab
-/// name is not the CLI's to refuse the way an agent's is (see
-/// [showAgentRenameDialog], which shows the machine's answer under the field):
-/// the desk takes the op, every computer on the account picks it up, and this
-/// phone has already drawn the new name over its own copy — see
-/// [PhoneDesk.renameTab]. A dialog held open for a round trip would sit there
-/// on a phone in a lift for no reason.
-Future<void> showDeskTabRenameDialog(
- BuildContext context,
- AppNotifier notifier, {
- required String tabId,
- required String currentName,
-}) => showAppDialog<void>(
- context: context,
- builder: (_) => _RenameTabDialog(
- notifier: notifier,
- tabId: tabId,
- currentName: currentName,
- ),
-);
-
-/// ⚠️ A widget that OWNS its controller — see the note in
-/// `widgets/rename_agent_dialog.dart` for the red screen the other shape
-/// caused.
-class _RenameTabDialog extends StatefulWidget {
- const _RenameTabDialog({
- required this.notifier,
- required this.tabId,
- required this.currentName,
- });
-
- final AppNotifier notifier;
- final String tabId;
- final String currentName;
-
- @override
- State<_RenameTabDialog> createState() => _RenameTabDialogState();
-}
-
-class _RenameTabDialogState extends State<_RenameTabDialog> {
- late final _controller = TextEditingController(text: widget.currentName)
- // The name is there to be replaced, not to be typed around: selected, the
- // first key wipes it, and a thumb that meant to edit still has the caret.
- ..selection = TextSelection(
- baseOffset: 0,
- extentOffset: widget.currentName.length,
- );
-
- @override
- void dispose() {
- _controller.dispose();
- super.dispose();
- }
-
- void _submit() {
- widget.notifier.renameDeskTab(widget.tabId, _controller.text);
- Navigator.of(context).pop();
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return AlertDialog(
- title: const Text('Rename tab'),
- content: TextField(
- controller: _controller,
- autofocus: true,
- style: kFieldTextStyle,
- textInputAction: TextInputAction.done,
- onSubmitted: (_) => _submit(),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('Cancel'),
- ),
- FilledButton(onPressed: _submit, child: const Text('Save')),
- ],
- );
- }
-}
diff --git a/mobile/lib/phone/desk_tab_strip.dart b/mobile/lib/phone/desk_tab_strip.dart
deleted file mode 100644
index 85ba25fef..000000000
--- a/mobile/lib/phone/desk_tab_strip.dart
+++ /dev/null
@@ -1,396 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/services.dart';
-import 'package:flutter/widgets.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/notify/agent_notice.dart';
-import 'package:harness_mobile/notify/unread_marks.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-
-import 'desk_groups.dart';
-import 'sheet_list.dart';
-
-/// The account's tabs as a row of pills, the one being shown filled in.
-///
-/// ```
-/// (▓Desktop▓) ( Docker ) ( Other ) (+)
-/// ```
-///
-/// It lives at the top of the tabs panel — see [DeskTabsPanel] — and picks
-/// which tab's agents the list under it holds. Nothing here opens an agent: the
-/// pill changes what is offered, the row below is what is chosen.
-///
-/// ⚠️ **Pills, not names over an underline.** The sheet around this is drawn
-/// the way iOS draws its own — a filled search bar, an inset-grouped list —
-/// and a bar under a word is Material's tab. A filled pill says "this one" at
-/// the weight of the list it picks, rather than in a 2pt line under it.
-///
-/// ⚠️ **A tab with nothing this phone can open is drawn dim, but still picked.**
-/// Its agents are on a machine that is asleep or wants its password. Dropping it
-/// from the row would read as a tab somebody deleted, and refusing the tap would
-/// leave the person tapping a name that never answers — picked, it says what is
-/// wrong in the space below, where there is room for the sentence.
-///
-/// ⚠️ **It scrolls, and the tab being shown is scrolled TO.** A desk of a dozen
-/// tabs is wider than a phone, and the one you are in is as likely to be the
-/// tenth as the first — opened at the left-hand end, the panel would say
-/// nothing about where you are until a thumb went looking. See
-/// [_DeskTabStripState._reveal].
-class DeskTabStrip extends StatefulWidget {
- const DeskTabStrip({
- super.key,
- required this.groups,
- required this.selectedId,
- required this.onPick,
- this.onAddTab,
- this.onRename,
- this.unreadFor,
- });
-
- /// Every tab, in the desk's own order — see [deskGroups]. Never empty.
- final List<DeskGroup> groups;
-
- /// [DeskGroup.id] of the tab whose agents are listed below. Null is the
- /// single group of a phone with no desk.
- final String? selectedId;
-
- final void Function(DeskGroup group) onPick;
-
- /// A tab of its own for an agent picked or made now. Null leaves the `+`
- /// undrawn — a desk that cannot be written to has nothing for it to do; see
- /// [AppNotifier.deskWritable].
- final VoidCallback? onAddTab;
-
- /// A name double-tapped. Called only for the groups that are real tabs on a
- /// desk this phone may write to.
- final void Function(DeskGroup group)? onRename;
-
- /// The news the agents of a tab carry that nobody has gone to yet — see
- /// `AgentUnread.mostUrgentOf`. Drawn as the rows' own [UnreadDot] before the
- /// tab's name: an agent finishing in a tab you are not reading has to say
- /// which tab it is in, or the dot is only found by opening every one of them.
- /// Null draws no marks.
- final NoticeKind? Function(DeskGroup group)? unreadFor;
-
- /// The row's height: a 32pt pill with 6pt either side of it, which a tap
- /// still lands in — a pill is short for a thumb, the row around it is not.
- static const double height = 44;
-
- /// The sheet's one side inset — see [kSheetInset] — so the first pill starts
- /// on the field's edge and the group's.
- static const double sideInset = kSheetInset;
-
- /// The gap between two pills: their outlines already part them, so this
- /// only has to keep two of them from reading as one wide one.
- static const double _gap = 8;
-
- @override
- State<DeskTabStrip> createState() => _DeskTabStripState();
-}
-
-class _DeskTabStripState extends State<DeskTabStrip> {
- /// Rides whichever pill is the selected one, so the row can be scrolled to
- /// it without knowing how wide any of the others are — pills keep their
- /// names' own widths, so there is no index-times-extent to jump to.
- final _selected = GlobalKey();
-
- @override
- void initState() {
- super.initState();
- // The panel is on its way up as this runs: no animation, because there is
- // nothing yet for a scroll to be seen moving against.
- WidgetsBinding.instance.addPostFrameCallback((_) => _reveal(Duration.zero));
- }
-
- @override
- void didUpdateWidget(DeskTabStrip old) {
- super.didUpdateWidget(old);
- // A tab picked by hand is already under the thumb; this is for the ones
- // picked by something else — a tab made by the `+`, which lands at the far
- // right of a row that was not scrolled there.
- if (old.selectedId != widget.selectedId) {
- WidgetsBinding.instance.addPostFrameCallback(
- (_) => _reveal(const Duration(milliseconds: 220)),
- );
- }
- }
-
- /// Scrolls the row until the selected name sits in its middle.
- ///
- /// ⚠️ **The row's own scroll, and nothing above it.** `Scrollable.ensureVisible`
- /// walks every scrollable the name sits in, and this row sits inside the
- /// terminal page now — inside the pager that swipes between agents (see
- /// [DeskTabsPanel]). Centring a name there would drag the pager part of a
- /// page sideways, off the agent on screen.
- void _reveal(Duration duration) {
- final context = _selected.currentContext;
- if (context == null || !mounted) return;
- final name = context.findRenderObject();
- final row = Scrollable.maybeOf(context);
- if (name == null || !name.attached || row == null) return;
- unawaited(
- row.position.ensureVisible(
- name,
- // Centred rather than merely brought inside the edge: a name flush
- // against the right-hand end reads as the last tab there is.
- alignment: 0.5,
- duration: duration,
- curve: Curves.easeOutCubic,
- ),
- );
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final groups = widget.groups;
- final selectedId = widget.selectedId;
- final onPick = widget.onPick;
- final onAddTab = widget.onAddTab;
- final onRename = widget.onRename;
- const sideInset = DeskTabStrip.sideInset;
- const height = DeskTabStrip.height;
- const gap = DeskTabStrip._gap;
- return SizedBox(
- height: height,
- child: Row(
- children: [
- Expanded(
- // Scrolls, because a desk can carry more tabs than a phone is wide.
- // The names keep their own widths — nothing is squeezed to make a
- // row fit, which is what turns tab names into `Deskt…`, `Dock…`.
- child: ListView.separated(
- scrollDirection: Axis.horizontal,
- padding: EdgeInsets.only(
- left: sideInset,
- // A full inset only where the row ends in nothing. Beside the
- // `+`, the button's own margin is the gap, and a pill stopping
- // an inset short of it as well reads as a row that ran out
- // rather than one that scrolls.
- right: onAddTab == null ? sideInset : 0,
- ),
- itemCount: groups.length,
- separatorBuilder: (context, index) => const SizedBox(width: gap),
- itemBuilder: (context, index) {
- final group = groups[index];
- final selected = group.id == selectedId;
- return _DeskTabPill(
- key: selected ? _selected : null,
- name: group.name,
- selected: selected,
- reachable: !group.isEmpty,
- unread: widget.unreadFor?.call(group),
- onTap: () => onPick(group),
- // ⚠️ **Only the tab being SHOWN can be double-tapped, and
- // that is a decision about the other tabs rather than about
- // this one.** A name that has to wait and see whether a
- // second tap is coming answers the first one 300ms late —
- // and on every other name that first tap is the switch
- // itself, which is the one thing on this row that has to
- // feel immediate. On the tab already open the tap does
- // nothing anyway, so the wait costs nothing.
- //
- // Null too for the no-desk group and on a desk with no
- // writes — see [DeskTabStrip.onRename].
- onRename: onRename == null || group.id == null || !selected
- ? null
- : () => onRename(group),
- );
- },
- ),
- ),
- // ⚠️ **Pinned beside the names, not carried at the end of them.** The
- // row scrolls, and a `+` that scrolls with it is a control that goes
- // away exactly when the desk is big enough to want another tab. Out
- // here it is always the rightmost thing on the row — which is also
- // what says it belongs to the row rather than to the list below.
- if (onAddTab != null) _AddTabButton(onTap: onAddTab),
- ],
- ),
- );
- }
-}
-
-/// The `+` that opens a tab: a round pill of its own at the end of the row.
-///
-/// ⚠️ **An icon alone, and it can be, because of where it stands.** The other
-/// `+` on this panel — the one that adds an agent to the tab being read — is a
-/// row down in the list, carrying the words. Two bare `+`s would be a guess; a
-/// pill among the tab pills and a labelled row in the agent list are two
-/// different things before either is read. See [DeskTabsPanel].
-class _AddTabButton extends StatelessWidget {
- const _AddTabButton({required this.onTap});
-
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Semantics(
- button: true,
- label: 'New tab',
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () {
- HapticFeedback.selectionClick();
- onTap();
- },
- child: Padding(
- // The gap to the last pill on the inside and the strip's inset on the
- // outside are both the button's: a 32pt circle is a small target,
- // and the row around it is what the thumb actually lands in.
- padding: const EdgeInsets.only(
- left: DeskTabStrip._gap,
- right: DeskTabStrip.sideInset,
- ),
- child: Center(
- child: Container(
- width: _DeskTabPill.height,
- height: _DeskTabPill.height,
- alignment: Alignment.center,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- border: Border.all(color: AppGlass.hair),
- ),
- child: Icon(
- LucideIcons.plus,
- size: 16,
- color: AppPalette.textSecondary,
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-/// One tab in the row: an outlined pill, filled in while it is the tab being
-/// shown.
-class _DeskTabPill extends StatelessWidget {
- const _DeskTabPill({
- super.key,
- required this.name,
- required this.selected,
- required this.reachable,
- required this.unread,
- required this.onTap,
- required this.onRename,
- });
-
- final String name;
- final bool selected;
-
- /// What its agents are carrying — see [DeskTabStrip.unreadFor].
- final NoticeKind? unread;
-
- /// False for a tab whose agents are all out of reach — drawn dim, and still
- /// pickable. See [DeskTabStrip].
- final bool reachable;
-
- final VoidCallback onTap;
-
- /// A double tap on the pill. Null on the groups that cannot be renamed, and
- /// that is worth more than a dead callback would be: a pill with no
- /// double-tap recognizer answers a SINGLE tap at once, while one that has to
- /// wait and see whether a second is coming answers it 300ms later. So the
- /// tabs that cannot be renamed keep the snappier tap.
- final VoidCallback? onRename;
-
- static const double height = 32;
-
- /// The longest a name is drawn before it ellipsises. Far wider than any
- /// name a tab is usually given — the row scrolls, and names keep their own
- /// widths — but a name pasted in whole must not make one pill wider than
- /// the phone.
- static const double _maxLabelWidth = 220;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- // The tab being shown is filled in the ink the names are written in, with
- // its name cut out of it in the sheet's own colour. One out of reach keeps
- // that shape a step dimmer: it is still the tab you are in while you read
- // why it is empty.
- final fill = !selected
- ? const Color(0x00000000)
- : reachable
- ? AppPalette.textPrimary
- : AppPalette.textSecondary;
- final ink = selected
- ? sheetFill
- : reachable
- ? AppPalette.textSecondary
- : AppPalette.textFaint;
- return Semantics(
- button: true,
- selected: selected,
- child: GestureDetector(
- // Opaque, so the whole height of the row either side of the pill takes
- // the tap — see [DeskTabStrip.height].
- behavior: HitTestBehavior.opaque,
- onTap: _tapped,
- onDoubleTap: onRename == null ? null : _renamed,
- child: Center(
- child: AnimatedContainer(
- duration: AppMotion.swap,
- curve: AppMotion.curve,
- height: height,
- padding: const EdgeInsets.symmetric(horizontal: 14),
- alignment: Alignment.center,
- decoration: BoxDecoration(
- color: fill,
- borderRadius: BorderRadius.circular(height / 2),
- border: Border.all(color: selected ? fill : AppGlass.hair),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- // ⚠️ Before the name here, where the agent rows below put it at
- // their far end — see [UnreadDot]. A pill is read as one thing,
- // so the mark belongs to it wherever it sits; a column of rows
- // is not, and a leading dot there moved every name.
- //
- // The gap is the caller's: the dot carries no margin, because
- // the two placements need it on opposite sides.
- if (unread case final kind?)
- Padding(
- padding: const EdgeInsets.only(right: 7),
- child: UnreadDot(kind: kind),
- ),
- ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: _maxLabelWidth),
- child: Text(
- name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: ink,
- fontSize: 14.5,
- // The tab being shown is a weight heavier as well as
- // filled, which is what carries it to someone who cannot
- // see the fill — the same pairing [PhoneTabBar] uses
- // below.
- fontWeight: selected ? FontWeight.w600 : FontWeight.w500,
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-
- void _tapped() {
- HapticFeedback.selectionClick();
- onTap();
- }
-
- void _renamed() {
- HapticFeedback.selectionClick();
- onRename?.call();
- }
-}
diff --git a/mobile/lib/phone/desk_tabs_panel.dart b/mobile/lib/phone/desk_tabs_panel.dart
deleted file mode 100644
index b79625867..000000000
--- a/mobile/lib/phone/desk_tabs_panel.dart
+++ /dev/null
@@ -1,611 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
-import 'package:harness_mobile/notify/agent_notice.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/state/app_state.dart';
-
-import 'agent_index.dart';
-import 'agents_page.dart' show openNewAgent;
-import 'desk_add_agent_sheet.dart';
-import 'desk_groups.dart';
-import 'desk_tab_rename_dialog.dart';
-import 'desk_tab_strip.dart';
-import 'phone_navigation.dart';
-import 'phone_status.dart';
-import 'sheet_agent_lines.dart';
-import 'sheet_list.dart';
-
-/// The account's tabs, and the agents inside the one being read — what the
-/// terminal's search sheet shows under its field until the field is focused.
-///
-/// ```
-/// (▓Desktop▓) ( Docker ) ( Other ) (+)
-/// DESKTOP 2
-/// ╭────────────────────────────────╮
-/// │ ▣ api-3 ◌ › │
-/// │ harness · ⑂ main · Mac mini │
-/// │ ────────────────────────────│
-/// │ + Add harness to this tab │
-/// ╰────────────────────────────────╯
-/// ```
-///
-/// ⚠️ **Two moves, not one.** A tab's pill changes which agents the list below
-/// offers and nothing else; opening happens on a row. That is what lets
-/// somebody look into another tab — see what is running there — without losing
-/// the terminal they are in, which a sheet of tab names could not do.
-///
-/// ⚠️ **Under the search field, not behind a mark of its own.** This was a
-/// sheet of its own, opened from a grid mark in the terminal header, beside a
-/// search that was a second screen. Finding an agent by where it is and finding
-/// it by name are one errand, so they are one sheet now, opened from the
-/// floating Search button and reading the tabs until something is typed — see
-/// [TerminalSearchOverlay].
-///
-/// ⚠️ **The agents scroll DOWN, in one inset group.** They were cards side by
-/// side, which put a scroll across the panel at right angles to the one every
-/// other list here has — and made a phone read four agents through a
-/// letterbox. They were then the Agents tab's own cards ([AgentTile]), until
-/// it showed that the search replacing them in place drew the same agents as
-/// flat lines: focusing the field swapped one look for another. Both are
-/// [SheetRow]s now — see [DeskAgentRow].
-///
-/// ⚠️ **It fills the height it is given, and the sheet around it gives one
-/// height whatever the tab holds.** Sized to its contents, the panel stood up
-/// and sat down as tabs were read — a tab of one agent, then a tab of six — and
-/// the pills along the top moved with it, so the next tab was somewhere else by
-/// the time the thumb got there.
-class DeskTabsPanel extends StatefulWidget {
- const DeskTabsPanel({
- super.key,
- required this.notifier,
- required this.onOpen,
- required this.onClose,
- this.showing,
- });
-
- /// ⚠️ **The groups are rebuilt from here on every change, not passed in
- /// once.** An agent added to a tab from this panel has to appear in it while
- /// the panel is still open — a list computed before the panel was shown
- /// answered a tap by doing nothing visible at all.
- final AppNotifier notifier;
-
- /// A row tapped: the agent, and the tab it was picked out of — what
- /// [openDeskAgent] takes.
- ///
- /// ⚠️ The caller puts the panel away FIRST: a terminal arriving under a panel
- /// still on its way out is the order every sheet here avoids.
- final void Function(DeskGroup group, AgentEntry entry) onOpen;
-
- /// Puts the panel away without opening anything here — for the paths that
- /// leave it for another screen, the new-agent form.
- final VoidCallback onClose;
-
- /// The agent on screen: it decides which tab the panel opens on (see
- /// [activeDeskGroup]), and its row is the one wearing the check. Null opens
- /// on the tab the phone was last in, and checks nothing.
- final AgentRef? showing;
-
- @override
- State<DeskTabsPanel> createState() => _DeskTabsPanelState();
-}
-
-class _DeskTabsPanelState extends State<DeskTabsPanel> {
- /// The tab being read: at first the one the agent on screen belongs to.
- ///
- /// ⚠️ Kept by this state and nothing above it, so a panel that stays built
- /// while something covers it comes back on the tab that was being read — see
- /// [TerminalSearchOverlay], which keeps it built under the results.
- late String? _selectedId = activeDeskGroup(
- widget.notifier,
- _groups,
- widget.showing,
- ).id;
-
- List<DeskGroup> get _groups =>
- deskGroups(widget.notifier, visibleAgents(agentIndex(widget.notifier)));
-
- /// The tab being read. Falls back to the first, which is only reachable if
- /// the desk dropped a tab while the panel was open.
- DeskGroup _groupIn(List<DeskGroup> groups) =>
- groups.where((group) => group.id == _selectedId).firstOrNull ??
- groups.first;
-
- /// Whether [group] can take another agent: a real tab on a desk this phone
- /// may write to. The single group a phone with no desk shows is not a tab —
- /// there is nothing to add an agent TO.
- bool _canAddTo(DeskGroup group) =>
- group.id != null && widget.notifier.deskWritable;
-
- /// Whether [group] is the single one a phone with no desk shows.
- ///
- /// It takes a row of its own rather than [_canAddTo]'s: there is no tab to
- /// add an agent TO, but a new harness can still be started from it.
- bool _canStartUntabbed(DeskGroup group) =>
- group.id == null && _hostMachineId != null;
-
- /// Every agent this phone could put in a tab: the ones it can actually open,
- /// which is the same test [deskGroups] makes of the ones already in them.
- List<AgentEntry> get _openable => [
- for (final entry in visibleAgents(agentIndex(widget.notifier)))
- if (entry.agent.terminalAvailable) entry,
- ];
-
- /// The machine a new agent would be made on: the first that can host one,
- /// which is also the form's own first question and changed there. Null where
- /// none can — every machine asleep, or wanting its password — and that is
- /// what leaves "New agent" out of the sheet rather than drawn dead.
- String? get _hostMachineId => [
- for (final machine in filterableMachines(widget.notifier))
- if (phoneMachineStatusOf(machine) == PhoneMachineStatus.ready) machine,
- ].firstOrNull?.machine.machineId;
-
- AgentRef _refOf(AgentEntry entry) =>
- (machineId: entry.machineId, agentId: entry.agent.id);
-
- /// Whether an empty [group] is empty because its agents are out of REACH, or
- /// because it holds none at all.
- ///
- /// The two look identical on screen and are nothing alike: the first is a
- /// machine asleep and the agents are still there, the second is a tab that
- /// has been emptied or has only just been made. Read from the desk itself —
- /// [DeskGroup] carries the agents this phone can open, which is by definition
- /// none in both cases.
- bool _everHeldAgents(DeskGroup group) =>
- widget.notifier.deskTabs
- .where((tab) => tab.id == group.id)
- .firstOrNull
- ?.panes
- .isNotEmpty ??
- false;
-
- /// A double tap on a tab's name.
- ///
- /// ⚠️ **The tab is picked as well as renamed, and not as an afterthought.**
- /// The first tap of the two has already picked it, so the panel below is
- /// showing what is being named — and after a rename the row under the names
- /// would otherwise belong to a different tab than the one just typed.
- void _rename(DeskGroup group) {
- final id = group.id;
- if (id == null) return;
- setState(() => _selectedId = id);
- unawaited(
- showDeskTabRenameDialog(
- context,
- widget.notifier,
- tabId: id,
- currentName: group.name,
- ),
- );
- }
-
- /// The `+` on the tab row: a tab of its own for an agent picked or made now.
- ///
- /// ⚠️ **The tab is written only once there is something to put in it.** A
- /// tab created up front and then abandoned — the form cancelled, the machine
- /// refusing — would be an empty tab on every computer the person owns, put
- /// there by a tap they took back. For a new agent that means arming
- /// [AppNotifier.openNextAgentInNewDeskTab] and letting the agent's own
- /// arrival make the tab.
- void _addTab() {
- final notifier = widget.notifier;
- final host = _hostMachineId;
- unawaited(
- showDeskAddAgentSheet(
- context,
- title: 'New tab',
- choices: _openable,
- onPick: (entry) {
- final group = DeskGroup(
- id: notifier.createDeskTabFor(
- _refOf(entry),
- name: entry.agent.displayName,
- ),
- name: entry.agent.displayName,
- entries: [entry],
- );
- if (group.id == null) return;
- // Opened, not merely listed: the tab exists now and the phone is in
- // it, and a panel that stayed put would say neither.
- widget.onOpen(group, entry);
- },
- onCreate: host == null
- ? null
- : () {
- notifier.openNextAgentInNewDeskTab();
- // Away first, then the form: it is pushed over the terminal,
- // and must not arrive under a panel still on its way out.
- widget.onClose();
- unawaited(
- openNewAgent(
- context,
- notifier,
- host,
- ).whenComplete(notifier.forgetNewDeskTabIntent),
- );
- },
- ),
- );
- }
-
- /// The row at the foot of the single group a phone with no desk shows: a
- /// harness that belongs to no tab, the way every harness did before the desk
- /// existed.
- ///
- /// The phone is taken out of any tab first: an agent made here joins
- /// whatever tab the phone is in ([PhoneDesk.adopt]).
- void _startUntabbed() {
- final host = _hostMachineId;
- if (host == null) return;
- final notifier = widget.notifier;
- notifier.selectDeskTab(null);
- widget.onClose();
- unawaited(openNewAgent(context, notifier, host));
- }
-
- /// The `+` at the foot of a tab's list: another agent in the tab being read.
- ///
- /// The panel stays open on the way back — this is a list being filled, and
- /// the agent appears in it under the thumb that added it.
- void _addAgentTo(DeskGroup group) {
- final id = group.id;
- if (id == null) return;
- final notifier = widget.notifier;
- final host = _hostMachineId;
- unawaited(
- showDeskAddAgentSheet(
- context,
- title: 'Add to “${group.name}”',
- choices: [
- for (final entry in _openable)
- if (!group.holds(_refOf(entry))) entry,
- ],
- onPick: (entry) => notifier.addAgentToDeskTab(id, _refOf(entry)),
- onCreate: host == null
- ? null
- : () {
- // The tab the phone is in is the tab an agent made here joins
- // — see [PhoneDesk.adopt] — so this is what aims that.
- notifier.selectDeskTab(id);
- widget.onClose();
- unawaited(openNewAgent(context, notifier, host));
- },
- ),
- );
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return ListenableBuilder(
- // The unread marks have their own notifier — see `notify/agent_unread.dart`.
- listenable: Listenable.merge([
- widget.notifier,
- widget.notifier.agentNotices.unread,
- ]),
- builder: (context, _) => _panel(context),
- );
- }
-
- Widget _panel(BuildContext context) {
- final groups = _groups;
- final group = _groupIn(groups);
- final showing = widget.showing;
- final canAdd = _canAddTo(group);
- final canStart = _canStartUntabbed(group);
- final count = group.entries.length + (canAdd || canStart ? 1 : 0);
- final padding = EdgeInsets.fromLTRB(
- kSheetInset,
- 0,
- kSheetInset,
- MediaQuery.paddingOf(context).bottom + 16,
- );
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- DeskTabStrip(
- groups: groups,
- selectedId: group.id,
- onPick: (picked) => setState(() => _selectedId = picked.id),
- // Undrawn on a desk that cannot be written to — see
- // [AppNotifier.deskWritable].
- onAddTab: widget.notifier.deskWritable ? _addTab : null,
- onRename: widget.notifier.deskWritable ? _rename : null,
- unreadFor: (tab) => widget.notifier.agentNotices.unread.mostUrgentOf(
- tab.entries.map(_refOf),
- ),
- ),
- SheetCaption(
- label: group.name,
- // A count only where there is something to count: `0` over a tab
- // whose machine is asleep would say the tab is empty, which is the
- // one thing the sentence under it says it is not.
- count: group.isEmpty ? null : '${group.entries.length}',
- ),
- Expanded(
- // ⚠️ **An empty tab keeps its sentence AND gets the `+`.** The two
- // answer different halves of the same screen: the sentence says why
- // there is nothing here, and the `+` is what to do about it. Dropped
- // in favour of the row, a tab whose machine is asleep silently became
- // a tab that merely had nothing in it.
- child: group.isEmpty
- // A list, not a column, though it holds two things: the height
- // it is given is what the sheet has left over, and on a phone
- // lying on its side that is less than the two of them.
- ? ListView(
- padding: padding,
- children: [
- _TabIsEmpty(everHeldAgents: _everHeldAgents(group)),
- if (canAdd)
- _AddAgentRow(
- tabName: group.name,
- first: true,
- last: true,
- onTap: () => _addAgentTo(group),
- )
- else if (canStart)
- _NewHarnessRow(
- first: true,
- last: true,
- onTap: _startUntabbed,
- ),
- ],
- )
- : ListView.builder(
- padding: padding,
- itemCount: count,
- itemBuilder: (context, index) {
- // ⚠️ **Last in the group, and a row of it rather than a
- // mark like the `+` on the tab row.** This one adds an
- // agent to the tab being read; that one opens a tab. Two
- // identical marks would be a guess, so the one that could
- // be mistaken carries the words — and closing the group
- // of the tab's agents is itself the sentence "into this
- // list".
- if (index == group.entries.length) {
- return canStart
- ? _NewHarnessRow(
- first: index == 0,
- last: true,
- onTap: _startUntabbed,
- )
- : _AddAgentRow(
- tabName: group.name,
- first: index == 0,
- last: true,
- onTap: () => _addAgentTo(group),
- );
- }
- final entry = group.entries[index];
- return DeskAgentRow(
- entry: entry,
- unread: widget.notifier.agentNotices.unread.kindFor(
- _refOf(entry),
- ),
- onScreen:
- showing != null &&
- entry.machineId == showing.machineId &&
- entry.agent.id == showing.agentId,
- first: index == 0,
- last: index == count - 1,
- onTap: () => widget.onOpen(group, entry),
- );
- },
- ),
- ),
- ],
- );
- }
-}
-
-/// One agent in the tab being read.
-///
-/// The row the sheet's search draws an agent with too ([SheetSearchRow]), so
-/// focusing the field changes which agents are listed and not how one looks.
-class DeskAgentRow extends StatelessWidget {
- const DeskAgentRow({
- super.key,
- required this.entry,
- required this.onScreen,
- required this.first,
- required this.last,
- required this.onTap,
- this.unread,
- });
-
- final AgentEntry entry;
-
- /// Its news nobody has gone to yet — see [SheetAgentStatus.unread].
- final NoticeKind? unread;
-
- /// The agent on screen. It keeps its row — it is the one you came from, and
- /// the list would read as missing an agent without it — and wears the check
- /// where the others have a chevron.
- final bool onScreen;
-
- /// Whether this row opens the group, and whether it closes it.
- final bool first, last;
-
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final agent = entry.agent;
- return SheetRow(
- first: first,
- last: last,
- selected: onScreen,
- enabled: agent.terminalAvailable,
- onTap: agent.terminalAvailable ? onTap : null,
- leading: SheetEngineTile(
- engine: agent.engine,
- displayName: agent.engineDisplayName,
- ),
- title: SheetAgentTitle(
- entry: entry,
- now: DateTime.now(),
- name: Text(
- agent.displayName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: sheetRowTitleStyle(),
- ),
- ),
- subtitle: SheetAgentMeta(entry: entry),
- trailing: SheetAgentStatus(
- summary: entry.summary,
- onScreen: onScreen,
- unread: unread,
- ),
- chevron: !onScreen,
- );
- }
-}
-
-/// The `+` at the foot of a tab's agents: one more agent in THIS tab.
-///
-/// ⚠️ **A row, not a mark, and that is the whole of how it is told apart from
-/// the `+` on the tab row above.** They are the same glyph doing two different
-/// things, so nothing rests on the glyph: this one is a row of the group it
-/// fills, closes it, is written in the accent iOS gives a row that acts rather
-/// than opens, and says which tab it fills. See [DeskTabStrip].
-class _AddAgentRow extends StatelessWidget {
- const _AddAgentRow({
- required this.tabName,
- required this.first,
- required this.last,
- required this.onTap,
- });
-
- final String tabName;
- final bool first, last;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final accent = AppPalette.accentOnSurface;
- return SheetRow(
- first: first,
- last: last,
- // ⚠️ The words on the row are "this tab", which is clear under a thumb
- // that has just read the tab's name and useless read aloud on its own.
- // Read aloud, the row names the tab it fills.
- semanticsLabel: 'Add harness to $tabName',
- leading: SheetTile(
- child: Icon(LucideIcons.plus, size: 18, color: accent),
- ),
- title: Text(
- 'Add harness to this tab',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: sheetRowTitleStyle().copyWith(color: accent),
- ),
- // It adds here rather than going anywhere.
- chevron: false,
- onTap: () {
- HapticFeedback.selectionClick();
- onTap();
- },
- );
- }
-}
-
-/// The row at the foot of the no-desk group: start a harness that no tab owns.
-///
-/// ⚠️ **"New harness", not "Add harness" — a different verb for a different
-/// act.** The row in a real tab PUTS something that exists into that tab; this
-/// one makes something that did not exist, and there is no tab to put it in.
-class _NewHarnessRow extends StatelessWidget {
- const _NewHarnessRow({
- required this.first,
- required this.last,
- required this.onTap,
- });
-
- final bool first, last;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final accent = AppPalette.accentOnSurface;
- return SheetRow(
- first: first,
- last: last,
- semanticsLabel: 'New harness, in no tab',
- leading: SheetTile(
- child: Icon(LucideIcons.plus, size: 18, color: accent),
- ),
- title: Text(
- 'New harness',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: sheetRowTitleStyle().copyWith(color: accent),
- ),
- // It opens the New Harness form, so it keeps the chevron the rows that
- // go somewhere wear.
- onTap: () {
- HapticFeedback.selectionClick();
- onTap();
- },
- );
- }
-}
-
-/// A tab whose agents are all out of reach — the machine they run on is asleep
-/// or wants its password. The tab is still listed and still opens to this,
-/// because a tab missing from the row reads as one somebody deleted.
-class _TabIsEmpty extends StatelessWidget {
- const _TabIsEmpty({required this.everHeldAgents});
-
- /// Whether the tab holds agents this phone cannot reach, as opposed to no
- /// agents at all — see [_DeskTabsPanelState._everHeldAgents].
- final bool everHeldAgents;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- // Under the caption's own first letter, and clear of the row below it.
- padding: const EdgeInsets.fromLTRB(
- kSheetCaptionInset - kSheetInset,
- 2,
- kSheetCaptionInset - kSheetInset,
- 14,
- ),
- child: Text(
- everHeldAgents
- ? 'Nothing here this phone can open — the machine these harnesses run '
- 'on is asleep or wants its password.'
- : 'This tab has no harnesses yet.',
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 13.5,
- height: 1.4,
- ),
- ),
- );
- }
-}
-
-/// Open [entry] from [group]: the phone is in that tab from here.
-///
-/// ⚠️ The order matters. [AppNotifier.selectDeskTab] is what settles which tab
-/// an agent that sits on TWO of them belongs to (see [activeDeskGroup]); set
-/// after the open, it would be read a frame too late and the panel would come
-/// back barring the tab that was left.
-void openDeskAgent(
- BuildContext context,
- AppNotifier notifier,
- DeskGroup group,
- AgentEntry entry,
-) {
- notifier.selectDeskTab(group.id);
- openAgent(context, notifier, entry.machineId, entry.agent.id);
-}
diff --git a/mobile/lib/phone/find_models.dart b/mobile/lib/phone/find_models.dart
new file mode 100644
index 000000000..d7e8d544a
--- /dev/null
+++ b/mobile/lib/phone/find_models.dart
@@ -0,0 +1,162 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'agent_model_controller.dart';
+import 'agent_model_sections.dart';
+import 'agent_model_sheet.dart' show applyModelChoice;
+import 'find_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Find's `:` — the desktop ⌘P's models mode: what the agent on screen can run on, as fzf rows.
+///
+/// Its engine's own subscription first (nearest the prompt), then every model the machine's grids
+/// serve — your own machines' local models, then each shared grid's. The one it runs on wears `*`.
+/// A tap moves it there, which re-execs the agent's process on the new model.
+///
+/// Only the engines whose switching is driven end to end are offered it ([kModelSheetEngines]);
+/// the rest are told so in one line rather than shown rows a tap could not act on.
+class FindModels extends StatefulWidget {
+ const FindModels({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ required this.agentId,
+ required this.query,
+ required this.onPicked,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+ final String agentId;
+
+ /// What was typed after the `:`.
+ final String query;
+
+ /// Called as a model is picked, before the move is asked for — Find closes on it.
+ final VoidCallback onPicked;
+
+ @override
+ State<FindModels> createState() => _FindModelsState();
+}
+
+class _FindModelsState extends State<FindModels> {
+ late final AgentModelController _models = AgentModelController(
+ notifier: widget.notifier,
+ machineId: widget.machineId,
+ agentId: widget.agentId,
+ );
+
+ @override
+ void dispose() {
+ _models.dispose();
+ super.dispose();
+ }
+
+ void _pick(GridModel? model) {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ widget.onPicked();
+ unawaited(
+ applyModelChoice(
+ widget.notifier,
+ machineId: widget.machineId,
+ agentId: widget.agentId,
+ model: model,
+ messenger: messenger,
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: _models,
+ builder: (context, _) {
+ final tty = Tty.of(context);
+ final agent = _models.agent;
+ final engine = agent?.engine?.trim().toLowerCase();
+ final needle = widget.query.trim().toLowerCase();
+ bool matches(String text) =>
+ needle.isEmpty || text.toLowerCase().contains(needle);
+ final rows = <Widget>[];
+ Widget note(String text) => Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 8),
+ child: Text(
+ text,
+ style: tty.style(color: tty.faint, size: TtySize.meta),
+ ),
+ );
+ if (!kModelSheetEngines.contains(engine)) {
+ rows.add(
+ note(
+ '${engineIdentity(agent?.engine, displayName: agent?.engineDisplayName).label} '
+ 'keeps its own model — `:` switches claude, codex and opencode',
+ ),
+ );
+ } else {
+ final reading = _models.subscription;
+ final ownTitle =
+ (reading?['title'] as String?) ??
+ engineIdentity(
+ agent?.engine,
+ displayName: agent?.engineDisplayName,
+ ).label;
+ if (matches(ownTitle)) {
+ rows.add(const FindHeader('subscription'));
+ rows.add(
+ FindRow(
+ title: ownTitle,
+ detail: reading?['account'] as String?,
+ terms: needle.isEmpty ? const [] : [needle],
+ state: agent?.gridModel == null ? '✓' : null,
+ stateColor: tty.green,
+ onTap: () => _pick(null),
+ ),
+ );
+ }
+ final answer = _models.answer;
+ if (answer == null) {
+ rows.add(note('asking the machine for its models…'));
+ } else if (!answer.canRunLocally(agent?.engine)) {
+ rows.add(note('this engine runs only on its own models'));
+ } else {
+ for (final section in modelSheetSections(answer)) {
+ final where = section.own ? 'local' : section.name;
+ final shown = [
+ for (final model in section.models)
+ if (matches(model.id) || matches(where)) model,
+ ];
+ if (section.models.isEmpty && needle.isEmpty) {
+ final empty = modelSheetEmptySentence(answer, section);
+ if (empty != null)
+ rows.add(note('$where: ${empty.toLowerCase()}'));
+ }
+ if (shown.isNotEmpty) rows.add(FindHeader(where));
+ for (final model in shown) {
+ rows.add(
+ FindRow(
+ title: model.id,
+ detail: model.node.isEmpty ? where : '$where · ${model.node}',
+ terms: needle.isEmpty ? const [] : [needle],
+ state: agent?.gridModel == model.id ? '✓' : null,
+ stateColor: tty.green,
+ onTap: () => _pick(model),
+ ),
+ );
+ }
+ }
+ }
+ }
+ // Find's list: down from the field at the top, the same rows as every other mode.
+ return ListView(
+ padding: EdgeInsets.zero,
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ children: rows,
+ );
+ },
+ );
+}
diff --git a/mobile/lib/phone/find_row.dart b/mobile/lib/phone/find_row.dart
new file mode 100644
index 000000000..c90821201
--- /dev/null
+++ b/mobile/lib/phone/find_row.dart
@@ -0,0 +1,254 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'fzf.dart' show fzfHighlight;
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// One of Find's rows: two lines, 60pt — the name at 17 with its state word at the right edge, and
+/// under it where the harness works (or, while it asks, its question).
+///
+/// ```
+/// api-fix asking
+/// "Run the migration on the test db?"
+/// docs-rewrite working
+/// M2:site ⑂ docs-v2 · 2m
+/// ```
+class FindRow extends StatelessWidget {
+ const FindRow({
+ super.key,
+ required this.title,
+ this.detail,
+ this.detailColor,
+ this.branch,
+ this.tail,
+ this.state,
+ this.stateColor,
+ this.terms = const [],
+ this.selected = false,
+ this.enabled = true,
+ this.onTap,
+ this.strict = false,
+ this.said,
+ });
+
+ final String title;
+
+ /// A harness row: its title's letters are lit the way harness rows match — see [fzfHighlight].
+ final bool strict;
+
+ /// Where the machine's session index found the words, in place of [detail]: what was asked
+ /// (`> …`), a command (`$ …`) or the answer, the matched words lit — fzf's preview line.
+ final ({String lead, List<({String text, bool matched})> runs})? said;
+
+ /// Line 2: `machine:folder`, or a quoted question.
+ final String? detail;
+ final Color? detailColor;
+
+ /// After [detail], behind the branch icon — see [ttyBranchMark].
+ final String? branch;
+
+ /// Last on line 2, after a `·`: the age, or `current`.
+ final String? tail;
+
+ /// `asking`, `working`, `idle`, `exited` — one word, right-aligned on line 1.
+ final String? state;
+ final Color? stateColor;
+
+ /// What was typed, lit green in [title] and [detail].
+ final List<String> terms;
+
+ /// The row Return opens: the raised ground behind it.
+ final bool selected;
+ final bool enabled;
+ final VoidCallback? onTap;
+
+ static const double height = 60;
+
+ TextStyle _base(Tty tty) =>
+ tty.style(color: detailColor ?? tty.faint, size: TtySize.meta);
+
+ /// [text] with the typed words lit — only where they are there as typed: fzf's scattered
+ /// letters inside a question or a path read as noise.
+ List<InlineSpan> _lit(String text, Tty tty) => fzfHighlight(
+ text,
+ [
+ for (final term in terms)
+ if (text.toLowerCase().contains(term.toLowerCase())) term,
+ ],
+ base: _base(tty),
+ hit: tty.style(color: tty.green, size: TtySize.meta),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final ink = enabled ? tty.text : tty.faint;
+ return TtyTap(
+ minHeight: height,
+ onTap: enabled && onTap != null
+ ? () {
+ HapticFeedback.selectionClick();
+ onTap!();
+ }
+ : null,
+ child: ColoredBox(
+ color: selected ? ttyRaised(tty) : Colors.transparent,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 9, Tty.origin, 9),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Expanded(
+ child: Text.rich(
+ TextSpan(
+ children: fzfHighlight(
+ title,
+ terms,
+ strict: strict,
+ base: tty.style(
+ color: ink,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ hit: tty.style(
+ color: tty.green,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ ),
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (state case final state?) ...[
+ const SizedBox(width: 12),
+ TtyText(
+ state,
+ color: stateColor ?? tty.faint,
+ size: TtySize.meta,
+ ),
+ ],
+ ],
+ ),
+ if (said case final said?) ...[
+ const SizedBox(height: 3),
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(text: said.lead, style: _base(tty)),
+ for (final run in said.runs)
+ TextSpan(
+ text: run.text,
+ style: run.matched
+ ? tty.style(color: tty.green, size: TtySize.meta)
+ : _base(tty),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ] else if (detail case final detail? when detail.isNotEmpty) ...[
+ const SizedBox(height: 3),
+ Text.rich(
+ TextSpan(
+ children: [
+ ..._lit(detail, tty),
+ if (branch case final branch? when branch.isNotEmpty) ...[
+ ttyBranchMark(tty, color: detailColor ?? tty.faint),
+ ..._lit(branch, tty),
+ ],
+ if (tail case final tail? when tail.isNotEmpty)
+ TextSpan(text: ' · $tail', style: _base(tty)),
+ ],
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The `+` row that ends a list: `+ New Harness`, `+ Open Folder`. Cyan, the colour of what can be
+/// tapped; an optional faint second line says where.
+class FindAddRow extends StatelessWidget {
+ const FindAddRow({
+ super.key,
+ required this.label,
+ required this.onTap,
+ this.detail,
+ });
+
+ final String label;
+ final String? detail;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return TtyTap(
+ minHeight: detail == null ? 52 : FindRow.height,
+ semanticsLabel: label,
+ onTap: onTap == null
+ ? null
+ : () {
+ HapticFeedback.selectionClick();
+ onTap!();
+ },
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 9, Tty.origin, 9),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TtyText(
+ '+ $label',
+ color: onTap == null ? tty.faint : tty.text,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(height: 3),
+ TtyText(detail, color: tty.faint, size: TtySize.meta),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// Find's section header — `needs you`, `recent`, `commands`: 13pt, faint, 28pt tall.
+class FindHeader extends StatelessWidget {
+ const FindHeader(this.text, {super.key, this.color});
+
+ final String text;
+ final Color? color;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return SizedBox(
+ height: 36,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 0),
+ child: TtyText(text, color: color ?? tty.faint, size: TtySize.meta),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/floating_glass.dart b/mobile/lib/phone/floating_glass.dart
index f5c2748d0..edf41711f 100644
--- a/mobile/lib/phone/floating_glass.dart
+++ b/mobile/lib/phone/floating_glass.dart
@@ -1,21 +1,14 @@
-import 'dart:ui' show ImageFilter;
-
import 'package:flutter/material.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
-/// The resting fill of the terminal's floating buttons — the mic, Search and
-/// `+`.
+/// The resting fill of the terminal's floating buttons — the mic, and Find while the keyboard is up.
///
-/// ⚠️ **Lighter than the terminal in both themes, because the terminal is dark
-/// in both.** Every terminal palette is a near-black, so the dark theme's
-/// surface grey laid over one at half strength drew a circle a few shades off
-/// the page under it — the buttons read as missing. White at low strength is a
-/// raised pane over that black; the light theme's is near-solid, as its
-/// surfaces are.
+/// ⚠️ **Solid, not see-through.** Over a terminal every button needs its own ground for its glyph to
+/// read, and a near-opaque fill gives it one for nothing — the frosted blur that did the same job
+/// read the whole backdrop through a GPU filter on every frame the output moved under it.
Color get floatingButtonFill =>
- AppTheme.pick(const Color(0xD1FFFFFF), const Color(0x33FFFFFF));
-
+ AppTheme.pick(const Color(0xF2FFFFFF), const Color(0xF22A2A2F));
/// The rim that draws the circle's edge over whatever runs under it.
Color get floatingButtonRim =>
AppTheme.pick(const Color(0x29000000), const Color(0x59FFFFFF));
@@ -30,38 +23,17 @@ List<BoxShadow> get floatingButtonShadow => [
),
];
-/// Frosted glass under a floating button: the output beneath [child] is
-/// blurred to a soft wash, so its glyph reads against any line of text, while
-/// the colour and movement of the terminal still show through.
+/// What stood under a floating button to frost the output behind it — now nothing: the fill is
+/// solid ([floatingButtonFill]). Kept as a pass-through so the buttons keep one shape to change.
///
-/// ⚠️ **Blurred, not see-through.** A clear fill let every character under the
-/// button cross its glyph, and the buttons were reported as too hard to see.
-/// What the button covers is not readable any more — it was not readable
-/// through a glyph either.
-///
-/// [child] is the circle itself and sets the size; the blur is clipped to it.
-/// Grouped with the other floating buttons' blurs when a [BackdropGroup] is
-/// above, so the backdrop is read once for all of them.
+/// ⚠️ **The blur went for speed.** A `BackdropFilter` re-reads and blurs what is under it every time
+/// that changes, and under a streaming terminal it changes every frame — the one control that is
+/// always on screen was the costliest thing on it.
class FloatingGlass extends StatelessWidget {
const FloatingGlass({super.key, required this.child});
final Widget child;
- static const double blurSigma = 6;
-
@override
- Widget build(BuildContext context) => Stack(
- alignment: Alignment.center,
- children: [
- Positioned.fill(
- child: ClipOval(
- child: BackdropFilter.grouped(
- filter: ImageFilter.blur(sigmaX: blurSigma, sigmaY: blurSigma),
- child: const SizedBox.expand(),
- ),
- ),
- ),
- child,
- ],
- );
+ Widget build(BuildContext context) => child;
}
diff --git a/mobile/lib/phone/fzf.dart b/mobile/lib/phone/fzf.dart
new file mode 100644
index 000000000..bc087f2c9
--- /dev/null
+++ b/mobile/lib/phone/fzf.dart
@@ -0,0 +1,316 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/core/fuzzy_match.dart';
+
+import 'composing_keyboard.dart';
+import 'tty.dart';
+
+/// fzf, drawn for a thumb: one-line rows over a `> ` prompt, the best match next to the prompt,
+/// matched letters in fzf's green, `3/14` above the prompt. Find is built from these, and so is
+/// every chooser New opens — the same list everywhere, the one a terminal user already reads
+/// without thinking.
+
+/// One row: an optional mark in fzf's gutter, the name with its matched letters lit, the detail
+/// in the dim face after it, and one word at the right edge (an age, or a state).
+class FzfRow extends StatelessWidget {
+ const FzfRow({
+ super.key,
+ required this.title,
+ this.detail,
+ this.trailing,
+ this.trailingColor,
+ this.terms = const [],
+ this.mark,
+ this.markColor,
+ this.enabled = true,
+ this.cursor = false,
+ this.onTap,
+ });
+
+ /// fzf's cursor row — the one Enter takes: `▌` in red in the gutter, the selection ground behind,
+ /// the name in bold.
+ final bool cursor;
+
+ final String title;
+ final String? detail;
+ final String? trailing;
+ final Color? trailingColor;
+
+ /// What was typed, to light in [title] — fzf's `hl`.
+ final List<String> terms;
+
+ /// One character in the gutter: `*` for the agent on screen, `✓` for a chosen value.
+ final String? mark;
+ final Color? markColor;
+
+ final bool enabled;
+ final VoidCallback? onTap;
+
+ static const double height = 40;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final ink = enabled ? tty.text : tty.dim;
+ final row = TtyTap(
+ minHeight: height,
+ onTap: enabled && onTap != null
+ ? () {
+ HapticFeedback.selectionClick();
+ onTap!();
+ }
+ : null,
+ child: Row(
+ children: [
+ SizedBox(
+ width: 24,
+ child: Center(
+ child: TtyText(
+ cursor ? '▌' : (mark ?? ' '),
+ color: cursor ? tty.red : (markColor ?? tty.red),
+ weight: FontWeight.w600,
+ ),
+ ),
+ ),
+ Expanded(
+ child: Text.rich(
+ TextSpan(
+ children: [
+ ...fzfHighlight(
+ title,
+ terms,
+ base: tty.style(
+ color: ink,
+ weight: cursor ? FontWeight.w600 : FontWeight.w400,
+ ),
+ hit: tty.style(color: tty.green, weight: FontWeight.w600),
+ ),
+ if (detail case final detail? when detail.isNotEmpty)
+ TextSpan(
+ text: ' $detail',
+ style: tty.style(color: tty.faint),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
+ ),
+ ),
+ if (trailing case final trailing?)
+ Padding(
+ padding: const EdgeInsets.only(left: 8, right: 12),
+ child: TtyText(trailing, color: trailingColor ?? tty.dim),
+ ),
+ ],
+ ),
+ );
+ return cursor ? ColoredBox(color: tty.selected, child: row) : row;
+ }
+}
+
+/// [text] as spans with each typed term lit — a substring where there is one (one that starts a
+/// word first: "port" lights "windows port", not "support"), else scattered letters in order.
+///
+/// [strict] lights scattered letters the way a harness row matched them (see
+/// `phoneFieldMatchScore`): starting a word and close together, or two letters as initials — so
+/// what is lit is what earned the row its place.
+List<TextSpan> fzfHighlight(
+ String text,
+ List<String> terms, {
+ required TextStyle base,
+ required TextStyle hit,
+ bool strict = false,
+}) {
+ final lit = List<bool>.filled(text.length, false);
+ final lower = text.toLowerCase();
+ // Case folding that changes the length would shift every index: leave such text plain.
+ if (lower.length != text.length) return [TextSpan(text: text, style: base)];
+ for (final raw in terms) {
+ final term = raw.toLowerCase();
+ if (term.isEmpty) continue;
+ var at = wordStartIndexOf(lower, term);
+ if (at < 0) at = lower.indexOf(term);
+ if (at >= 0) {
+ for (var i = at; i < at + term.length; i++) {
+ lit[i] = true;
+ }
+ continue;
+ }
+ if (strict) {
+ wordSubsequenceSpread(
+ lower,
+ term,
+ onMatch: (start, end) {
+ for (var i = start; i < end; i++) {
+ lit[i] = true;
+ }
+ },
+ );
+ continue;
+ }
+ var from = 0;
+ final marks = <int>[];
+ for (final unit in term.split('')) {
+ final found = lower.indexOf(unit, from);
+ if (found < 0) {
+ marks.clear();
+ break;
+ }
+ marks.add(found);
+ from = found + 1;
+ }
+ for (final i in marks) {
+ lit[i] = true;
+ }
+ }
+ final spans = <TextSpan>[];
+ var start = 0;
+ for (var i = 1; i <= text.length; i++) {
+ if (i == text.length || lit[i] != lit[start]) {
+ spans.add(
+ TextSpan(
+ text: text.substring(start, i),
+ style: lit[start] ? hit : base,
+ ),
+ );
+ start = i;
+ }
+ }
+ return spans;
+}
+
+/// fzf's info line: ` 3/14 ──────` and, at its right edge, the words that act — `+new`, `esc`.
+class FzfInfoLine extends StatelessWidget {
+ const FzfInfoLine({
+ super.key,
+ required this.matched,
+ required this.total,
+ this.actions = const [],
+ this.label,
+ });
+
+ final int matched;
+ final int total;
+
+ /// A word in place of the count, for a list that counts itself elsewhere — `:`'s models.
+ final String? label;
+ final List<({String label, VoidCallback onTap})> actions;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return SizedBox(
+ height: 36,
+ child: Row(
+ children: [
+ const SizedBox(width: 24),
+ // fzf's info line: always `matched/total`, then its rule drawn in `─`, not a hairline.
+ TtyText(label ?? '$matched/$total', color: tty.yellow),
+ const SizedBox(width: 8),
+ Expanded(
+ child: ClipRect(child: TtyText('─' * 80, color: tty.dim)),
+ ),
+ for (final action in actions)
+ TtyTap(
+ onTap: action.onTap,
+ minHeight: 36,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: TtyText(action.label, color: tty.cyan),
+ ),
+ ),
+ const SizedBox(width: 4),
+ ],
+ ),
+ );
+ }
+}
+
+/// fzf's prompt: `> ` and the query, on the terminal's ground — no box, no border, no magnifier.
+class FzfPrompt extends StatelessWidget {
+ const FzfPrompt({
+ super.key,
+ required this.controller,
+ required this.focus,
+ required this.onChanged,
+ this.hint,
+ this.onSubmitted,
+ });
+
+ final TextEditingController controller;
+ final FocusNode focus;
+ final ValueChanged<String> onChanged;
+ final String? hint;
+ final VoidCallback? onSubmitted;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return SizedBox(
+ height: 48,
+ child: Row(
+ // ⚠️ On the text's baseline, not centred: a field and a glyph centred separately sat the
+ // query ~9pt above its `>`.
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ SizedBox(
+ width: 24,
+ child: Center(
+ child: TtyText('>', color: tty.blue, weight: FontWeight.w600),
+ ),
+ ),
+ Expanded(
+ child: TextField(
+ textAlignVertical: TextAlignVertical.center,
+ controller: controller,
+ focusNode: focus,
+ onChanged: onChanged,
+ onSubmitted: (_) => onSubmitted?.call(),
+ // ⚠️ The keyboard's own composing, left on: Vietnamese Telex on iOS rides on
+ // autocorrection, and a prompt that turned it off could not be typed in. Dashes and
+ // quotes stay straight — they are search text, not prose. See [ComposingKeyboard].
+ autocorrect: ComposingKeyboard.autocorrect,
+ enableSuggestions: ComposingKeyboard.enableSuggestions,
+ smartDashesType: SmartDashesType.disabled,
+ smartQuotesType: SmartQuotesType.disabled,
+ textCapitalization: TextCapitalization.none,
+ textInputAction: TextInputAction.search,
+ cursorColor: tty.text,
+ cursorWidth: 2,
+ style: tty.style(),
+ // Bare: the app theme fills and rounds every field, and a prompt has neither.
+ decoration: InputDecoration(
+ isCollapsed: true,
+ // The app theme gives every field a minimum height, which floated the text to the
+ // top of a taller box.
+ constraints: const BoxConstraints(),
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ contentPadding: EdgeInsets.zero,
+ hintText: hint,
+ hintStyle: tty.style(color: tty.faint),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ ],
+ ),
+ );
+ }
+}
+
+/// How long ago, the way a terminal would say it: `now`, `3m`, `2h`, `5d`.
+String fzfAge(DateTime? at, DateTime now) {
+ if (at == null) return '';
+ final gone = now.difference(at);
+ if (gone.inMinutes < 1) return 'now';
+ if (gone.inHours < 1) return '${gone.inMinutes}m';
+ if (gone.inDays < 1) return '${gone.inHours}h';
+ return '${gone.inDays}d';
+}
diff --git a/mobile/lib/phone/link_page.dart b/mobile/lib/phone/link_page.dart
index 37773bfeb..5eacad166 100644
--- a/mobile/lib/phone/link_page.dart
+++ b/mobile/lib/phone/link_page.dart
@@ -2,10 +2,11 @@ import 'package:flutter/material.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/widgets/link_machine_screen.dart';
-import 'phone_header.dart';
import 'phone_shell_scope.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+import 'welcome/unlock_computer.dart';
/// A machine's password form, as a phone page — the same [LinkMachineScreen] the desktop pops
/// up, since the exchange behind it is the same.
@@ -106,27 +107,33 @@ class _LinkPageState extends State<LinkPage> {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
+ final tty = Tty.of(context);
final machine = widget.notifier.stateOf(widget.machineId);
return Scaffold(
- backgroundColor: AppPalette.windowBg,
+ backgroundColor: tty.ground,
body: SafeArea(
child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- PhoneHeader(
- title: machine?.machine.displayName ?? 'Machine',
- subtitle: Text(
- 'Enter the password set on this machine',
- style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),
+ if (!widget.embedded)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
),
- ),
if (machine != null)
Expanded(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
- child: LinkMachineScreen(
- notifier: widget.notifier,
- machineState: machine,
- ),
+ child: UnlockComputer(
+ notifier: widget.notifier,
+ machineState: machine,
+ // Home, not a pushed page: nothing pops here, so the shell is told — and it
+ // carries on to the harnesses, or to New when there are none.
+ onUnlocked: widget.embedded
+ ? () =>
+ PhoneShellScope.maybeOf(context)
+ ?.onMachineLinked(widget.machineId)
+ : null,
),
),
],
diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dart
index 58cc7ced1..22d0f8307 100644
--- a/mobile/lib/phone/machines_tab.dart
+++ b/mobile/lib/phone/machines_tab.dart
@@ -8,14 +8,14 @@ import 'package:harness_mobile/shared/widgets/empty_state.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'link_page.dart';
+import 'welcome/connect_computer.dart';
+import 'tty_controls.dart';
+import 'tty.dart';
+import 'find_row.dart';
import 'machine_actions.dart';
import 'machine_index.dart';
-import 'machine_tile.dart';
import 'phone_card.dart';
-import 'phone_header.dart';
import 'phone_navigation.dart';
-import 'phone_search_button.dart';
-import 'phone_section_label.dart';
import 'phone_status.dart';
/// The machines on the account, grouped by what they need.
@@ -40,23 +40,26 @@ class MachinesTab extends StatelessWidget {
listenable: notifier,
builder: (context, _) {
AppTheme.watch(context);
+ final tty = Tty.of(context);
return Scaffold(
- backgroundColor: AppPalette.windowBg,
+ backgroundColor: tty.ground,
body: SafeArea(
bottom: false,
child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- // The same search the Agents tab offers, reached the same way.
- // It spans both kinds, so which tab it was opened from changes
- // nothing about what it finds — a machine hunted for from here
- // and an agent hunted for from there are one query.
- PhoneHeader(
- large: large,
- title: 'Machines',
- trailing: [
- if (notifier.machines.isNotEmpty)
- PhoneSearchButton(notifier: notifier),
- ],
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 12,
+ Tty.origin,
+ 4,
+ ),
+ child: TtyText(
+ 'Computers',
+ size: large ? 24 : TtySize.title,
+ weight: FontWeight.w600,
+ ),
),
Expanded(child: _Body(notifier: notifier)),
],
@@ -89,7 +92,7 @@ class _Body extends StatelessWidget {
if (ordered.isEmpty && failure != null) {
return EmptyState(
icon: LucideIcons.circleAlert300,
- title: "Couldn't load your machines",
+ title: "Couldn't reach your computers",
message: failure,
action: FilledButton(
onPressed: () => unawaited(notifier.retryMachines()),
@@ -100,58 +103,84 @@ class _Body extends StatelessWidget {
if (ordered.isEmpty) {
return const EmptyState(
icon: LucideIcons.laptopMinimal300,
- title: 'No machines yet',
+ title: 'No computers yet',
message:
- 'Run Harness on a computer signed in to this account and it will '
- 'appear here.',
+ 'Set up Harness on your computer, signed in to this account, and it '
+ 'appears here.',
);
}
- final working = workingMachines(ordered);
- final needsAttention = machinesNeedingAttention(ordered);
-
+ final tty = Tty.of(context);
return RefreshIndicator(
onRefresh: notifier.retryMachines,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
- padding: phoneListPadding(context),
+ padding: EdgeInsets.only(
+ bottom: MediaQuery.paddingOf(context).bottom + 24,
+ ),
children: [
- if (working.isNotEmpty) ...[
- const PhoneSectionLabel('Linked'),
- for (final state in working) _tile(context, state),
- const SizedBox(height: 6),
- ],
- if (needsAttention.isNotEmpty) ...[
- if (working.isNotEmpty)
- const PhoneSectionLabel('Needs your attention'),
- for (final state in needsAttention) _tile(context, state),
- ],
+ Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 0, Tty.origin, 8),
+ child: Text(
+ 'Your harnesses run on these. Each one is unlocked with its own '
+ 'phone password.',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ ),
+ for (final state in ordered) _row(context, state, tty),
+ const SizedBox(height: 8),
+ FindAddRow(
+ label: 'Set up another computer',
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (route) => ConnectComputerPage(
+ notifier: notifier,
+ signedIn: false,
+ onBack: () => Navigator.of(route).maybePop(),
+ ),
+ ),
+ ),
+ ),
],
),
);
}
- Widget _tile(BuildContext context, MachineState state) => Padding(
- padding: const EdgeInsets.only(bottom: kPhoneCardGap),
- // An offline machine has nothing to connect to and nothing to unlink from here that would
- // change anything, so its row does not open — see [PhoneCard], which dims a row with no tap.
- child: MachineTile(
- machine: state,
- onTap: phoneMachineStatusOf(state) == PhoneMachineStatus.offline
+ Widget _row(BuildContext context, MachineState state, Tty tty) {
+ final status = phoneMachineStatusOf(state);
+ final count = state.agents.length;
+ final (String word, Color color, String detail) = switch (status) {
+ PhoneMachineStatus.ready => (
+ 'ready',
+ tty.green,
+ count == 0
+ ? 'nothing running'
+ : '$count harness${count == 1 ? '' : 'es'}',
+ ),
+ PhoneMachineStatus.connecting => ('connecting', tty.faint, 'one moment…'),
+ PhoneMachineStatus.needsPassword => (
+ 'locked',
+ tty.yellow,
+ 'tap to unlock with its phone password',
+ ),
+ PhoneMachineStatus.offline => (
+ 'asleep',
+ tty.faint,
+ 'turn it on, or run harness start there',
+ ),
+ };
+ return FindRow(
+ title: state.machine.displayName,
+ detail: detail,
+ state: word,
+ stateColor: color,
+ enabled: status != PhoneMachineStatus.offline,
+ onTap: status == PhoneMachineStatus.offline
? null
: () => _open(context, state),
- ),
- );
+ );
+ }
- /// This screen connects and disconnects, and does nothing else.
- ///
- /// A machine that wants its password opens the form for it. A machine that already has one has
- /// exactly one thing left to offer — giving it up — so a tap brings that rather than a page.
- ///
- /// ⚠️ Deliberately NOT the agent list any more. Agents belong to the Agents tab, which lists
- /// every one on the account and treats the machine as a filter; reaching them a second way
- /// through here made the machine something to navigate THROUGH, which is the shape that tab
- /// exists to replace.
void _open(BuildContext context, MachineState state) {
if (state.needsLink) {
Navigator.of(context).push(
diff --git a/mobile/lib/phone/new_agent_chooser.dart b/mobile/lib/phone/new_agent_chooser.dart
new file mode 100644
index 000000000..253ebd70a
--- /dev/null
+++ b/mobile/lib/phone/new_agent_chooser.dart
@@ -0,0 +1,256 @@
+import 'package:flutter/material.dart';
+
+import 'find_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// One row of a [showNewAgentChooser] list.
+class ChooserItem<T> {
+ const ChooserItem({
+ required this.value,
+ required this.title,
+ this.subtitle,
+ this.icon,
+ this.leading,
+ this.selected = false,
+ this.enabled = true,
+ this.warn = false,
+ });
+
+ final T value;
+ final String title;
+
+ /// Under the title, in the faint face — a folder's machine and path, an engine's "not installed".
+ final String? subtitle;
+
+ final IconData? icon;
+
+ /// Drawn in place of [icon] — an engine's own mark.
+ final Widget? leading;
+
+ final bool selected;
+ final bool enabled;
+
+ /// Drawn in the warning colour: a choice that lets the agent do more than it should by default.
+ final bool warn;
+
+ bool matches(String query) {
+ if (query.isEmpty) return true;
+ final needle = query.toLowerCase();
+ return title.toLowerCase().contains(needle) ||
+ (subtitle?.toLowerCase().contains(needle) ?? false);
+ }
+}
+
+/// A chooser for one of New's rows — a full-height sheet that slides UP, since sideways means Find
+/// and New: a title and Cancel, a search field at the top, the list growing down with `✓` on the
+/// current value, and the `+` actions ending it. A tap picks and closes.
+///
+/// [fold] keeps a long list short: past that many items a `more` row stands in for the rest, until
+/// it is tapped or something is typed.
+Future<T?> showNewAgentChooser<T>(
+ BuildContext context, {
+ required String hint,
+ required List<ChooserItem<T>> items,
+ List<ChooserItem<T>> actions = const [],
+ String? title,
+ int? fold,
+}) => Navigator.of(context, rootNavigator: true).push<T>(
+ PageRouteBuilder<T>(
+ opaque: false,
+ barrierColor: Colors.black54,
+ barrierDismissible: true,
+ transitionDuration: const Duration(milliseconds: 200),
+ reverseTransitionDuration: const Duration(milliseconds: 160),
+ pageBuilder: (_, _, _) => _Chooser<T>(
+ title: title ?? hint.replaceFirst(RegExp(r'^Search '), ''),
+ hint: hint,
+ items: items,
+ actions: actions,
+ fold: fold,
+ ),
+ transitionsBuilder: (_, animation, _, child) => SlideTransition(
+ position: Tween(begin: const Offset(0, 1), end: Offset.zero).animate(
+ CurvedAnimation(
+ parent: animation,
+ curve: Curves.easeOutCubic,
+ reverseCurve: Curves.easeInCubic,
+ ),
+ ),
+ child: child,
+ ),
+ ),
+);
+
+class _Chooser<T> extends StatefulWidget {
+ const _Chooser({
+ required this.title,
+ required this.hint,
+ required this.items,
+ required this.actions,
+ this.fold,
+ });
+
+ final String title;
+ final String hint;
+ final List<ChooserItem<T>> items;
+ final List<ChooserItem<T>> actions;
+ final int? fold;
+
+ @override
+ State<_Chooser<T>> createState() => _ChooserState<T>();
+}
+
+class _ChooserState<T> extends State<_Chooser<T>> {
+ final _controller = TextEditingController();
+ final _focus = FocusNode();
+ String _query = '';
+ bool _unfolded = false;
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ void _choose(ChooserItem<T> item) {
+ if (!item.enabled) return;
+ FocusManager.instance.primaryFocus?.unfocus();
+ Navigator.of(context).pop(item.value);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final media = MediaQuery.of(context);
+ final query = _query.trim();
+ final matches = [
+ for (final item in widget.items)
+ if (item.matches(query)) item,
+ ];
+ final fold = widget.fold;
+ final folded =
+ fold != null && !_unfolded && query.isEmpty && matches.length > fold;
+ final shown = folded ? matches.take(fold).toList() : matches;
+ final terms = query.isEmpty
+ ? const <String>[]
+ : query.split(RegExp(r'\s+'));
+ // Everything but a strip at the top, where the form it belongs to still shows.
+ return Align(
+ alignment: Alignment.bottomCenter,
+ child: Container(
+ // Three quarters of the screen: the dimmed form above it is the way out.
+ height: media.size.height * 0.75,
+ decoration: BoxDecoration(
+ color: tty.ground,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(10)),
+ border: Border(
+ top: BorderSide(color: tty.dim.withValues(alpha: 0.6)),
+ ),
+ ),
+ child: Material(
+ type: MaterialType.transparency,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 4, 0),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyText(
+ widget.title,
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ // No Cancel: a tap above the sheet, or a pull down, puts it away.
+ const SizedBox(height: 44),
+ ],
+ ),
+ ),
+ // Search where there is something to search: a long list that is not folded.
+ if (widget.items.length > 8 && widget.fold == null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 4,
+ Tty.origin,
+ 4,
+ ),
+ child: TtyField(
+ controller: _controller,
+ focus: _focus,
+ hint: widget.hint,
+ action: TextInputAction.search,
+ onChanged: (value) => setState(() => _query = value),
+ onSubmitted: () {
+ final first = matches
+ .where((item) => item.enabled)
+ .firstOrNull;
+ if (first != null) _choose(first);
+ },
+ ),
+ ),
+ Expanded(
+ child: ListView(
+ keyboardDismissBehavior:
+ ScrollViewKeyboardDismissBehavior.onDrag,
+ padding: EdgeInsets.only(bottom: media.padding.bottom + 16),
+ children: [
+ for (final item in shown)
+ FindRow(
+ title: item.title,
+ detail: item.subtitle,
+ terms: terms,
+ state: item.selected
+ ? '✓'
+ : item.warn
+ ? 'risky'
+ : null,
+ stateColor: item.selected ? tty.green : tty.red,
+ enabled: item.enabled,
+ onTap: () => _choose(item),
+ ),
+ if (folded)
+ FindRow(
+ title: 'more',
+ detail:
+ '${matches.length - shown.length} others, A to Z',
+ onTap: () => setState(() => _unfolded = true),
+ ),
+ if (matches.isEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 16,
+ Tty.origin,
+ 8,
+ ),
+ child: TtyText(
+ 'No match.',
+ color: tty.faint,
+ size: TtySize.row,
+ ),
+ ),
+ if (widget.actions.isNotEmpty) const SizedBox(height: 8),
+ // An action the computer cannot do is left out, not drawn dead: a greyed row
+ // with no reason reads as broken.
+ for (final action in widget.actions)
+ if (action.enabled)
+ FindAddRow(
+ label: action.title,
+ detail: action.subtitle,
+ onTap: () => _choose(action),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/new_agent_draft.dart b/mobile/lib/phone/new_agent_draft.dart
index a406dd5ec..144679207 100644
--- a/mobile/lib/phone/new_agent_draft.dart
+++ b/mobile/lib/phone/new_agent_draft.dart
@@ -32,8 +32,12 @@ class NewAgentDraft {
this.git,
this.gitFolder,
this.codexProfile,
+ this.task,
});
+ /// The first task, typed or said and not yet started — it survives Cancel until the next Start.
+ final String? task;
+
final String machineId;
final String? engine;
final String permissionMode;
diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dart
index e60510b6c..909a343b5 100644
--- a/mobile/lib/phone/new_agent_page.dart
+++ b/mobile/lib/phone/new_agent_page.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
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/permission_modes.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -14,12 +15,13 @@ import 'package:harness_mobile/widgets/remote_folder_picker.dart';
import 'agent_index.dart';
import 'branch_picker_sheet.dart';
-import 'phone_header.dart';
import 'phone_navigation.dart';
import 'new_agent_draft.dart';
import 'phone_status.dart';
-import 'project_picker_sheet.dart';
-import 'settings_row.dart';
+import 'new_agent_chooser.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+import 'voice_input_controller.dart';
/// Starting an agent from the phone: a folder on that machine, and an engine to
/// run there.
@@ -37,11 +39,21 @@ class NewAgentPage extends StatefulWidget {
super.key,
required this.notifier,
required this.machineId,
+ this.folder,
+ this.voice,
});
+ /// The mic the task field talks through — the pager's, so a take survives the swipe here. Null
+ /// makes the page its own.
+ final VoiceInputController? voice;
+
final AppNotifier notifier;
final String machineId;
+ /// A folder on [machineId] to start in — Find's `+ New Harness in api`. Null takes the last one
+ /// used there.
+ final String? folder;
+
@override
State<NewAgentPage> createState() => _NewAgentPageState();
}
@@ -51,25 +63,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// MACHINE rows change it.
late String _machineId = widget.machineId;
- /// Whether the MACHINE row is folded open onto the other machines.
- bool _machinesOpen = false;
-
- /// Whether the engines past [_primaryEngines] are shown.
- bool _moreEnginesOpen = false;
-
- /// Whether PROJECT and ENGINE are folded open onto their choices. BRANCH
- /// opens a sheet of its own instead — see [showBranchPickerSheet] — because
- /// its list is the one that needs searching.
- ///
- /// ⚠️ **Shut by default, and that is what makes this a form rather than a
- /// list of everything.** Laid out flat it ran to ten rows with four sources
- /// and five engines always on screen, so the two rows that matter — where the
- /// work is and what runs it — read as items in a catalogue, and Branch had
- /// nowhere to go. Folded, the page says what is chosen; opening a section is
- /// how it is changed. It is the idiom MACHINE above already uses.
- bool _projectOpen = false;
- bool _engineOpen = false;
-
String? _folder;
/// Set when the MACHINE is to produce the folder — a fresh project, or a clone — instead of one
@@ -104,9 +97,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// `core/permission_modes.dart`.
String _permissionMode = kDefaultPermissionMode;
- /// Whether the approval rows are folded open, like the engine list above them.
- bool _approvalsOpen = false;
-
/// The modes the chosen engine offers, empty for one that has none to choose between — the row
/// is then left out rather than drawn dead.
List<PermissionMode> get _permissionModes =>
@@ -169,14 +159,69 @@ 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.
+ bool _engineChosen = false;
+
@override
void dispose() {
_keepDraft();
+ _task.dispose();
+ _ownVoice?.dispose();
super.dispose();
}
+ /// The first task — `prompt` on `agent_create`. Optional: empty starts the harness idle.
+ final _task = TextEditingController();
+
+ /// Made on the first tap of the mic, not before: a recorder opens a platform channel, and a
+ /// form nobody talks to should not.
+ VoiceInputController? _ownVoice;
+ VoiceInputController? get _voiceIfAny => widget.voice ?? _ownVoice;
+
+ /// The task field's mic: talk, and what was said is added to the task.
+ void _talk() {
+ final voice =
+ _voiceIfAny ??
+ (_ownVoice = VoiceInputController(
+ transcriber: (wav, lang) =>
+ widget.notifier.api.transcribeVoice(wav, lang: lang),
+ ));
+ if (widget.voice == null) setState(() {});
+ if (voice.status == VoiceInputStatus.listening) {
+ unawaited(
+ voice.submit((text) async {
+ if (!mounted) return false;
+ final said = text.trim();
+ final before = _task.text.trimRight();
+ final next = before.isEmpty ? said : '$before $said';
+ _task.value = TextEditingValue(
+ text: next,
+ selection: TextSelection.collapsed(offset: next.length),
+ );
+ setState(() {});
+ return true;
+ }),
+ );
+ return;
+ }
+ if (voice.status == VoiceInputStatus.idle)
+ unawaited(voice.startListening());
+ }
+
/// Takes back what the form was left holding — see [NewAgentDraft].
///
/// ⚠️ **The machine comes from the draft, not from the page's argument**, which is what the
@@ -190,6 +235,11 @@ class _NewAgentPageState extends State<NewAgentPage> {
void _restoreDraft() {
final draft = newAgentDraft;
if (draft == null) return;
+ // Opened for a place — `+ New Harness in api` — the place wins; only the words carry over.
+ if (widget.folder != null) {
+ _task.text = draft.task ?? '';
+ return;
+ }
if (widget.notifier.stateOf(draft.machineId) == null) {
newAgentDraft = null;
return;
@@ -207,6 +257,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
_git = draft.git;
_gitFolder = draft.gitFolder;
_codexProfile = draft.codexProfile;
+ _task.text = draft.task ?? '';
}
/// Leaves the form's answers where the next open will find them. Called from [dispose], so it
@@ -215,7 +266,10 @@ class _NewAgentPageState extends State<NewAgentPage> {
void _keepDraft() {
// Nothing chosen and nothing typed is not a draft; it is the form as it opens. Kept, it would
// pin the page to whichever machine was last looked at for the rest of the run.
- if (_folder == null && _project == null && _branchName == null) {
+ if (_folder == null &&
+ _project == null &&
+ _branchName == null &&
+ _task.text.trim().isEmpty) {
newAgentDraft = null;
return;
}
@@ -233,6 +287,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
git: _git,
gitFolder: _gitFolder,
codexProfile: _codexProfile,
+ task: _task.text,
);
}
@@ -252,13 +307,9 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// different folder that happens to share the path. The engine stays: it names a program, not a
/// place.
void _selectMachine(String machineId) {
- if (machineId == _machineId) {
- setState(() => _machinesOpen = false);
- return;
- }
+ if (machineId == _machineId) return;
setState(() {
_machineId = machineId;
- _machinesOpen = false;
_folder = null;
_project = null;
_projectLabel = null;
@@ -309,7 +360,22 @@ class _NewAgentPageState extends State<NewAgentPage> {
// A late answer about a folder the form has since left belongs to nobody —
// see the note on [_gitFolder].
if (!mounted || machineId != _machineId || folder != _folder) return;
- final info = GitProjectInfo.fromJson(raw);
+ var info = GitProjectInfo.fromJson(raw);
+ // ⚠️ **A worktree is a temporary folder, so New shows its repository** — the desktop's rule
+ // (`state/new_harness.dart`). Harness made it for another harness; opening New on it named
+ // that harness's folder (`silent-beacon`) as the project, which nobody recognises. The
+ // machine names the main checkout, and new work starts from the branch that is on.
+ if (info.mainFolder case final main?) {
+ _folder = main;
+ _gitFolder = main;
+ info = GitProjectInfo(
+ isGit: true,
+ branch: info.mainBranch,
+ branches: info.branches,
+ defaultRef: info.defaultRef,
+ root: main,
+ );
+ }
setState(() {
_gitLoading = false;
_gitFailed = info.unavailable;
@@ -342,24 +408,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
);
}
- /// The PROJECT row's own line: the folder's last segment, or the name of the
- /// source that will make one.
- String get _projectTitle => _folder != null
- ? _basename(_folder!)
- : (_projectLabel ?? 'Choose a folder');
-
- /// Under it: the whole path, or why there is none yet.
- String? get _projectDetail =>
- _folder ??
- (_project?.repository != null
- ? 'Cloned on the machine'
- : _project != null
- ? 'A fresh folder, made on the machine'
- : null);
-
- String get _engineLabel =>
- _engine == null ? 'Choose an agent' : _engineName(_engine!);
-
/// What this form calls an engine.
///
/// ⚠️ **"Claude Code", not "Claude", and only here.** The desktop's launcher says the same
@@ -467,19 +515,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
'project or clone one there.';
}
- /// Folders agents have been started in on THIS machine, newest first.
- ///
- /// ⚠️ A stored history, not a reading of what exists now. It survives the agent that put it
- /// there, which is what makes "recent" honest — the list that came from `machine.agents` emptied
- /// itself when an agent was deleted, and called that "recent" too.
- ///
- /// Scoped per machine because the paths are: a folder on one computer means nothing on another.
- List<String> get _recent => widget.notifier.projectHistory.recent(_machineId);
-
- /// Whether the chosen folder came from the browser rather than from Recent.
- bool get _browsed => _folder != null && !_recent.contains(_folder);
-
- /// The recent folder currently chosen, for the folded row to show, or null.
/// The last segment of a path, for the row's title. No `package:path` here — these are the remote
/// machine's paths, and its separator is not this device's to assume.
String _basename(String path) {
@@ -500,22 +535,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// the caveat instead — see [_engineNote].
List<EngineIdentity> get _engines => allEngines;
- /// The engines shown before "More". The rest fold behind it: fourteen rows put the Create button's
- /// neighbours out of reach, and most people start with one of these.
- static const _primaryEngines = {'claude', 'codex', 'opencode', 'hermes'};
-
- /// The engine rows on screen: the primary ones, then the rest once unfolded. A chosen engine from
- /// the folded part stays visible, so the tick is never hidden behind "More".
- List<EngineIdentity> get _shownEngines => [
- for (final identity in _engines)
- if (_primaryEngines.contains(identity.id) ||
- _moreEnginesOpen ||
- identity.id == _engine)
- identity,
- ];
-
- int get _hiddenEngineCount => _engines.length - _shownEngines.length;
-
/// The one caveat worth printing beside an engine's name, or none.
///
/// Absent and installable earns nothing: Harness puts it there before it
@@ -574,27 +593,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
unawaited(_loadGit(chosen));
}
- /// The searchable list of folders already worked in — the desktop's project menu, which is the
- /// same history this page's Recent row lists.
- ///
- /// ⚠️ **It folds Recent shut on the way back.** Both are the same list, and leaving one open
- /// under an answer taken from the other left the folder ticked in two places at once.
- Future<void> _searchProject() async {
- final chosen = await showProjectPickerSheet(
- context,
- folders: _recent,
- selected: _folder,
- );
- if (chosen == null || !mounted) return;
- setState(() {
- _folder = chosen;
- _project = null;
- _projectLabel = null;
- _error = null;
- });
- unawaited(_loadGit(chosen));
- }
-
Future<void> _create() async {
final folder = _folder, engine = _engine, project = _project;
if ((folder == null && project == null) || engine == null || _creating) {
@@ -639,21 +637,30 @@ class _NewAgentPageState extends State<NewAgentPage> {
// with its own default CODEX_HOME.
codexHome: _showsCodexProfile ? _codexProfile?.path : null,
attempt: creation,
+ prompt: _engine != null && takesFirstTask(_engine!) ? _task.text : null,
);
if (!mounted) return;
if (error == null) {
// The harness exists: the draft that described it would be a second one waiting to be made
// by accident. See [NewAgentDraft].
newAgentDraft = null;
+ unawaited(widget.notifier.agentPreference.select(engine));
_open(creation.agentId);
return;
}
setState(() {
_creating = false;
_error = error;
+ _failed = true;
});
}
+ /// Options unfolded: branch, approvals and profile shown rather than left on their defaults.
+ bool _optionsOpen = false;
+
+ /// The last Start did not take: the button says Try Again, and every value stays.
+ bool _failed = false;
+
/// Where a finished creation lands: inside the agent it just started.
///
/// Asking for an agent and being handed back the list to find it in is a step
@@ -682,530 +689,606 @@ class _NewAgentPageState extends State<NewAgentPage> {
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.notifier,
builder: (context, _) {
- AppTheme.watch(context);
- final machine = _machine;
- final machines = _machines;
- // "New project" is the folder until one is chosen. Applied here rather than in `initState`
- // because it can only be offered once the machine has said it can make one, and that answer
- // lands after the page opens. Nothing but a machine switch leaves both unset again, so this
- // never overrides a choice — and a switch re-applies it on the new machine.
- if (_folder == null && _project == null && _canMakeProject) {
- _project = const ProjectFolderRequest.newProject();
- _projectLabel = 'New project';
- }
- final ready =
- (_folder != null || _project != null) &&
- _engine != null &&
- !_creating;
+ final tty = Tty.of(context);
+ _applyDefaultProject();
+ final info = _repository;
+ final mode = _permissionModeChoice;
+ final ready = _engine != null && (_folder != null || _project != null);
+ final nothingRunning = _machines.every((m) => m.agents.isEmpty);
+ final count = _task.text.trim().length;
+ // Typing the task, the keyboard leaves room for one line of the choices, not four cut ones.
+ final typing = MediaQuery.viewInsetsOf(context).bottom > 0;
+ final summary = [
+ if (_engine != null) _engineName(_engine!),
+ if (_folder != null || _project != null) _projectValue,
+ if (_repository != null) _worktree ? 'worktree' : _branchTitle,
+ if (_permissionModes.isNotEmpty)
+ (_permissionModeChoice?.label ?? 'Auto-approve'),
+ ].join(' · ');
return Scaffold(
- backgroundColor: AppPalette.windowBg,
+ backgroundColor: tty.ground,
body: SafeArea(
- child: Column(
- children: [
- // No machine under the title any more: the MACHINE rows below say it, and are where it
- // is changed.
- const PhoneHeader(title: 'New Harness'),
- Expanded(
- child: ListView(
- // ⚠️ **A side inset, where this list had none.** The cards
- // ran edge to edge while every other list on the phone sits
- // 16 in ([phoneListPadding]), so a form of three rows read as
- // three bands across the screen rather than as cards on it.
- padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
- children: [
- const SettingsCaption('MACHINE'),
- SettingsGroup(
+ // ⚠️ **A swipe right ANYWHERE goes back to Focus.** New is a swipe left from the terminal
+ // (Snapchat's layout), and the way home is the same swipe the other way — not only the
+ // system's sliver of left edge, which a thumb in the middle of the screen never finds.
+ child: GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onHorizontalDragStart: (_) => _swipedBack = 0,
+ onHorizontalDragUpdate: (details) =>
+ _swipedBack += details.primaryDelta ?? 0,
+ onHorizontalDragEnd: (details) {
+ if (_swipedBack >= 64 || (details.primaryVelocity ?? 0) >= 300) {
+ unawaited(Navigator.of(context).maybePop());
+ }
+ },
+ // A form, the phone's way: who and where on top, what to do and Start at the foot, in
+ // the thumb's reach and riding the keyboard. See
+ // docs/plans/2026-09-26-003-mobile-find-new-spec.md.
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, 4, 0),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyText(
+ 'New Harness',
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ // No Cancel: a swipe right goes back, the way a swipe left came in.
+ const SizedBox(height: 44),
+ ],
+ ),
+ ),
+ if (nothingRunning)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 0,
+ Tty.origin,
+ 4,
+ ),
+ child: TtyText(
+ 'Nothing running yet. Start your first harness.',
+ color: tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ const SizedBox(height: 8),
+ if (typing)
+ TtyFormRow(
+ label: 'harness',
+ value: summary.isEmpty ? 'Choose an agent' : summary,
+ onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
+ )
+ else
+ Expanded(
+ child: ListView(
+ keyboardDismissBehavior:
+ ScrollViewKeyboardDismissBehavior.onDrag,
+ padding: EdgeInsets.zero,
children: [
- // Folded like Recent: the chosen machine is the answer most of the time,
- // and the others only matter to somebody about to change it.
- SettingsRow(
- title: machine?.machine.displayName ?? 'Machine',
- leading: Icon(
- LucideIcons.laptopMinimal300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: machines.length < 2
+ TtyFormRow(
+ label: 'agent',
+ value: _engine == null
+ ? 'Choose an agent'
+ : _engineName(_engine!),
+ valueColor: _engine == null ? tty.green : null,
+ detail: _engine == null
? null
- : Icon(
- _machinesOpen
- ? LucideIcons.chevronUp300
- : LucideIcons.chevronDown300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- onTap: machines.length < 2
+ : _engineNote(_engine!),
+ onTap: _creating
? null
- : () => setState(
- () => _machinesOpen = !_machinesOpen,
- ),
+ : () => unawaited(_chooseAgent()),
),
- if (_machinesOpen)
- for (final other in machines)
- SettingsRow(
- title: other.machine.displayName,
- nested: true,
- trailing: _check(
- other.machine.machineId == _machineId,
- ),
- onTap: () =>
- _selectMachine(other.machine.machineId),
- ),
- ],
- ),
- const SettingsCaption('PROJECT'),
- SettingsGroup(
- children: [
- // What is chosen, and the way into changing it. Its
- // detail is the full path: the title is only the last
- // segment, and two machines' `mobile` folders are told
- // apart by everything before it.
- SettingsRow(
- title: _projectTitle,
- detail: _projectDetail,
- leading: Icon(
- LucideIcons.folder300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: Icon(
- _projectOpen
- ? LucideIcons.chevronUp300
- : LucideIcons.chevronDown300,
- size: 18,
- color: AppPalette.textFaint,
- ),
+ TtyFormRow(
+ label: 'project',
+ value: _folder == null && _project == null
+ ? 'Choose a project'
+ : _projectValue,
+ valueColor: _folder == null && _project == null
+ ? tty.green
+ : null,
+ detail: null,
+ onTap: _creating
+ ? null
+ : () => unawaited(_chooseProject()),
+ ),
+ // Options, folded as the desktop folds them: branch, approvals and profile
+ // sit on their defaults until asked for.
+ TtyFormRow(
+ label: 'options',
+ // Left as it is nearly every time: folded to `[+]`.
+ value: _optionsOpen ? '[−]' : '[+]',
+ chevron: false,
onTap: () =>
- setState(() => _projectOpen = !_projectOpen),
+ setState(() => _optionsOpen = !_optionsOpen),
),
- if (_projectOpen) ...[
- // ⚠️ **First, and above the three ways of naming a folder the machine
- // does not know yet** — the desktop's own order, and the right one: on a
- // machine that has been worked on, the answer is nearly always a folder
- // that already exists. Absent where there is no history to search; the
- // Recent row below is absent then too, for the same reason.
- if (_recent.isNotEmpty)
- SettingsRow(
- title: 'Search project',
- nested: true,
- // ⚠️ It says RECENT, because this row is where the Recent list went.
- // "Find one by name or path" read as though it searched the machine's
- // disk — it searches the folders already worked in, and a row that
- // promises more than it holds is worse than one that promises less.
- detail: 'Recent folders, by name or path',
- leading: Icon(
- LucideIcons.search300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: Icon(
- LucideIcons.chevronRight300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- onTap: () => unawaited(_searchProject()),
- ),
- SettingsRow(
- title: 'Clone Repository',
- nested: true,
- detail:
- _projectSourceNote ??
- (_project?.repository == null
- ? 'Clone a GitHub repository'
- : _projectLabel),
- leading: Icon(
- LucideIcons.gitBranch300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: _check(_project?.repository != null),
- onTap: !_canMakeProject
+ if (_optionsOpen &&
+ (info != null || _gitLoading || _gitFailed))
+ TtyFormRow(
+ label: 'branch',
+ valueColor: info == null && !_gitLoading
+ ? tty.faint
+ : null,
+ value: _gitLoading
+ ? 'Reading…'
+ : info == null
+ ? 'No answer from the computer'
+ : _worktree
+ ? 'New worktree'
+ : _branchTitle,
+ detail: info == null
? null
- : () => unawaited(_pickRepository()),
+ : _worktree
+ ? 'from $_branchTitle, in its own folder'
+ : _branchNote,
+ onTap: info == null || _creating
+ ? null
+ : () => unawaited(_chooseBranch(info)),
),
- // Shows its path only when the choice is this row's own. A folder picked
- // from RECENT below is already named there, and printing it here too would
- // put one answer under two ticks.
- SettingsRow(
- title: 'Open Folder',
- nested: true,
- detail: _browsed ? _folder : null,
- leading: Icon(
- LucideIcons.folderSearch300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: _check(_browsed),
- onTap: () => unawaited(_browse()),
+ if (_optionsOpen && _permissionModes.isNotEmpty)
+ TtyFormRow(
+ label: 'approvals',
+ value: mode?.label ?? 'Auto-approve',
+ detail: mode?.detail,
+ valueColor: (mode?.risky ?? false) ? tty.red : null,
+ onTap: _creating
+ ? null
+ : () => unawaited(_chooseApprovals()),
),
- SettingsRow(
- title: 'New Project',
- nested: true,
- detail:
- _projectSourceNote ??
- 'A fresh folder, made on the machine',
- leading: Icon(
- LucideIcons.folderPlus300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: _check(
- _project != null && _project!.repository == null,
- ),
- onTap: !_canMakeProject
+ if (_optionsOpen && _showsCodexProfile)
+ TtyFormRow(
+ label: 'profile',
+ value: _codexProfile?.label ?? 'Default',
+ onTap: _creating
? null
- : () => setState(() {
- _project =
- const ProjectFolderRequest.newProject();
- _projectLabel = 'New project';
- _folder = null;
- _git = null;
- _gitFolder = null;
- _error = null;
- }),
+ : () => unawaited(_chooseProfile()),
),
- ],
],
),
- ..._branchSection(),
- // ⚠️ **"Agent" here means the ENGINE — Claude Code, Codex —
- // and that is the desktop's word, not a slip back into the
- // one this app spent a rename getting rid of.** The desktop
- // calls a running instance a HARNESS and the program it
- // runs an AGENT (`NewHarnessField.agent => 'Agent'`), so on
- // this form the two words sit one above the other meaning
- // two different things. Anywhere else in this app, a
- // harness is a harness.
- const SettingsCaption('AGENT'),
- SettingsGroup(
- children: [
- // The engine in one row, the rest behind it — see
- // [_projectOpen] for why nothing here is laid out flat.
- SettingsRow(
- title: _engineLabel,
- detail: _engine == null
- ? null
- : _engineNote(_engine!),
- leading: _engine == null
- ? Icon(
- LucideIcons.cpu300,
- size: 18,
- color: AppPalette.textSecondary,
- )
- : EngineMark(engine: _engine!, size: 18),
- trailing: Icon(
- _engineOpen
- ? LucideIcons.chevronUp300
- : LucideIcons.chevronDown300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- onTap: () =>
- setState(() => _engineOpen = !_engineOpen),
- ),
- if (_engineOpen)
- for (final identity in _shownEngines) ...[
- SettingsRow(
- title: _engineName(identity.id),
- nested: true,
- detail: _engineNote(identity.id),
- leading: EngineMark(
- engine: identity.id,
- size: 18,
- ),
- trailing: _check(_engine == identity.id),
- onTap: () => setState(() {
- _engine = identity.id;
- // See [_permissionMode]: a mode is one engine's
- // word, and the CLI refuses another's.
- _permissionMode = kDefaultPermissionMode;
- _error = null;
- }),
- ),
- // Codex's profiles belong UNDER Codex, not in a section of their own at
- // the foot of the page. They are a detail of one engine — a section
- // separated from the row that summons it reads as a second question,
- // and appearing at the bottom of a long list is how it went unnoticed.
- //
- // ⚠️ Only for the engine that has them, and only once the machine has
- // said it understands CODEX_HOME. Every other engine shows nothing here,
- // which is why this is a list inside the loop rather than a block after
- // it.
- if (identity.id == 'codex' &&
- _showsCodexProfile) ...[
- SettingsRow(
- title: 'Default profile',
- nested: true,
- detail: _codexProfilesLoaded
- ? null
- : 'Looking for others…',
- trailing: _check(_codexProfile == null),
- onTap: () =>
- setState(() => _codexProfile = null),
- ),
- for (final profile in _codexProfiles)
- SettingsRow(
- title: profile.label,
- detail: profile.path,
- nested: true,
- trailing: _check(_codexProfile == profile),
- onTap: () =>
- setState(() => _codexProfile = profile),
+ ),
+ if (typing) const Spacer(),
+ // The dock: the task, then Start. It rides the keyboard.
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 20,
+ Tty.origin,
+ 12,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // A first harness has nothing to go on: three first tasks to tap, the kind
+ // that shows what an agent does in a minute.
+ if (_task.text.trim().isEmpty && !_creating)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Wrap(
+ 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(
+ text: idea,
+ onTap: () => setState(() {
+ _task.value = TextEditingValue(
+ text: idea,
+ selection: TextSelection.collapsed(
+ offset: idea.length,
+ ),
+ );
+ }),
),
],
- ],
- // The rest of the engines, behind one row. It stays once opened: there is
- // nothing to fold back to that the person would want.
- if (_engineOpen &&
- !_moreEnginesOpen &&
- _hiddenEngineCount > 0)
- SettingsRow(
- title: '$_hiddenEngineCount more',
- leading: Icon(
- LucideIcons.ellipsis300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- onTap: () =>
- setState(() => _moreEnginesOpen = true),
),
- ],
- ),
- // ⚠️ **Its own caption, the way the desktop gives it its own row.** Approvals
- // is not a detail of which engine was picked — it is the one choice here that
- // decides what the harness may do to the machine while nobody is watching, and
- // a phone is exactly where nobody is watching. Folded under AGENT beside the
- // Codex profile, it read as another engine setting.
- //
- // Left out entirely for an engine with nothing to choose between: a row saying
- // "Not used by this agent" is a row that has to be read to learn it says
- // nothing.
- if (_permissionModes.isNotEmpty) ...[
- const SettingsCaption('APPROVALS'),
- SettingsGroup(
+ ),
+ Row(
children: [
- SettingsRow(
- title:
- _permissionModeChoice?.label ?? 'Auto-approve',
- detail: _permissionModeChoice?.detail,
- leading: Icon(
- LucideIcons.shieldCheck300,
- size: 18,
- color: _permissionModeChoice?.risky == true
- ? AppPalette.warn
- : AppPalette.textSecondary,
+ Expanded(
+ child: TtyText(
+ 'task (optional)',
+ color: tty.faint,
+ size: TtySize.meta,
),
- trailing: Icon(
- _approvalsOpen
- ? LucideIcons.chevronUp300
- : LucideIcons.chevronDown300,
- size: 18,
- color: AppPalette.textFaint,
+ ),
+ if (count > 1800)
+ TtyText(
+ '$count/$kFirstTaskMaxLength',
+ color: count > kFirstTaskMaxLength
+ ? tty.red
+ : tty.faint,
+ size: TtySize.meta,
),
- onTap: () => setState(
- () => _approvalsOpen = !_approvalsOpen,
+ ],
+ ),
+ const SizedBox(height: 6),
+ TtyField(
+ controller: _task,
+ hint: 'What should it do?',
+ lines: 6,
+ maxLength: kFirstTaskMaxLength,
+ action: TextInputAction.newline,
+ onChanged: (_) => setState(() {}),
+ trailing: [
+ Align(
+ alignment: Alignment.bottomRight,
+ child: ListenableBuilder(
+ listenable: _voiceIfAny ?? const _Silent(),
+ builder: (context, _) {
+ final status = _voiceIfAny?.status;
+ return TtyFieldMic(
+ live:
+ status == VoiceInputStatus.listening ||
+ status == VoiceInputStatus.starting,
+ onTap: _creating ? null : _talk,
+ );
+ },
),
),
- if (_approvalsOpen)
- for (final mode in _permissionModes)
- SettingsRow(
- title: mode.label,
- detail: mode.detail,
- nested: true,
- // The one that turns the engine's own safety net off wears the
- // danger ink every other row on this phone uses for "this cannot
- // be taken back". It is a mode like any other to the CLI, and not
- // to the person reading the list.
- destructive: mode.risky,
- trailing: _check(_permissionMode == mode.id),
- onTap: () =>
- setState(() => _permissionMode = mode.id),
- ),
],
),
- ],
- ],
- ),
- ),
- // ⚠️ The refusal belongs BESIDE the button, not at the end of the list above it.
- // It used to sit after the engines and the Codex profile — past nine rows and well
- // below the fold — while the button is pinned here. Pressing Create and being
- // refused looked exactly like pressing Create and nothing happening, because the
- // answer rendered somewhere nobody was looking.
- if (_error != null)
- Padding(
- padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
- child: Text(
- _error!,
- style: TextStyle(color: AppPalette.offline, fontSize: 13),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
- child: SizedBox(
- width: double.infinity,
- // ⚠️ **The rows' width and the rows' corner, but not their
- // height.** It sat narrower than the cards, shorter, and
- // rounder — three small differences that together read as
- // something from another screen, so the inset (16, the
- // list's) and the radius ([AppCard.radius]) are theirs. The
- // height is not: a solid accent bar as tall as a row is the
- // heaviest thing on a page whose other three items are
- // outlines, and it read as the page being built around the
- // button. 44 is what the folder sheet gives the controls a
- // thumb aims at, so every button in this flow is one height.
- height: 44,
- child: FilledButton(
- style: FilledButton.styleFrom(
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AppCard.radius),
- ),
- ),
- onPressed: ready ? () => unawaited(_create()) : null,
- child: Text(
- _creating ? 'Starting…' : 'Create Harness',
- style: const TextStyle(
- fontSize: 15,
- fontWeight: FontWeight.w600,
+ if (_error != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(
+ '✗ ${_error!}',
+ style: tty.style(
+ color: tty.red,
+ size: TtySize.meta,
+ ),
+ ),
+ ),
+ const SizedBox(height: 10),
+ TtyPrimaryButton(
+ // Says what it will do: start, or choose what is still missing first.
+ label: _failed
+ ? 'Try Again'
+ : ready
+ ? 'Start'
+ : _engine == null
+ ? 'Choose an agent'
+ : 'Choose a project',
+ busy: _creating,
+ busyLabel: 'Starting…',
+ // Never a dead button: with a choice missing, Start opens its chooser.
+ onPressed: () => unawaited(_start()),
),
- ),
+ ],
),
),
- ),
- ],
+ ],
+ ),
),
),
);
},
);
- /// BRANCH and Worktree, or nothing at all.
- ///
- /// ⚠️ **Absent rather than empty for a folder with no repository.** Most of
- /// what a phone starts is a fresh project or a clone, and a Branch row that
- /// could never be tapped would be two thirds of this form saying "not
- /// applicable". It appears the moment a folder turns out to be a checkout,
- /// which is also the moment it has something to offer.
- ///
- /// While the machine is still answering, the section is drawn with the row
- /// dimmed instead of appearing late under the thumb — a form that grows a
- /// section between reading it and pressing Create is how people press the
- /// wrong thing.
- List<Widget> _branchSection() {
- final info = _repository;
- // ⚠️ **Always drawn, whatever the folder turns out to be** — the desktop keeps Branch and
- // Worktree on the form and answers both with "Not a Git repository" (`new_harness_form.dart`,
- // `_blocked`). A section that comes and goes with the folder makes a person wonder what else
- // they have not been shown, and a missing Branch row is indistinguishable from an app that
- // cannot do branches. Where there is nothing to choose the rows are inert rather than absent.
- if (info == null && !_gitLoading) {
- // A machine that could not answer is not the same as a folder that is not a checkout, and
- // the difference is worth a sentence: one of them is worth trying again.
- final reason = _gitFailed
- ? 'The machine did not answer'
- : 'Not a Git repository';
- return [
- const SettingsCaption('BRANCH'),
- SettingsGroup(
- children: [
- SettingsRow(
- title: 'Branch',
- value: reason,
- detail: _gitFailed
- ? 'The harness still starts in the folder, on the branch it '
- 'is on.'
- : null,
- leading: Icon(
- LucideIcons.gitBranch300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- ),
- SettingsRow(
- title: 'Worktree',
- value: reason,
- leading: Icon(
- LucideIcons.gitFork300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- ),
- ],
+ /// The branch row: this folder as it is, or a new worktree — and any other branch behind them.
+ Future<void> _chooseBranch(GitProjectInfo info) async {
+ final here = info.branch ?? 'This folder';
+ final picked = await showNewAgentChooser<String>(
+ context,
+ title: 'Branch',
+ hint: 'Search branches',
+ items: [
+ ChooserItem(
+ value: 'here',
+ title: here,
+ subtitle: 'this folder, as it is',
+ selected: !_worktree && _branchName == null,
),
- ];
+ ChooserItem(
+ value: 'worktree',
+ title: 'New Worktree',
+ subtitle: 'a new branch from $here, in its own folder',
+ selected: _worktree,
+ ),
+ ],
+ actions: const [
+ ChooserItem(
+ value: 'other',
+ title: 'Other Branch',
+ subtitle: 'start from another branch, or name a new one',
+ ),
+ ],
+ );
+ if (picked == null || !mounted) return;
+ switch (picked) {
+ case 'here':
+ setState(() {
+ _worktree = false;
+ _branchRef = defaultBranchRef(info, worktree: false);
+ _branchName = null;
+ _error = null;
+ });
+ case 'worktree':
+ setState(() {
+ _worktree = true;
+ _branchRef = defaultBranchRef(info, worktree: true);
+ _error = null;
+ });
+ case 'other':
+ await _pickBranch(info);
}
- return [
- const SettingsCaption('BRANCH'),
- SettingsGroup(
- children: [
- SettingsRow(
- title: _gitLoading ? 'Reading the repository…' : _branchTitle,
- detail: _gitLoading ? null : _branchNote,
- leading: Icon(
- LucideIcons.gitBranch300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- // A chevron pointing RIGHT, not a fold arrow: this row opens a
- // sheet rather than unfolding under itself.
- trailing: _gitLoading
- ? null
- : Icon(
- LucideIcons.chevronRight300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- onTap: _gitLoading || info == null
- ? null
- : () => unawaited(_pickBranch(info)),
+ }
+
+ /// A home folder written the way a shell prints it.
+ static String _tilde(String path) =>
+ path.replaceFirst(RegExp(r'^/(Users|home)/[^/]+'), '~');
+
+ /// How far the current drag has gone right — see the swipe back in [build].
+ double _swipedBack = 0;
+
+ /// The last project started on this machine, else its most recent one — the desktop's rule. No
+ /// project yet leaves the row on "Choose project", which the button then asks for.
+ void _applyDefaultProject() {
+ if (_folder != null || _project != null || _projectDefaulted) return;
+ final history = widget.notifier.projectHistory;
+ // Then, with no history on this phone: the folder of the computer's most recent harness —
+ // someone who has only ever started harnesses on the desktop still opens New ready to Start.
+ final folder =
+ widget.folder ??
+ history.selected(_machineId) ??
+ history.recent(_machineId).firstOrNull ??
+ _latestAgentFolder();
+ if (folder == null) return;
+ _projectDefaulted = true;
+ _folder = folder;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _folder == folder) unawaited(_loadGit(folder));
+ });
+ }
+
+ /// A folder Harness made for a harness's worktree — `~/harnesses/worktrees/<repo>/<name>`.
+ static bool _isHarnessWorktree(String folder) =>
+ folder.contains('/harnesses/worktrees/');
+
+ String? _latestAgentFolder() {
+ final agents = [...?_machine?.agents]
+ ..sort(
+ (a, b) =>
+ (b.updatedAt ?? DateTime(0)).compareTo(a.updatedAt ?? DateTime(0)),
+ );
+ for (final agent in agents) {
+ final path = agent.project?.root ?? agent.project?.cwd;
+ if (path != null && path.isNotEmpty) return path;
+ }
+ return null;
+ }
+
+ /// Set once the default project has been applied, so a person who clears it is not handed it
+ /// back on the next build.
+ bool _projectDefaulted = false;
+
+ /// The project on one line: `computer:name`. The full path is in the chooser.
+ String get _projectValue {
+ final String name;
+ if (_folder case final folder?) {
+ name = _basename(folder);
+ } else if (_project?.repository case final repository?) {
+ name = repository.name;
+ } else if (_project != null) {
+ name = 'New folder';
+ } else {
+ return 'Choose project';
+ }
+ // One line, `computer:name` — always the computer, as the title on Focus and every Find row
+ // write it. Most repositories live in a folder of the same name; the full path is in the
+ // chooser.
+ final machine = _machine?.machine.displayName;
+ return machine == null ? name : '$machine:$name';
+ }
+
+ /// The button: a missing choice opens its chooser and says why, the desktop's `requiredChoice`.
+ Future<void> _start() async {
+ // The keyboard goes with the form: the new harness should open on its terminal and the mic,
+ // not on a keyboard left up from typing the task.
+ FocusManager.instance.primaryFocus?.unfocus();
+ if (_engine == null) {
+ setState(() => _error = 'Choose an agent.');
+ await _chooseAgent();
+ return;
+ }
+ if (_folder == null && _project == null) {
+ setState(() => _error = 'Choose a project.');
+ await _chooseProject();
+ return;
+ }
+ await _create();
+ }
+
+ Future<void> _chooseAgent() async {
+ final machine = _machine;
+ // Claude Code and Codex first — what nearly everyone runs — then the rest A to Z behind `more`.
+ const first = ['claude', 'codex'];
+ final ids = {for (final identity in _engines) identity.id, ?_engine};
+ final ordered = [
+ for (final id in first)
+ if (ids.contains(id)) id,
+ ...(ids.where((id) => !first.contains(id)).toList()
+ ..sort((a, b) => _engineName(a).compareTo(_engineName(b)))),
+ ];
+ final picked = await showNewAgentChooser<String>(
+ context,
+ title: 'Agent',
+ hint: 'Search agents',
+ fold: ordered.where(first.contains).length,
+ items: [
+ for (final id in ordered)
+ ChooserItem(
+ value: id,
+ title: _engineName(id),
+ subtitle: _engineNote(id),
+ leading: EngineMark(engine: id, size: 18),
+ selected: id == _engine,
+ enabled:
+ machine == null ||
+ !machine.engines.loaded ||
+ _engineNote(id) == null,
),
- // ⚠️ Beside the branch row, never inside what opens from it. It
- // changes what that row MEANS — with it off the folder itself moves
- // to the branch, with it on the harness gets a checkout of its own —
- // so it has to be readable at the same time as the answer it
- // qualifies.
- if (info == null)
- // Still reading. Drawn without an answer rather than left out, so
- // the row does not arrive under a thumb already on its way down.
- SettingsRow(
- title: 'Worktree',
- leading: Icon(
- LucideIcons.gitFork300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- )
- else
- SettingsRow(
- title: 'Worktree',
- detail: _worktree
- ? 'A checkout of its own, beside the folder'
- : 'Work in the folder itself',
- leading: Icon(
- LucideIcons.gitFork300,
- size: 18,
- color: AppPalette.textSecondary,
- ),
- trailing: Switch.adaptive(
- value: _worktree,
- onChanged: (value) => setState(() {
- _worktree = value;
- // The base a branch starts from is read differently by each
- // — see [defaultBranchRef] — so a ref chosen for one is not
- // an answer to the other.
- _branchRef = defaultBranchRef(info, worktree: value);
- _error = null;
- }),
- ),
- onTap: () => setState(() {
- _worktree = !_worktree;
- _branchRef = defaultBranchRef(info, worktree: _worktree);
- _error = null;
- }),
- ),
- ],
- ),
+ ],
+ );
+ if (picked == null || !mounted) return;
+ setState(() {
+ if (picked != _engine) _permissionMode = kDefaultPermissionMode;
+ _engineChosen = true;
+ _engine = picked;
+ _error = null;
+ });
+ }
+
+ /// Every machine's projects as `machine · folder` pairs — this machine first, then the rest —
+ /// with Clone Repository, Open Folder and New Folder above them, as the desktop lists them.
+ /// Choosing a pair on another machine moves the harness there.
+ Future<void> _chooseProject() async {
+ final notifier = widget.notifier;
+ final machines = [
+ ?_machine,
+ for (final other in _machines)
+ if (other.machine.machineId != _machineId) other,
];
+ final pairs = <ChooserItem<_ProjectChoice>>[];
+ for (final machine in machines) {
+ final id = machine.machine.machineId;
+ // Worktrees Start made are temporary: their repository is the project, and it is listed
+ // once it has been chosen (the desktop's `_recentProjectFolders`).
+ final folders = <String>{
+ if (id == _machineId) ?_folder,
+ for (final folder in [
+ ...notifier.projectHistory.recent(id),
+ for (final agent in machine.agents)
+ if (agent.project?.root ?? agent.project?.cwd case final path?)
+ path,
+ ])
+ if (folder.isNotEmpty && !_isHarnessWorktree(folder)) folder,
+ };
+ for (final folder in folders) {
+ pairs.add(
+ ChooserItem(
+ value: _ProjectChoice.folder(id, folder),
+ title: _basename(folder),
+ subtitle: '${machine.machine.displayName}:${_tilde(folder)}',
+ icon: LucideIcons.folder300,
+ selected: id == _machineId && folder == _folder,
+ ),
+ );
+ }
+ }
+ final here = _machine?.machine.displayName ?? 'this machine';
+ final canMake = _canMakeProject;
+ final picked = await showNewAgentChooser<_ProjectChoice>(
+ context,
+ title: 'Project',
+ hint: 'Search projects',
+ actions: [
+ ChooserItem(
+ value: const _ProjectChoice.open(),
+ title: 'Open Folder',
+ subtitle: 'Any folder on $here',
+ icon: LucideIcons.folderSearch300,
+ ),
+ ChooserItem(
+ value: const _ProjectChoice.clone(),
+ title: 'Clone Repository',
+ subtitle: _projectSourceNote ?? 'A GitHub repository, on $here',
+ icon: LucideIcons.gitBranch300,
+ enabled: canMake,
+ ),
+ ChooserItem(
+ value: const _ProjectChoice.newFolder(),
+ title: 'New Folder',
+ subtitle: _projectSourceNote ?? 'A fresh folder, made on $here',
+ icon: LucideIcons.folderPlus300,
+ enabled: canMake,
+ ),
+ ],
+ items: pairs,
+ );
+ if (picked == null || !mounted) return;
+ switch (picked.kind) {
+ case _ProjectChoiceKind.clone:
+ await _pickRepository();
+ case _ProjectChoiceKind.open:
+ await _browse();
+ case _ProjectChoiceKind.newFolder:
+ setState(() {
+ _project = const ProjectFolderRequest.newProject();
+ _projectLabel = 'New folder';
+ _folder = null;
+ _git = null;
+ _gitFolder = null;
+ _error = null;
+ });
+ case _ProjectChoiceKind.folder:
+ final machineId = picked.machineId!, folder = picked.folder!;
+ if (machineId != _machineId) _selectMachine(machineId);
+ setState(() {
+ _projectDefaulted = true;
+ _folder = folder;
+ _project = null;
+ _projectLabel = null;
+ _error = null;
+ });
+ unawaited(_loadGit(folder));
+ }
+ }
+
+ Future<void> _chooseApprovals() async {
+ final picked = await showNewAgentChooser<String>(
+ context,
+ title: 'Approvals',
+ hint: 'How much it may do without asking',
+ items: [
+ for (final mode in _permissionModes)
+ ChooserItem(
+ value: mode.id,
+ title: mode.label,
+ subtitle: mode.detail,
+ icon: LucideIcons.shieldCheck300,
+ selected: mode.id == _permissionMode,
+ warn: mode.risky,
+ ),
+ ],
+ );
+ if (picked == null || !mounted) return;
+ setState(() => _permissionMode = picked);
+ }
+
+ Future<void> _chooseProfile() async {
+ final picked = await showNewAgentChooser<LocalCodexProfile?>(
+ context,
+ title: 'Profile',
+ hint: 'Search profiles',
+ items: [
+ ChooserItem(
+ value: null,
+ title: 'Default',
+ subtitle: _codexProfilesLoaded ? null : 'Looking for others…',
+ icon: LucideIcons.user300,
+ selected: _codexProfile == null,
+ ),
+ for (final profile in _codexProfiles)
+ ChooserItem(
+ value: profile,
+ title: profile.label,
+ subtitle: profile.path,
+ icon: LucideIcons.user300,
+ selected: _codexProfile == profile,
+ ),
+ ],
+ );
+ if (!mounted) return;
+ setState(() => _codexProfile = picked);
}
/// The branch row: the picker, and the name dialog behind its first entry.
@@ -1246,10 +1329,6 @@ class _NewAgentPageState extends State<NewAgentPage> {
_error = null;
});
}
-
- Widget? _check(bool selected) => selected
- ? Icon(LucideIcons.check300, size: 18, color: AppPalette.accent)
- : null;
}
/// A branch name, cleaned the way Git would take it.
@@ -1391,3 +1470,69 @@ class _RepositoryDialogState extends State<_RepositoryDialog> {
);
}
}
+
+enum _ProjectChoiceKind { folder, clone, open, newFolder }
+
+/// What the Project chooser hands back: a `machine · folder` pair, or one of its three actions.
+class _ProjectChoice {
+ const _ProjectChoice.folder(String this.machineId, String this.folder)
+ : kind = _ProjectChoiceKind.folder;
+ const _ProjectChoice.clone()
+ : kind = _ProjectChoiceKind.clone,
+ machineId = null,
+ folder = null;
+ const _ProjectChoice.open()
+ : kind = _ProjectChoiceKind.open,
+ machineId = null,
+ folder = null;
+ const _ProjectChoice.newFolder()
+ : kind = _ProjectChoiceKind.newFolder,
+ machineId = null,
+ folder = null;
+
+ final _ProjectChoiceKind kind;
+ final String? machineId;
+ final String? folder;
+}
+
+/// A listenable that never speaks — the mic's before a recorder exists.
+class _Silent implements Listenable {
+ const _Silent();
+
+ @override
+ void addListener(VoidCallback listener) {}
+
+ @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/phone_destination.dart b/mobile/lib/phone/phone_destination.dart
index 32ed84e1a..dc1d6f0f5 100644
--- a/mobile/lib/phone/phone_destination.dart
+++ b/mobile/lib/phone/phone_destination.dart
@@ -1,5 +1,6 @@
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/session_preview.dart';
+import 'package:harness_mobile/state/external_session.dart';
import 'agent_index.dart';
import 'phone_prompt_context.dart';
@@ -27,6 +28,10 @@ enum PhoneDestinationKind {
/// A `?` row: it rewrites the query in place instead of opening anything.
mode,
+
+ /// A Claude Code or Codex conversation Harness did not start, found by what was said in it.
+ /// Opening it resumes it as a new harness — see [PhoneDestination.external].
+ external,
}
/// One row the search can offer, whichever of the catalogs it came from.
@@ -59,6 +64,8 @@ class PhoneDestination {
this.members = const {},
this.entry,
this.machine,
+ this.external,
+ this.lastAt,
Iterable<String?> searchFields = const [],
int titleFields = 1,
}) : fields = [
@@ -136,7 +143,14 @@ class PhoneDestination {
/// match there outranks any match in a folder, a machine or a recap.
final int titleFieldCount;
+ /// A conversation Harness did not start — [PhoneDestinationKind.external].
+ final ExternalSessionRef? external;
+
+ /// When [external] was last worked on, from the hit that found it.
+ final DateTime? lastAt;
+
bool get isAgent => kind == PhoneDestinationKind.agent;
+ bool get isExternal => kind == PhoneDestinationKind.external;
bool get isProject => kind == PhoneDestinationKind.project;
bool get isMachine => kind == PhoneDestinationKind.machine;
bool get isCommand => kind == PhoneDestinationKind.command;
diff --git a/mobile/lib/phone/phone_header.dart b/mobile/lib/phone/phone_header.dart
index d667c511f..082686b28 100644
--- a/mobile/lib/phone/phone_header.dart
+++ b/mobile/lib/phone/phone_header.dart
@@ -138,7 +138,7 @@ class _Titles extends StatelessWidget {
style: TextStyle(
color: AppPalette.textPrimary,
fontSize: large ? 32 : 17,
- fontWeight: large ? FontWeight.w700 : FontWeight.w600,
+ fontWeight: large ? FontWeight.w600 : FontWeight.w600,
letterSpacing: large ? -0.6 : -0.2,
),
),
diff --git a/mobile/lib/phone/phone_search_actions.dart b/mobile/lib/phone/phone_search_actions.dart
index 36f96c775..76834c609 100644
--- a/mobile/lib/phone/phone_search_actions.dart
+++ b/mobile/lib/phone/phone_search_actions.dart
@@ -9,6 +9,7 @@ import 'phone_navigation.dart';
import 'phone_search_commands.dart';
import 'phone_status.dart';
import 'settings_page.dart';
+import 'welcome/how_it_works.dart';
/// What `>` offers on the phone, and so what `?` lists under its three modes.
///
@@ -35,25 +36,31 @@ List<PhoneCommand> phoneSearchCommands(
title: 'New Harness',
detail: ready.length == 1
? 'On ${ready.first.machine.displayName}'
- : 'Choose a machine, then an engine',
+ : 'Choose a computer, then an agent',
run: () =>
openNewAgent(context, notifier, ready.first.machine.machineId),
),
PhoneCommand(
id: 'navigation.agents',
title: 'All harnesses',
- detail: 'Every harness on the account, by machine',
- run: () => Navigator.of(
- context,
- ).push(phoneRoute((_) => AgentsListPage(notifier: notifier))),
+ detail: 'Every harness on the account, by computer',
+ run: () =>
+ Navigator.of(context)
+ .push(phoneRoute((_) => AgentsListPage(notifier: notifier))),
),
PhoneCommand(
id: 'app.settings',
title: 'Settings',
detail: 'Appearance · terminal · account',
- run: () => Navigator.of(context).push(
- phoneRoute((_) => SettingsPage(notifier: notifier, large: false)),
- ),
+ run: () => Navigator.of(
+ context,
+ ).push(phoneRoute((_) => SettingsPage(notifier: notifier, large: false))),
+ ),
+ PhoneCommand(
+ id: 'app.help',
+ title: 'Help: how Harness works',
+ detail: 'Computers, agents, harnesses and the gestures',
+ run: () => openHowItWorks(context),
),
];
}
diff --git a/mobile/lib/phone/phone_search_commands.dart b/mobile/lib/phone/phone_search_commands.dart
index cc1db3501..b9ccc6080 100644
--- a/mobile/lib/phone/phone_search_commands.dart
+++ b/mobile/lib/phone/phone_search_commands.dart
@@ -44,6 +44,7 @@ List<PhoneDestination> phoneSearchModes(List<PhoneCommand> commands) => [
_mode('commands', '> Commands', 'Run anything by name', '> '),
_mode('projects', '# Projects', 'Choose a project, then one of its harnesses', '# '),
_mode('machines', '@ Machines', 'Choose a machine, then one of its harnesses', '@ '),
+ _mode('models', ': Models', 'Local models, shared models, subscriptions', ': '),
for (final command in commands) command.destination,
];
diff --git a/mobile/lib/phone/phone_search_controller.dart b/mobile/lib/phone/phone_search_controller.dart
index 036b3876b..f8a43ecd4 100644
--- a/mobile/lib/phone/phone_search_controller.dart
+++ b/mobile/lib/phone/phone_search_controller.dart
@@ -4,6 +4,9 @@ import 'package:flutter/foundation.dart';
import 'package:harness_mobile/core/phone_search_history.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/external_session.dart';
+import 'package:harness_mobile/state/search_when.dart';
+import 'package:harness_mobile/state/session_content_search.dart';
import 'phone_destination.dart';
import 'phone_search_catalog.dart';
@@ -15,8 +18,7 @@ import 'phone_search_rank.dart';
/// The desktop's `kSwarmSearchHint`, word for word. It searches four kinds of
/// thing, and a hint that named only one of them ("Search agents") was most of
/// why nobody on the phone knew the other three existed.
-const kPhoneSearchHint =
- 'Search harnesses > commands # projects @ machines ? help';
+const kPhoneSearchHint = 'Search harnesses';
/// One search session, shared by the field and its results.
///
@@ -24,10 +26,12 @@ const kPhoneSearchHint =
/// `#` projects, `@` machines, `?` help, and the group scope that choosing a
/// project or a machine drops you into.
///
-/// ⚠️ **Keystrokes never ask a machine anything.** They filter the catalog the
-/// app already holds — agents, machines, projects, and the session content
-/// [AppNotifier.sessionPreviews] has cached — so typing on two bars of signal
-/// stays instant and costs no data.
+/// Keystrokes filter the catalog the app already holds — agents, machines, projects and the
+/// session content [AppNotifier.sessionPreviews] has cached — so the list answers at once. A pause
+/// in typing (110ms) also asks every connected machine's session index what was said in each
+/// conversation (`session_search`, the desktop Cmd-P's search — see
+/// docs/research/2026-09-26-session-search.md); its hits join the ranking as they arrive. Only
+/// the hits leave a machine, sealed like every other request.
///
/// What the desktop has and this does not: panes, tabs, placement, splits, the
/// preview panel, and the "New Harness" row. All four are about WHERE a result
@@ -37,8 +41,14 @@ class PhoneSearchController extends ChangeNotifier {
required this.notifier,
this.history,
this.commands,
+ this.modes = true,
}) {
_catalog = _cache.read(notifier);
+ _content = SessionContentSearch(
+ machines: () => notifier.searchableMachineIds,
+ ask: (machineId, words, when) =>
+ notifier.searchSessions(machineId, words, when: when),
+ )..addListener(_contentChanged);
_filter();
notifier.addListener(_rebuild);
notifier.sessionPreviews.addListener(_previewChanged);
@@ -55,7 +65,76 @@ class PhoneSearchController extends ChangeNotifier {
/// no agent is open.
final List<PhoneCommand> Function()? commands;
+ /// Whether a leading `>` `#` `@` `?` switches the box into commands, projects, machines or help.
+ ///
+ /// Off in Find (`TerminalSearchOverlay`): a phone searches its agents, and a query is read as
+ /// typed. The modes were the desktop's command palette carried over.
+ final bool modes;
+
final _cache = PhoneSearchCatalogCache();
+
+ /// What every machine's session index found for the query — see [contentHitFor].
+ late final SessionContentSearch _content;
+
+ /// The query the machines' session indexes last answered, or null before any answer.
+ String? get contentAnswered => _content.answered;
+
+ /// What a machine's session index found in this row's conversation for the current query.
+ SessionContentHit? contentHitFor(String rowId) =>
+ _contentQuery.isEmpty ? null : _content.hitsFor(_contentQuery)[rowId];
+
+ /// When the query says to look ("dial last week"), and its words without that.
+ ({String words, SearchWhen? when}) get _read => _contentQuery.isEmpty
+ ? (words: matchQuery, when: null)
+ : _content.read(_contentQuery);
+
+ /// The words matched against names and lit in the rows: the query less any time phrase.
+ String get wordsQuery => _read.words;
+
+ /// What the session indexes are asked: a plain harness search only, never a command or a mode.
+ String get _contentQuery => _listsAgents ? matchQuery : '';
+
+ void _contentChanged() {
+ if (_disposed) return;
+ _filter();
+ notifyListeners();
+ }
+
+ /// A Find row for a conversation Harness did not start, from the hit that found it: its title (or
+ /// what was first asked), and where it ran — the desktop's `externalSessionDestination`.
+ PhoneDestination _externalRow(
+ SessionContentHit hit,
+ ExternalSessionRef external,
+ ) {
+ final machine = notifier.stateOf(hit.machineId)?.machine.displayName ?? '';
+ return PhoneDestination(
+ id: hit.destinationId,
+ kind: PhoneDestinationKind.external,
+ title: external.title.isEmpty ? 'Untitled conversation' : external.title,
+ detail: '$machine:${external.folderName}',
+ machineId: hit.machineId,
+ machineLabel: machine,
+ engine: external.engine,
+ external: external,
+ lastAt: hit.lastAt ?? hit.at,
+ searchFields: [external.folderName, external.cwd, external.engineLabel],
+ );
+ }
+
+ /// With a time in the query, the rows worked on then: the conversation last moved in it, or a
+ /// machine vouches it saw a turn in it.
+ List<PhoneDestination> _within(List<PhoneDestination> rows) {
+ final when = _read.when;
+ if (when == null) return rows;
+ final hits = _content.hitsFor(_contentQuery);
+ bool then(DateTime? at) =>
+ at != null && !at.isBefore(when.from) && !at.isAfter(when.to);
+ return [
+ for (final row in rows)
+ if (hits.containsKey(row.id) || then(row.entry?.agent.updatedAt)) row,
+ ];
+ }
+
List<PhoneDestination> _catalog = const [];
Set<String> _commandIds = const {};
@@ -69,14 +148,18 @@ class PhoneSearchController extends ChangeNotifier {
int total = 0;
int matchCount = 0;
- static final _quickAccessPrefix = RegExp(r'^[>@#?]');
+ static final _quickAccessPrefix = RegExp(r'^[>@#?:]');
static final _commandPrefix = RegExp(r'^>\s*');
static final _helpPrefix = RegExp(r'^\?\s*');
- bool get isCommandMode => query.trimLeft().startsWith('>');
- bool get isHelpMode => query.trimLeft().startsWith('?');
- bool get isProjectMode => query.trimLeft().startsWith('#');
- bool get isMachineMode => query.trimLeft().startsWith('@');
+ bool get isCommandMode => modes && query.trimLeft().startsWith('>');
+ bool get isHelpMode => modes && query.trimLeft().startsWith('?');
+ bool get isProjectMode => modes && query.trimLeft().startsWith('#');
+ bool get isMachineMode => modes && query.trimLeft().startsWith('@');
+
+ /// `:` — the models the agent on screen can run on, the desktop ⌘P's `:`. Drawn by Find itself
+ /// (it needs the machine's grid, asked for as the mode opens), so this list stays empty.
+ bool get isModelMode => modes && query.trimLeft().startsWith(':');
bool get isGroupMode => isProjectMode || isMachineMode;
String get commandQuery => query.trimLeft().replaceFirst(_commandPrefix, '');
@@ -94,7 +177,7 @@ class PhoneSearchController extends ChangeNotifier {
? commandQuery
: isHelpMode
? helpQuery
- : isGroupMode
+ : isGroupMode || isModelMode
? query.trimLeft().substring(1).trimLeft()
: query;
@@ -106,6 +189,8 @@ class PhoneSearchController extends ChangeNotifier {
? 'Projects'
: isMachineMode
? 'Machines'
+ : isModelMode
+ ? 'Models'
: _groupScope != null
? 'Harnesses · ${_groupScope!.name}'
: 'Search';
@@ -120,15 +205,20 @@ class PhoneSearchController extends ChangeNotifier {
? 'Search projects…'
: isMachineMode
? 'Search machines…'
+ : isModelMode
+ ? 'Search models…'
: kPhoneSearchHint;
void setQuery(String value) {
if (query == value) return;
// Typing a mode character leaves whatever group was chosen: `@` means "pick
// a machine", which is not a thing to do inside one.
- if (_quickAccessPrefix.hasMatch(value.trimLeft())) _groupScope = null;
+ if (modes && _quickAccessPrefix.hasMatch(value.trimLeft())) {
+ _groupScope = null;
+ }
query = value;
_filter();
+ _content.search(_contentQuery);
notifyListeners();
}
@@ -150,6 +240,7 @@ class PhoneSearchController extends ChangeNotifier {
_groupScope = null;
query = '';
_filter();
+ _content.search('');
notifyListeners();
}
@@ -188,12 +279,19 @@ class PhoneSearchController extends ChangeNotifier {
PhoneDestinationKind.agent => row.entry?.isOpenable ?? false,
// A locked machine opens its password form, which is the thing to do about
// it; a switched-off one has nothing to take a password.
- PhoneDestinationKind.machine =>
- _catalog.any((entry) => entry.id == row.id && entry.isMachine),
- PhoneDestinationKind.project =>
- _catalog.any((entry) => entry.id == row.id && entry.isProject),
+ PhoneDestinationKind.machine => _catalog.any(
+ (entry) => entry.id == row.id && entry.isMachine,
+ ),
+ PhoneDestinationKind.project => _catalog.any(
+ (entry) => entry.id == row.id && entry.isProject,
+ ),
PhoneDestinationKind.command => _commandIds.contains(row.id),
PhoneDestinationKind.mode => true,
+ // Not while it is open in a terminal or an app elsewhere — two processes would write one
+ // conversation — nor while its machine cannot be asked.
+ PhoneDestinationKind.external =>
+ !(row.external?.open ?? true) &&
+ notifier.searchableMachineIds.contains(row.machineId),
};
void _rebuild() {
@@ -245,6 +343,13 @@ class PhoneSearchController extends ChangeNotifier {
bool _disposed = false;
void _filter() {
+ if (isModelMode) {
+ rows = const [];
+ total = 0;
+ matchCount = 0;
+ _commandIds = const {};
+ return;
+ }
if (isHelpMode) {
// The modes keep the order they are taught in; what follows `?` only
// narrows them, the way a quick-open's own `?` does.
@@ -263,8 +368,7 @@ class PhoneSearchController extends ChangeNotifier {
}
final available = isCommandMode
? [
- for (final command
- in commands?.call() ?? const <PhoneCommand>[])
+ for (final command in commands?.call() ?? const <PhoneCommand>[])
command.destination,
]
: const <PhoneDestination>[];
@@ -279,9 +383,15 @@ class PhoneSearchController extends ChangeNotifier {
final candidates = isCommandMode
? available
: isProjectMode
- ? [for (final row in _catalog) if (row.isProject) row]
+ ? [
+ for (final row in _catalog)
+ if (row.isProject) row,
+ ]
: isMachineMode
- ? [for (final row in _catalog) if (row.isMachine) row]
+ ? [
+ for (final row in _catalog)
+ if (row.isMachine) row,
+ ]
: scoped != null
? [
for (final row in _catalog)
@@ -299,20 +409,38 @@ class PhoneSearchController extends ChangeNotifier {
if (row.isAgent) row,
];
total = candidates.length;
+ _findExtras();
+ // Conversations Harness did not start, found by what was said in them: a row only while a
+ // search matches one, never in the list as it opens — the desktop Cmd-P's rule.
+ final found = _contentQuery.isEmpty || _groupScope != null || isCommandMode
+ ? candidates
+ : [
+ ...candidates,
+ for (final hit in _content.hitsFor(_contentQuery).values)
+ if (hit.external case final external?
+ when !candidates.any((row) => row.id == hit.destinationId))
+ _externalRow(hit, external),
+ ];
rows = isCommandMode
? _recentFirst(rankPhoneDestinations(candidates, commandQuery))
: rankPhoneDestinations(
- candidates,
- matchQuery,
+ _within(found),
+ wordsQuery,
recent: history?.recent ?? const <String>[],
previews: notifier.sessionPreviews,
+ byActivity: _listsAgents,
+ contentHits: _contentQuery.isEmpty
+ ? null
+ : _content.hitsFor(_contentQuery),
);
matchCount = rows.length;
// ⚠️ **Not with nothing typed.** That list is the desktop's Harness Monitor
// order ([rankPhoneDestinations]), where paused work sits among the rest by
// when it last moved — moving it to the bottom here is the phone's list
// disagreeing with the laptop's again.
- if (_listsMonitorOrder) return;
+ // A list of agents keeps its last-use order whole, the desktop ⌘P's rule — a row that cannot be
+ // opened stays where it is, dimmed, rather than sinking. See [rankPhoneDestinations].
+ if (_listsAgents) return;
// Keep the match order, but put rows a tap can open first. An agent whose
// terminal has gone must not bury the ones that answer.
final open = <PhoneDestination>[];
@@ -324,13 +452,56 @@ class PhoneSearchController extends ChangeNotifier {
matchCount = rows.length;
}
+ /// With a plain query typed: the commands that match it, best first — Find's `commands` section
+ /// under the harnesses. Empty with nothing typed, in a mode, or inside a project or machine.
+ List<PhoneDestination> commandMatches = const [];
+
+ /// The project that best matches a plain query — Find's `+ New Harness in <project>`.
+ PhoneDestination? projectMatch;
+
+ void _findExtras() {
+ final plain =
+ _listsAgents && _groupScope == null && matchQuery.trim().isNotEmpty;
+ if (!plain) {
+ commandMatches = const [];
+ projectMatch = null;
+ return;
+ }
+ final available = [
+ for (final command in commands?.call() ?? const <PhoneCommand>[])
+ command.destination,
+ ];
+ _commandIds = {..._commandIds, for (final row in available) row.id};
+ // By name only: a command whose description merely mentions the letters ("ap" in Settings'
+ // "Appearance") is noise under the harnesses.
+ final needle = matchQuery.trim().toLowerCase();
+ commandMatches = rankPhoneDestinations(available, matchQuery)
+ .where(
+ (row) =>
+ row.title
+ .toLowerCase()
+ .split(RegExp(r'\s+'))
+ .any((word) => word.startsWith(needle)) ||
+ row.title.toLowerCase().startsWith(needle),
+ )
+ .take(3)
+ .toList();
+ projectMatch = rankPhoneDestinations([
+ for (final row in _catalog)
+ if (row.isProject) row,
+ ], matchQuery).firstOrNull;
+ }
+
/// Whether [rows] are agents with nothing typed — the list that follows the
/// desktop's monitor.
- bool get _listsMonitorOrder =>
+ /// Whether the rows are agents — the plain list, or one project's or machine's — rather than
+ /// commands, projects or machines.
+ bool get _listsAgents =>
!isCommandMode &&
+ !isHelpMode &&
!isProjectMode &&
!isMachineMode &&
- matchQuery.trim().isEmpty;
+ !isModelMode;
/// With nothing typed, the commands run lately lead, newest first; the rest
/// keep their order. Once something is typed, the match decides.
@@ -352,6 +523,9 @@ class PhoneSearchController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
+ _content
+ ..removeListener(_contentChanged)
+ ..dispose();
notifier.removeListener(_rebuild);
notifier.sessionPreviews.removeListener(_previewChanged);
super.dispose();
diff --git a/mobile/lib/phone/phone_search_field.dart b/mobile/lib/phone/phone_search_field.dart
index ea5fce988..5b06d4448 100644
--- a/mobile/lib/phone/phone_search_field.dart
+++ b/mobile/lib/phone/phone_search_field.dart
@@ -150,14 +150,23 @@ class SheetSearchField extends StatelessWidget {
required this.onClear,
required this.hintText,
this.onCancel,
+ this.onNew,
+ this.onSubmitted,
});
+ /// The return key: Find opens the top row, as Enter does in the desktop's ⌘P.
+ final VoidCallback? onSubmitted;
+
final TextEditingController controller;
final FocusNode focus;
final ValueChanged<String> onChanged;
final VoidCallback onClear;
final String hintText;
+ /// A `+` beside the box, for a new agent. Null leaves it out — and it IS null while [onCancel] is
+ /// set, so the two never stand side by side.
+ final VoidCallback? onNew;
+
/// "Cancel", beside the box. Null leaves it out.
///
/// Set for as long as the sheet is searching: it ends the SEARCH — results
@@ -207,10 +216,11 @@ class SheetSearchField extends StatelessWidget {
controller: controller,
focus: focus,
onChanged: onChanged,
- // The sheet is opened to read its tabs, and focus is
- // what trades them for the results.
+ // Opened to read the recent agents; focus is what
+ // brings the keyboard.
autofocus: false,
hintText: hintText,
+ onSubmitted: onSubmitted,
// The query's own size, and ink a step under it: the
// hint is one short phrase here, and iOS draws its
// placeholder bright enough to be read at a glance.
@@ -227,12 +237,48 @@ class SheetSearchField extends StatelessWidget {
),
),
_CancelButton(onTap: onCancel),
+ if (onNew != null && onCancel == null) _NewButton(onTap: onNew!),
],
),
);
}
}
+/// `+`, for a new agent — see [SheetSearchField.onNew].
+class _NewButton extends StatelessWidget {
+ const _NewButton({required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ button: true,
+ label: 'New agent',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ // Padding, not a gap: the space between the box and the mark is part of the target.
+ padding: const EdgeInsets.only(left: 12),
+ child: SizedBox(
+ width: 32,
+ height: 44,
+ child: Center(
+ child: Icon(
+ LucideIcons.plus,
+ size: 24,
+ color: AppPalette.accentOnSurface,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
/// "Cancel" — see [SheetSearchField.onCancel].
///
/// ⚠️ **Kept built while it leaves, and dead while it does.** The word has to
@@ -338,11 +384,15 @@ class _QueryInput extends StatelessWidget {
required this.autofocus,
required this.hintText,
required this.hintStyle,
+ this.onSubmitted,
});
final TextEditingController controller;
final FocusNode focus;
final ValueChanged<String> onChanged;
+
+ /// The keyboard's return key. Null puts the keyboard away and nothing more.
+ final VoidCallback? onSubmitted;
final bool autofocus;
final String hintText;
@@ -363,7 +413,10 @@ class _QueryInput extends StatelessWidget {
// nothing left for the return key to submit, so it stays a plain "done"
// that drops the keyboard and leaves the results up.
textInputAction: TextInputAction.search,
- onSubmitted: (_) => focus.unfocus(),
+ onSubmitted: (_) {
+ focus.unfocus();
+ onSubmitted?.call();
+ },
// Composing stays on — or Telex types `thoi tiet` for `thời tiết`. See
// [ComposingKeyboard]; with autocorrect on, iOS would also start curling
// quotes and joining dashes, which a query means literally.
diff --git a/mobile/lib/phone/phone_search_rank.dart b/mobile/lib/phone/phone_search_rank.dart
index e7ecfd002..17d514cb3 100644
--- a/mobile/lib/phone/phone_search_rank.dart
+++ b/mobile/lib/phone/phone_search_rank.dart
@@ -1,4 +1,5 @@
import 'package:harness_mobile/core/fuzzy_match.dart';
+import 'package:harness_mobile/state/session_content_search.dart';
import 'package:harness_mobile/state/session_preview.dart';
import 'agent_index.dart' show compareMonitorOrder;
@@ -19,23 +20,70 @@ List<String> phoneSearchTerms(String query) {
/// How well [term] matches [field]: LOWER is better, null does not match.
///
-/// The desktop's `swarmFieldMatchScore`, unchanged. The bands, cheapest first:
-/// an exact field, a prefix, a substring anywhere, and last a scattered-letter
-/// subsequence whose cost grows with how far apart the letters landed. A
-/// non-title field takes a flat 64, which is what keeps a name match ahead of
-/// every piece of metadata under it.
-int? phoneFieldMatchScore(String field, String term, {required bool title}) {
+/// The desktop's `swarmFieldMatchScore`, unchanged. Whole words beat fragments: "port" is exact in
+/// "port", a prefix of "port audit", a word of "windows port" and only a fragment of "support".
+/// A non-title field takes a flat 64, which keeps a name match ahead of every piece of metadata.
+///
+/// [strict] is for harness rows — hundreds of names and long folder paths, where loose letters
+/// match nearly anything ("auth" in every `.../autonomous-harness/...`): scattered letters must
+/// start a word and stay close, and two letters count only as initials. Commands, machines,
+/// projects and models are short curated lists that keep any scattered letters.
+int? phoneFieldMatchScore(
+ String field,
+ String term, {
+ required bool title,
+ bool strict = false,
+}) {
final offset = field.indexOf(term);
- final spread = offset >= 0 ? 0 : subsequenceSpread(field, term);
- if (spread == null) return null;
- return (title ? 0 : 64) +
- (field == term
- ? 0
- : offset == 0
- ? 8
- : offset > 0
- ? 16
- : 128 + spread);
+ final int score;
+ if (offset == 0) {
+ score = field.length == term.length ? 0 : 8;
+ } else if (offset > 0) {
+ score = wordStartIndexOf(field, term, offset) >= 0 ? 12 : 16;
+ } else {
+ final spread = strict
+ ? wordSubsequenceSpread(field, term)
+ : subsequenceSpread(field, term);
+ if (spread == null) return null;
+ score = 128 + spread;
+ }
+ return (title ? 0 : 64) + score;
+}
+
+/// How well a row matched, coarsest first — the desktop's `SwarmMatchStrength`. Harnesses order
+/// by when their conversation last moved only among equally good matches, so the one named for a word is never buried under
+/// newer ones that mention it in a folder or a recap.
+enum PhoneMatchStrength {
+ /// The whole query is the name.
+ exact,
+
+ /// Every word starts a word of the name or title.
+ name,
+
+ /// A fragment of the name, or a whole word of the project, branch or machine.
+ context,
+
+ /// A fragment of the project, branch, folder or machine.
+ fragment,
+
+ /// Every word in one turn of the conversation — asked, answered, or a file or command it
+ /// touched — as the machine's session index found it.
+ said,
+
+ /// The words appear in the conversation, but not together.
+ content,
+
+ /// Scattered letters of the name or its context: real words anywhere in the conversation are
+ /// better evidence than letters strewn across a name.
+ scattered;
+
+ static PhoneMatchStrength ofScore(int score) => score <= 12
+ ? name
+ : score <= 76
+ ? context
+ : score < 128
+ ? fragment
+ : scattered;
}
/// The field [term] reaches best on [row] — its score and its index in
@@ -68,6 +116,7 @@ int? phoneFieldMatchScore(String field, String term, {required bool title}) {
field,
term,
title: i < row.titleFieldCount,
+ strict: row.isAgent,
);
if (score == null) continue;
if (best == null || score < best.score) best = (score: score, index: i);
@@ -76,115 +125,139 @@ int? phoneFieldMatchScore(String field, String term, {required bool title}) {
return best;
}
-/// What a word found only in the conversation costs: more than any metadata
-/// match can, so an agent that IS "llama" stays ahead of one that talked about
-/// it. The desktop's figure.
+/// What a word found only in the conversation costs: more than any metadata match can, so an
+/// agent that IS "llama" stays ahead of one that talked about it. The desktop's figure.
const _contentScore = 256;
-/// The rows [query] reaches, best first — the desktop's `rankSwarmDestinations`.
-///
-/// A word that matches no field is looked for in the agent's session content —
-/// its recent requests, its latest answer, what it is writing right now — which
-/// is how "llama" finds the agent somebody asked about llama.cpp. Rows that
-/// needed the content rank after every row that matched on the agent itself.
-///
-/// ⚠️ **The tie-breaks are the desktop's, in the desktop's order**, with one
-/// deliberate substitution: content, then score, then — only with nothing typed
-/// — the tier below, then how recently the row was OPENED, then [all]'s own
-/// order, and finally the id so two rows can never swap places on a rebuild.
-/// [recent] is the phone's visit history (see [PhoneSearchHistory]).
-///
-/// ⚠️ **The substitution is the last-but-one step: [all]'s order where the
-/// desktop compares names.** The desktop can afford alphabetical there because
-/// by the time it is reached its visit history has already placed almost
-/// everything — it records every pane you focus, over weeks. A phone opened for
-/// the first time has no history at all, so EVERY row fell through to that step
-/// and the box opened on an alphabetical list: `Codex harness 8:16` above the
-/// agent that finished a minute ago. That is not what the desktop looks like,
-/// it is what the desktop's last resort looks like.
+typedef _Match = ({
+ PhoneDestination entry,
+ int score,
+ PhoneMatchStrength strength,
+
+ /// How the machine's session index ranked this row among its hits, as a reciprocal rank
+ /// (higher is better), when it found it.
+ double said,
+ int index,
+});
+
+/// The rows [query] reaches, best first — the desktop's `rankSwarmDestinationsByActivity` and
+/// `rankSwarmDestinations`, from main's Cmd-P search (docs/research/2026-09-26-session-search.md).
///
-/// [phoneSearchCatalog] hands its agents in [recentAgents] order — waiting on
-/// you, then working, then whose conversation moved last — so deferring to it
-/// puts the phone's best guess where the desktop puts its worst one, and the two
-/// converge on the same list as the history fills.
+/// Each word may match a different field, in either order: "mini auth" and "auth mini" both find
+/// Auth on Mac mini. A word no field holds is looked for in the session excerpt the app already
+/// has, at word starts only ("port" does not find every "support"). [contentHits] are what the
+/// machines' session indexes found for this query, by row id: everything ever said in each
+/// session. A hit vouches for every word, so it admits a row the fields alone cannot, and lifts
+/// one that only scattered letters matched.
///
-/// It is also what keeps the list still. That order is decided when the CATALOG
-/// is built, and the catalog is cached against the shape of the fleet
-/// ([PhoneSearchCatalogCache]) — so a turn event, which moves `lastActiveAt`
-/// every second on a busy machine, does not rebuild it and cannot move a row out
-/// from under a thumb.
+/// ⚠️ **Typed, a list of agents orders by how well each matched, then by when its conversation last
+/// moved** — not by that alone, which buried the harness named `hn` 6th of 166 under newer ones
+/// whose folder paths spell h…n. With nothing typed it is the conversations that moved last first,
+/// and [recent] (this phone's visits) only breaks ties.
List<PhoneDestination> rankPhoneDestinations(
List<PhoneDestination> all,
String query, {
List<String> recent = const [],
SessionPreviewStore? previews,
+ bool byActivity = false,
+ Map<String, SessionContentHit>? contentHits,
}) {
final needle = query.trim().toLowerCase();
final terms = phoneSearchTerms(query);
final recency = {for (var i = 0; i < recent.length; i++) recent[i]: i};
- final ranked =
- <({PhoneDestination entry, int score, bool content, int index})>[];
+ final ranked = <_Match>[];
for (final (index, entry) in all.indexed) {
- // An exact hit on the name — or on the agent's own title — wins outright,
- // ahead of every scored row. Typing one in full is the least ambiguous
- // thing somebody can do.
- if (entry.fields.take(entry.titleFieldCount).contains(needle)) {
- ranked.add((entry: entry, score: -1, content: false, index: index));
+ // An exact hit on the name — or on the agent's own title — wins outright.
+ if (needle.isNotEmpty &&
+ entry.fields.take(entry.titleFieldCount).contains(needle)) {
+ ranked.add((
+ entry: entry,
+ score: -1,
+ strength: PhoneMatchStrength.exact,
+ said: 0,
+ index: index,
+ ));
continue;
}
+ final hit = terms.isEmpty ? null : contentHits?[entry.id];
+ final hitStrength = hit == null
+ ? null
+ : hit.together
+ ? PhoneMatchStrength.said
+ : PhoneMatchStrength.content;
var total = 0;
- var content = false;
+ var strength = PhoneMatchStrength.name;
String? excerpt;
for (final term in terms) {
final best = phoneBestFieldMatch(entry, term);
+ final PhoneMatchStrength termStrength;
+ final int cost;
if (best == null) {
excerpt ??= entry.previewKey == null
? ''
: previews?.read(entry.previewKey!)?.searchText ?? '';
- // Literal only, never the scattered-letter match the fields get: a few
- // turns of prose contain almost every short run of letters somewhere,
- // and a fuzzy hit in them would return every agent on the account.
- if (!excerpt.contains(term)) {
+ if (wordStartIndexOf(excerpt, term) < 0) {
total = -1;
break;
}
- content = true;
- total += _contentScore;
- continue;
+ termStrength = PhoneMatchStrength.content;
+ cost = _contentScore;
+ } else {
+ termStrength = PhoneMatchStrength.ofScore(best.score);
+ cost = best.score;
}
- total += best.score;
+ if (termStrength.index > strength.index) strength = termStrength;
+ total += cost;
+ }
+ if (hitStrength != null &&
+ (total < 0 || hitStrength.index < strength.index)) {
+ strength = hitStrength;
+ if (total < 0) total = _contentScore * terms.length;
}
if (total >= 0) {
- ranked.add((entry: entry, score: total, content: content, index: index));
+ ranked.add((
+ entry: entry,
+ score: total,
+ strength: strength,
+ // Reciprocal rank: each machine's index ranks its own hits, and a machine's first is as
+ // good as another's first.
+ said: hit == null ? 0 : 1 / (1 + hit.position),
+ index: index,
+ ));
}
}
- // A group or a command is not something the phone can open, so with nothing
- // typed it sits under every agent — the desktop's `!hasView` tier.
- //
- // ⚠️ **The desktop's third tier, `current`, is deliberately absent.** It
- // demotes the pane you are looking at, and porting that rule literally
- // inverted its effect. The desktop's box is always opened with `adding: true`
- // and so always targets a NEW tab or pane (`swarm_screen.dart`), where nothing
- // is focused — so `current` almost never fires there, and the agent you came
- // from ranks near the top: in a live window it sat at rows[2] of 16. A phone's
- // search is ALWAYS opened from a terminal showing an agent, so the same rule
- // fired every single time and buried that agent at the bottom.
- //
- // Matching the desktop means matching what it does, not what it says. And the
- // agent you came from is the most recently active one anyway, so the order it
- // falls into is the one the catalog already wanted.
- int tier(PhoneDestination e) => !e.isAgent
- ? 3
- : recency.containsKey(e.id)
- ? 0
- : 1;
+ bool conversation(_Match match) =>
+ match.strength == PhoneMatchStrength.said ||
+ match.strength == PhoneMatchStrength.content;
ranked.sort((a, b) {
- if (needle.isEmpty) return _monitorOrder(a, b);
- var order = (a.content ? 1 : 0).compareTo(b.content ? 1 : 0);
- if (order == 0) order = a.score.compareTo(b.score);
- if (order == 0 && needle.isEmpty) {
- order = tier(a.entry).compareTo(tier(b.entry));
+ // Nothing typed: the conversation that moved last first, then this phone's visits.
+ if (needle.isEmpty) {
+ var order = _lastMovedFirst(a.entry, b.entry);
+ if (order == 0) {
+ order = (recency[a.entry.id] ?? 1 << 20).compareTo(
+ recency[b.entry.id] ?? 1 << 20,
+ );
+ }
+ return order != 0 ? order : _monitorOrder(a, b);
}
+ if (byActivity) {
+ var order = a.strength.index.compareTo(b.strength.index);
+ // What was said is ranked by the index, which weighs how well it matched against how long
+ // ago; the conversation's last move decides between equal answers.
+ if (order == 0 && conversation(a)) order = b.said.compareTo(a.said);
+ if (order == 0) order = _lastMovedFirst(a.entry, b.entry);
+ if (order == 0) {
+ order = (recency[a.entry.id] ?? 1 << 20).compareTo(
+ recency[b.entry.id] ?? 1 << 20,
+ );
+ }
+ if (order == 0) order = a.score.compareTo(b.score);
+ if (order == 0) order = a.index.compareTo(b.index);
+ return order == 0 ? a.entry.id.compareTo(b.entry.id) : order;
+ }
+ // Commands, machines, projects: names outrank metadata, metadata outranks what was said.
+ var order = (conversation(a) ? 1 : 0).compareTo(conversation(b) ? 1 : 0);
+ if (order == 0) order = a.score.compareTo(b.score);
if (order == 0) {
order = (recency[a.entry.id] ?? 999).compareTo(
recency[b.entry.id] ?? 999,
@@ -196,6 +269,16 @@ List<PhoneDestination> rankPhoneDestinations(
return [for (final row in ranked) row.entry];
}
+/// The conversation that moved last first — the true time; opening a harness is not work on it. An
+/// agent never dated, and anything that is not an agent, after.
+int _lastMovedFirst(PhoneDestination a, PhoneDestination b) {
+ final left =
+ (a.entry?.agent.updatedAt ?? a.lastAt)?.millisecondsSinceEpoch ?? 0;
+ final right =
+ (b.entry?.agent.updatedAt ?? b.lastAt)?.millisecondsSinceEpoch ?? 0;
+ return right.compareTo(left);
+}
+
/// With nothing typed, the list the field opens on: the agents in the desktop's Harness Monitor
/// order ([compareMonitorOrder]), and whatever is not an agent after them in [all]'s order.
///
@@ -204,10 +287,7 @@ List<PhoneDestination> rankPhoneDestinations(
/// on the laptop beside it, and the agent at the top of the desktop's monitor could be halfway down
/// the phone's. Somebody moving between the two reads the same list on both now. Once a word is
/// typed the match decides, as it always has.
-int _monitorOrder(
- ({PhoneDestination entry, int score, bool content, int index}) a,
- ({PhoneDestination entry, int score, bool content, int index}) b,
-) {
+int _monitorOrder(_Match a, _Match b) {
final left = a.entry.entry;
final right = b.entry.entry;
if (left != null && right != null) return compareMonitorOrder(left, right);
diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dart
index 50b6dc9b3..9b777aa1a 100644
--- a/mobile/lib/phone/phone_search_results.dart
+++ b/mobile/lib/phone/phone_search_results.dart
@@ -6,18 +6,27 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/empty_state.dart';
+import 'package:harness_mobile/notify/agent_notice.dart' show NoticeKind;
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/external_session.dart';
import 'agent_index.dart';
+import 'find_row.dart';
+import 'fzf.dart' show fzfAge;
import 'phone_destination.dart';
import 'phone_navigation.dart';
+import 'phone_search_catalog.dart' show phoneAgentId;
import 'phone_search_commands.dart';
import 'phone_search_controller.dart';
import 'phone_search_rank.dart';
import 'phone_search_row.dart';
import 'resume_agent.dart';
+import 'search_result_text.dart'
+ show phoneResultMatches, snippetLead, snippetRuns;
import 'sheet_list.dart';
import 'sheet_search_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
/// What the query reaches, drawn.
///
@@ -43,9 +52,19 @@ class PhoneSearchResults extends StatefulWidget {
required this.controller,
this.onOpen,
this.grouped = false,
+ this.fzf = false,
this.showing,
+ this.onNewHarness,
});
+ /// Find's `+ New Harness` row — with a project's machine and folder when the query matched one
+ /// (`+ New Harness in api`). Null leaves the row out.
+ final void Function(({String machineId, String folder, String label})? place)?
+ onNewHarness;
+
+ /// Find's list: two-line rows growing down from the field at the top — see [FindRow].
+ final bool fzf;
+
final AppNotifier notifier;
final PhoneSearchController controller;
@@ -68,10 +87,28 @@ class PhoneSearchResults extends StatefulWidget {
final AgentRef? showing;
@override
- State<PhoneSearchResults> createState() => _PhoneSearchResultsState();
+ State<PhoneSearchResults> createState() => PhoneSearchResultsState();
}
-class _PhoneSearchResultsState extends State<PhoneSearchResults> {
+class PhoneSearchResultsState extends State<PhoneSearchResults> {
+ /// Opens the first row a tap could open — Enter in the desktop's ⌘P, the return key here.
+ void openFirst() {
+ final search = widget.controller;
+ final showing = widget.showing;
+ final rows = search.matchQuery.trim().isEmpty && showing != null
+ ? [
+ for (final row in search.rows)
+ if (!_isShowing(row, showing)) row,
+ ]
+ : search.rows;
+ for (final row in rows) {
+ if (search.canSubmit(row)) {
+ _tap(row);
+ return;
+ }
+ }
+ }
+
/// The row whose agent is being brought back, if any — see [_open].
///
/// One at a time: the resume is a round trip to the machine, and a list that
@@ -79,6 +116,13 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
/// person who only meant to open one.
String? _resuming;
+ /// The order Find opened with — each row's section (needs you, recent, the one on screen,
+ /// paused) and place in it, by id. Held while Find is open: a harness that starts or stops
+ /// asking, pauses, or does something new keeps its place and only its words change, so the row
+ /// under your finger is the row you meant. Rows that arrive later — a machine answering —
+ /// join the end of their section. Null until the first rows are drawn.
+ Map<String, (int, int)>? _openedOrder;
+
/// ⚠️ **Three sources, and they answer different questions.**
///
/// The controller says WHICH rows and in what order. The other two are what
@@ -102,7 +146,12 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
// account reported down was never even dialled. Asked on the way in, not
// awaited: what is already known draws immediately, and each machine adds
// its agents as it answers.
- unawaited(notifier.reachAllMachines());
+ //
+ // ⚠️ After the frame, not in it: reaching can notify synchronously, and a notify while this
+ // list is being mounted marks the page above it dirty mid-build.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) unawaited(notifier.reachAllMachines());
+ });
notifier.sessionPreviews.warm([
for (final entry in recentAgents(agentIndex(notifier)))
notifier.previewKey(entry.machineId, entry.agent),
@@ -116,6 +165,7 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
AppTheme.watch(context);
final search = widget.controller;
final rows = search.rows;
+ if (widget.fzf) return _find(search, rows);
if (widget.grouped) return _grouped(search, rows);
if (rows.isEmpty) return _empty(search);
final terms = phoneSearchTerms(search.matchQuery);
@@ -153,7 +203,293 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
},
);
- /// The rows as the terminal sheet lists them — see [grouped].
+ /// Find's list: grows down from the field at the top. With nothing typed, `needs you` (newest
+ /// question first) then `recent`, the harness on screen last, `+ New Harness` at the end; typed,
+ /// the matches in their order, then the commands that match, then `+ New Harness in <project>`.
+ /// See docs/plans/2026-09-26-003-mobile-find-new-spec.md.
+ Widget _find(PhoneSearchController search, List<PhoneDestination> rows) {
+ // The words, less any time ("dial last week" lights "dial").
+ final terms = phoneSearchTerms(search.wordsQuery);
+ final showing = widget.showing;
+ final now = DateTime.now();
+ final tty = Tty.of(context);
+ final typed = search.matchQuery.trim().isNotEmpty;
+ final plain =
+ !search.isCommandMode &&
+ !search.isHelpMode &&
+ !search.isGroupMode &&
+ !search.isModelMode &&
+ !search.canGoBack;
+ bool asking(PhoneDestination row) => row.entry?.isWaiting ?? false;
+ DateTime since(PhoneDestination row) {
+ final entry = row.entry;
+ return entry?.machine.blockedAgents[entry.agent.id]?.since ??
+ DateTime.fromMillisecondsSinceEpoch(0);
+ }
+
+ // Paused work has its own place at the end: last used lately, it is still not what is running.
+ bool paused(PhoneDestination row) => row.entry?.agent.isStopped ?? false;
+ List<PhoneDestination> needsYou;
+ List<PhoneDestination> rest;
+ var pausedRows = const <PhoneDestination>[];
+ PhoneDestination? current;
+ if (!typed && plain) {
+ current = showing == null
+ ? null
+ : rows.where((row) => _isShowing(row, showing)).firstOrNull;
+ needsYou = [
+ for (final row in rows)
+ if (asking(row) && row != current) row,
+ ]..sort((a, b) => since(b).compareTo(since(a)));
+ rest = [
+ for (final row in rows)
+ if (!asking(row) && row != current && !paused(row)) row,
+ ];
+ pausedRows = [
+ for (final row in rows)
+ if (!asking(row) && row != current && paused(row)) row,
+ ];
+ } else {
+ current = null;
+ needsYou = const [];
+ rest = rows;
+ }
+ if (!typed && plain) {
+ final frozen = _openedOrder ??= rows.isEmpty
+ ? null
+ : {
+ for (final (i, row) in needsYou.indexed) row.id: (0, i),
+ for (final (i, row) in rest.indexed) row.id: (1, i),
+ if (current != null) current.id: (2, 0),
+ for (final (i, row) in pausedRows.indexed) row.id: (3, i),
+ };
+ if (frozen != null) {
+ // Back into the sections they opened in, in the order they opened in; newcomers after.
+ final live = [
+ for (final (i, row) in needsYou.indexed) (row, 0, i),
+ for (final (i, row) in rest.indexed) (row, 1, i),
+ if (current != null) (current, 2, 0),
+ for (final (i, row) in pausedRows.indexed) (row, 3, i),
+ ];
+ final sections = List.generate(4, (_) => <(PhoneDestination, int)>[]);
+ for (final (row, section, i) in live) {
+ final (at, place) = frozen[row.id] ?? (section, 1 << 20 | i);
+ sections[at].add((row, place));
+ }
+ for (final section in sections) {
+ section.sort((a, b) => a.$2.compareTo(b.$2));
+ }
+ needsYou = [for (final (row, _) in sections[0]) row];
+ rest = [for (final (row, _) in sections[1]) row];
+ current = sections[2].firstOrNull?.$1;
+ pausedRows = [for (final (row, _) in sections[3]) row];
+ }
+ }
+ final ordered = [...needsYou, ...rest, ?current, ...pausedRows];
+ final selectedAt = typed ? ordered.indexWhere(search.canSubmit) : -1;
+ final newHarness = widget.onNewHarness;
+ final project = search.projectMatch;
+ final children = <Widget>[];
+ var index = 0;
+ Widget row(PhoneDestination row) =>
+ _findRow(row, terms, now, tty, selected: index++ == selectedAt);
+ if (needsYou.isNotEmpty) {
+ children.add(FindHeader('needs you', color: tty.yellow));
+ children.addAll(needsYou.map(row));
+ children.add(const FindHeader('recent'));
+ }
+ children.addAll(rest.map(row));
+ if (current != null) children.add(row(current));
+ // At the end and without a heading: each one's own word on the right says `paused`.
+ children.addAll(pausedRows.map(row));
+ if (ordered.isEmpty) {
+ children.add(
+ Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 20, Tty.origin, 8),
+ child: TtyText(
+ search.total == 0 && !typed ? 'No harnesses running.' : 'No match.',
+ color: tty.faint,
+ size: TtySize.row,
+ ),
+ ),
+ );
+ }
+ if (search.commandMatches.isNotEmpty) {
+ children.add(const FindHeader('commands'));
+ for (final command in search.commandMatches) {
+ children.add(
+ FindRow(
+ title: command.title,
+ terms: terms,
+ state: command.shortcut,
+ onTap: () => _tap(command),
+ ),
+ );
+ }
+ }
+ if (newHarness != null && plain) {
+ final place = project == null ? null : _projectPlace(project);
+ children.add(const SizedBox(height: 8));
+ children.add(
+ FindAddRow(
+ label: place == null
+ ? 'New Harness'
+ : 'New Harness in ${project!.title}',
+ detail: place?.label,
+ onTap: () => newHarness(place),
+ ),
+ );
+ }
+ children.add(const SizedBox(height: 24));
+ return ListView(
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ padding: EdgeInsets.zero,
+ children: children,
+ );
+ }
+
+ /// One harness (or command) as a Find row — see [FindRow].
+ Widget _findRow(
+ PhoneDestination row,
+ List<String> terms,
+ DateTime now,
+ Tty tty, {
+ required bool selected,
+ }) {
+ final entry = row.entry;
+ final openable = widget.controller.canSubmit(row);
+ final showing = widget.showing;
+ final onScreen = showing != null && _isShowing(row, showing);
+ // A conversation Harness did not start: where it was said, and `resume` — or, open in a
+ // terminal or app elsewhere, that instead, and no tap.
+ if (row.external case final external?) {
+ final hit = widget.controller.contentHitFor(row.id);
+ return FindRow(
+ title: row.title,
+ detail: row.detail,
+ branch: null,
+ tail: [
+ external.engineLabel,
+ if (row.lastAt case final at?) fzfAge(at, now),
+ ].join(' · '),
+ said: hit == null || hit.snippet.isEmpty || hit.field == 'name'
+ ? null
+ : (lead: snippetLead(hit.field), runs: snippetRuns(hit.snippet)),
+ state: _resuming == row.id
+ ? 'opening…'
+ : external.open
+ ? 'open in ${external.originLabel}'
+ : 'resume',
+ stateColor: external.open ? tty.faint : tty.text,
+ terms: terms,
+ selected: selected,
+ enabled: openable || _resuming == row.id,
+ onTap: _resuming != null ? null : () => _tap(row),
+ );
+ }
+ if (entry == null) {
+ return FindRow(
+ title: row.title,
+ detail: row.detail,
+ terms: terms,
+ selected: selected,
+ enabled: openable,
+ onTap: () => _tap(row),
+ );
+ }
+ final question = entry.machine.blockedAgents[entry.agent.id]?.prompt.trim();
+ final state = _stateOf(entry, openable, tty, resuming: _resuming == row.id);
+ final asking = question != null && question.isNotEmpty && entry.isWaiting;
+ final branch = entry.agent.project?.branch;
+ // Found in what was said rather than in its own name and place: the second line shows where
+ // — the desktop Cmd-P's rule.
+ final hit = widget.controller.contentHitFor(row.id);
+ final said =
+ hit != null &&
+ hit.snippet.isNotEmpty &&
+ hit.field != 'name' &&
+ (terms.isEmpty ||
+ phoneResultMatches(row, terms).length <
+ terms.take(12).toSet().length)
+ ? (lead: snippetLead(hit.field), runs: snippetRuns(hit.snippet))
+ : null;
+ return FindRow(
+ title: row.title,
+ strict: true,
+ said: said,
+ // `M2:site ⑂ docs-v2 · 2m` — or, while it asks, its question.
+ detail: asking
+ ? '"${question.split('\n').first}"'
+ : '${entry.machineName}:${entry.agent.project?.label ?? entry.project?.name ?? ''}',
+ branch: asking || branch == null || branch.isEmpty ? null : branch,
+ tail: asking
+ ? null
+ : onScreen
+ ? 'current'
+ : fzfAge(entry.agent.updatedAt, now),
+ detailColor: question != null && entry.isWaiting ? tty.text : null,
+ state: state.word,
+ stateColor: state.color,
+ terms: terms,
+ selected: selected,
+ enabled: openable || _resuming == row.id,
+ // The harness on screen is where Cancel goes: a tap on it is Cancel.
+ onTap: _resuming != null
+ ? null
+ : onScreen
+ ? widget.onOpen
+ : () => _tap(row),
+ );
+ }
+
+ ({String word, Color color}) _stateOf(
+ AgentEntry entry,
+ bool openable,
+ Tty tty, {
+ required bool resuming,
+ }) {
+ if (resuming) return (word: 'resuming', color: tty.faint);
+ if (entry.isWaiting) return (word: 'asking', color: tty.yellow);
+ if (entry.agent.isStopped) {
+ return (word: openable ? 'paused' : 'stopped', color: tty.faint);
+ }
+ if (!openable) return (word: 'exited', color: tty.red);
+ if (entry.isWorking) return (word: 'working', color: tty.green);
+ final unread = widget.notifier.agentNotices.unread.kindFor((
+ machineId: entry.machineId,
+ agentId: entry.agent.id,
+ ));
+ if (unread == NoticeKind.done) return (word: 'done', color: tty.faint);
+ return (word: 'idle', color: tty.faint);
+ }
+
+ /// Where a project lives, for `+ New Harness in <project>`: its machine and folder, read from the
+ /// first harness in it.
+ ({String machineId, String folder, String label})? _projectPlace(
+ PhoneDestination project,
+ ) {
+ for (final entry in agentIndex(widget.notifier)) {
+ if (!project.members.contains(
+ phoneAgentId(entry.machineId, entry.agent.id),
+ )) {
+ continue;
+ }
+ final cwd = entry.agent.project?.cwd ?? entry.project?.cwd;
+ if (cwd == null || cwd.isEmpty) continue;
+ return (
+ machineId: entry.machineId,
+ folder: cwd,
+ label:
+ '${entry.machineName}:${entry.agent.project?.label ?? project.title}',
+ );
+ }
+ return null;
+ }
+
+ static bool _isShowing(PhoneDestination row, AgentRef showing) =>
+ row.entry?.machineId == showing.machineId &&
+ row.entry?.agent.id == showing.agentId;
+
Widget _grouped(PhoneSearchController search, List<PhoneDestination> rows) {
final bottom = MediaQuery.paddingOf(context).bottom + 16;
if (rows.isEmpty) {
@@ -231,6 +567,10 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
_run(opened);
return;
}
+ if (opened.external case final external?) {
+ unawaited(_resumeExternal(opened, external));
+ return;
+ }
final entry = opened.entry;
if (entry == null) return;
if (entry.agent.isStopped) {
@@ -240,6 +580,38 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
_openAgent(entry);
}
+ /// A conversation Harness did not start, opened as a new harness that resumes it in its own
+ /// folder (`claude --resume`, `codex resume`), then its terminal. The machine refuses one open
+ /// elsewhere or already a harness, and the reason is said.
+ Future<void> _resumeExternal(
+ PhoneDestination row,
+ ExternalSessionRef external,
+ ) async {
+ final machineId = row.machineId;
+ if (machineId == null) return;
+ setState(() => _resuming = row.id);
+ final attempt = AgentCreationAttempt();
+ final error = await widget.notifier.resumeConversation(
+ machineId,
+ engine: external.engine,
+ folder: external.cwd,
+ sessionId: external.sessionId,
+ name: external.title.isEmpty ? null : external.title,
+ attempt: attempt,
+ );
+ if (!mounted) return;
+ setState(() => _resuming = null);
+ final agentId = attempt.agentId;
+ if (error != null || agentId == null) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(content: Text(error ?? 'Could not open that conversation.')),
+ );
+ return;
+ }
+ widget.onOpen?.call();
+ openAgent(context, widget.notifier, machineId, agentId);
+ }
+
/// Bring a stopped agent back, then open it — the desktop's
/// `_resumeStoppedDestination` followed by its activation.
///
@@ -253,9 +625,8 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
if (!mounted) return;
setState(() => _resuming = null);
if (error != null) {
- ScaffoldMessenger.maybeOf(
- context,
- )?.showSnackBar(SnackBar(content: Text(error)));
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text(error)));
return;
}
// ⚠️ Re-read from the catalog rather than reusing `entry`. The resume
@@ -284,8 +655,8 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {
void _run(PhoneDestination row) {
final id = row.commandId;
if (id == null) return;
- for (final command in widget.controller.commands?.call() ??
- const <PhoneCommand>[]) {
+ for (final command
+ in widget.controller.commands?.call() ?? const <PhoneCommand>[]) {
if (command.id != id) continue;
unawaited(Future.sync(command.run));
return;
diff --git a/mobile/lib/phone/phone_sheet.dart b/mobile/lib/phone/phone_sheet.dart
index 99ad921cb..f61a5d2ea 100644
--- a/mobile/lib/phone/phone_sheet.dart
+++ b/mobile/lib/phone/phone_sheet.dart
@@ -13,6 +13,8 @@ import 'package:harness_mobile/shared/widgets/app_dialog.dart'
showAppDialog;
import 'settings_row.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
/// One action in a phone sheet.
class PhoneSheetAction {
@@ -25,11 +27,15 @@ class PhoneSheetAction {
this.valueColor,
this.enabled = true,
this.chevron = false,
+ this.quiet = false,
});
final IconData icon;
final String label;
+ /// Drawn small and faint, at the foot — the action least used, kept out of the way (Stop).
+ final bool quiet;
+
/// Run AFTER the sheet has closed — see [showPhoneSheet], which pops first and then calls this.
/// A dialog opened from here would otherwise open behind the closing sheet.
final VoidCallback onTap;
@@ -107,6 +113,7 @@ Future<void> showPhoneSheet(
List<String>? titleParts,
Widget? titleDetail,
Widget? titleLeading,
+ String? titleBranch,
}) {
assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context));
@@ -125,117 +132,213 @@ Future<void> showPhoneSheet(
barrierOnTapHint: localizations.scrimOnTapHint(
localizations.bottomSheetLabel,
),
- showDragHandle: true,
- backgroundColor: AppPalette.panelBg,
- // ⚠️ **Without this the sheet is capped at 9/16 of the screen**, which is Flutter's default and
- // is not a height anything here asked for. An agent's sheet — three cards, a caption, a two-line
- // title detail under the name — outgrows it on a normal phone, and the row that fell past the cap was
- // Settings: the column below scrolls, so nothing was broken, but a sheet that ends mid-list with
- // no bottom edge in sight reads as the whole menu rather than as a scrollable one.
+ // The terminal's ground, a rounded top like every sheet New opens, no handle.
+ showDragHandle: false,
+ backgroundColor: Tty.of(context).ground,
isScrollControlled: true,
- // A ceiling of its own, because `isScrollControlled` alone removes the cap altogether and lets a
- // long sheet stand up the full height of the screen — voice input's six languages would. Short of
- // the top on purpose: the gap is what says a sheet is a layer over the page rather than a page of
- // its own, and it keeps the terminal underneath recognisable while its own menu is open.
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
builder: (sheetContext) => SafeArea(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- // 20 from the edge is 4 inside the cards' own 16 — where a Settings caption stands over
- // its card — so the title reads as the heading of what follows it. A title with parts
- // (an agent's name over where it runs) is a block of its own and takes more room below.
- padding: EdgeInsets.fromLTRB(
- 20,
- 0,
- titleAction == null ? 20 : 8,
- titleParts == null ? 12 : 16,
+ child: _TmuxMenu(
+ title: title,
+ branch: titleBranch,
+ actions: actions,
+ sections: sections,
+ onAction: (action) {
+ Navigator.of(sheetContext).pop();
+ action.onTap();
+ },
+ ),
+ ),
+ ),
+ );
+}
+
+/// A harness's menu, the phone's way: its name and where it runs at the top with Cancel, one 17pt
+/// row per action, a rule between groups, the destructive one red, `›` on one that opens more.
+/// Drawn in the terminal's face, like every sheet New opens.
+class _TmuxMenu extends StatefulWidget {
+ const _TmuxMenu({
+ required this.title,
+ this.branch,
+ required this.actions,
+ required this.sections,
+ required this.onAction,
+ });
+
+ final String title;
+
+ /// Under the name, after where it runs, behind the branch icon — see [ttyBranchMark].
+ final String? branch;
+ final List<PhoneSheetAction> actions;
+ final List<PhoneSheetSection> sections;
+ final void Function(PhoneSheetAction action) onAction;
+
+ @override
+ State<_TmuxMenu> createState() => _TmuxMenuState();
+}
+
+class _TmuxMenuState extends State<_TmuxMenu> {
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final groups = <List<Widget>>[
+ if (widget.actions.isNotEmpty)
+ [for (final action in widget.actions) _item(tty, action)],
+ for (final section in widget.sections)
+ if (section.actions.isNotEmpty)
+ [
+ if (section.caption case final caption?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 10,
+ Tty.origin,
+ 2,
+ ),
+ child: TtyText(
+ caption.toLowerCase(),
+ color: tty.faint,
+ size: TtySize.meta,
+ ),
),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (titleLeading != null) ...[
- titleLeading,
- const SizedBox(width: 14),
- ],
- Expanded(
- child: titleParts == null
- ? Text(
- title,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 13,
- ),
- )
- : Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _TitleParts(parts: titleParts),
- if (titleDetail != null) ...[
- const SizedBox(height: 3),
- titleDetail,
- ],
+ for (final action in section.visible) _item(tty, action),
+ if (section.hiddenCount > 0)
+ _item(
+ tty,
+ PhoneSheetAction(
+ icon: LucideIcons.ellipsis300,
+ label: '${section.hiddenCount} more',
+ onTap: () {},
+ ),
+ onTap: () => setState(section.expand),
+ ),
+ ],
+ ];
+ // `hn · M2:autonomous-harness (main)`: the name on its own line, where it runs under it.
+ final split = widget.title.indexOf(' · ');
+ final name = split < 0 ? widget.title : widget.title.substring(0, split);
+ final place = split < 0 ? null : widget.title.substring(split + 3);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 10, 4, 6),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ if (place != null || widget.branch != null)
+ Text.rich(
+ TextSpan(
+ children: [
+ if (place != null) TextSpan(text: place),
+ if (widget.branch case final branch?) ...[
+ ttyBranchMark(tty, lead: place == null ? 0 : 8),
+ TextSpan(text: branch),
],
- ),
- ),
- // [titleAction]: an icon on the title line — for something that is not about the
- // subject of the sheet (Settings, on an agent's sheet), so it does not take a row
- // among the actions that are. Its label is the tooltip.
- if (titleAction != null)
- IconButton(
- tooltip: titleAction.label,
- icon: Icon(
- titleAction.icon,
- size: 20,
- color: AppPalette.textSecondary,
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(size: TtySize.meta, color: tty.faint),
),
- visualDensity: VisualDensity.compact,
- onPressed: () {
- Navigator.of(sheetContext).pop();
- titleAction.onTap();
- },
+ ],
+ ),
+ ),
+ // No Cancel: a tap anywhere outside the sheet puts it away.
+ ],
+ ),
+ ),
+ Flexible(
+ child: ListView(
+ shrinkWrap: true,
+ padding: const EdgeInsets.only(bottom: 8),
+ children: [
+ for (var g = 0; g < groups.length; g++) ...[
+ if (g > 0)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: Container(
+ height: 1,
+ color: tty.dim.withValues(alpha: 0.6),
),
- ],
+ ),
+ ...groups[g],
+ ],
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _item(Tty tty, PhoneSheetAction action, {VoidCallback? onTap}) {
+ if (action.quiet) {
+ return TtyTap(
+ onTap: action.enabled ? (onTap ?? () => widget.onAction(action)) : null,
+ semanticsLabel: action.label,
+ minHeight: 44,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: TtyText(action.label, color: tty.faint, size: TtySize.meta),
+ ),
+ );
+ }
+ final color = !action.enabled
+ ? tty.dim
+ : action.destructive
+ ? tty.red
+ : tty.text;
+ return TtyTap(
+ onTap: action.enabled ? (onTap ?? () => widget.onAction(action)) : null,
+ semanticsLabel: action.label,
+ minHeight: 52,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyText(
+ action.label,
+ color: color,
+ size: TtySize.row,
+ weight: FontWeight.w500,
),
),
- // Scrolls once the rows outgrow the sheet — voice input's six languages do on a short phone —
- // and is laid out exactly like a plain column until then.
- Flexible(
- // Stateful only for [PhoneSheetSection.maxVisible]: "N more" opens the rest in place
- // rather than closing the sheet.
- child: StatefulBuilder(
- builder: (context, setSheetState) => ListView(
- shrinkWrap: true,
- // The cards' inset from the sheet's edge: the Settings list's own 16.
- padding: const EdgeInsets.symmetric(horizontal: 16),
- children: _sheetCards(
- actions: actions,
- sections: sections,
- // Close first, then act: an action that opens a dialog or pushes a page must not
- // do it underneath a sheet that is still animating out.
- onAction: (action) {
- Navigator.of(sheetContext).pop();
- action.onTap();
- },
- // Stays open: this row reveals, it does not act.
- onExpand: (section) => setSheetState(section.expand),
- ),
+ if (action.value case final value?)
+ Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: TtyText(
+ value,
+ color: action.valueColor ?? tty.faint,
+ size: TtySize.meta,
),
),
- ),
- const SizedBox(height: 12),
+ if (action.chevron)
+ Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: TtyText('›', color: tty.faint, size: TtySize.title),
+ ),
],
),
),
- ),
- );
+ );
+ }
}
/// The route [showPhoneSheet] pushes: Material's own bottom sheet, standing on the app's sheet veil
@@ -264,6 +367,9 @@ class _PhoneSheetRoute<T> extends ModalBottomSheetRoute<T> {
required super.showDragHandle,
required super.isScrollControlled,
}) : super(
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
+ ),
modalBarrierColor: Colors.black.withValues(alpha: kSheetVeilOpacity),
);
@@ -287,172 +393,6 @@ class _PhoneSheetRoute<T> extends ModalBottomSheetRoute<T> {
}
}
-/// The body of a sheet, as cards: [actions] first, then every section that has rows.
-List<Widget> _sheetCards({
- required List<PhoneSheetAction> actions,
- required List<PhoneSheetSection> sections,
- required void Function(PhoneSheetAction action) onAction,
- required void Function(PhoneSheetSection section) onExpand,
-}) {
- final cards = <Widget>[];
- void addCard(List<Widget> rows, {String? caption}) {
- if (caption != null) {
- cards.add(SettingsCaption(caption));
- } else if (cards.isNotEmpty) {
- // A bare card still has to part from the one above it, or the two read as one card with a
- // seam in it — and the row set apart would not be.
- cards.add(const SizedBox(height: 16));
- }
- cards.add(SettingsGroup(children: rows));
- }
-
- if (actions.isNotEmpty) {
- addCard([
- for (final action in actions)
- _SheetRow(action: action, onTap: () => onAction(action)),
- ]);
- }
- for (final section in sections) {
- if (section.actions.isEmpty) continue;
- addCard([
- for (final action in section.visible)
- _SheetRow(action: action, onTap: () => onAction(action)),
- if (section.hiddenCount > 0)
- _SheetRow(
- action: PhoneSheetAction(
- icon: LucideIcons.ellipsis300,
- label: '${section.hiddenCount} more',
- onTap: () {},
- ),
- onTap: () => onExpand(section),
- ),
- ], caption: section.caption);
- }
- return cards;
-}
-
-/// A title made of named parts — an agent, then its machine — one per line.
-///
-/// The first part reads as the title and the rest as quieter lines under it. A long name wraps, up to
-/// two lines each, and only past that is it cut with `…` — so a pathological name cannot push the
-/// actions off the sheet.
-class _TitleParts extends StatelessWidget {
- const _TitleParts({required this.parts});
-
- final List<String> parts;
-
- @override
- Widget build(BuildContext context) => Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- for (var index = 0; index < parts.length; index++)
- Text(
- parts[index],
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- // 17 over the place lines' 13: the name is what the whole sheet is about, and it has to
- // read as the heading of the cards under it rather than as one more line among them.
- style: index == 0
- ? TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 17,
- fontWeight: FontWeight.w600,
- )
- : TextStyle(color: AppPalette.textSecondary, fontSize: 13),
- ),
- ],
- );
-}
-
-/// One row of a sheet's card: the icon, the label, then a value and a chevron when it has them.
-///
-/// On a [Material] of its own because the card under it is a painted box: an [InkWell] draws on the
-/// nearest Material, which without this is the sheet's — UNDER the card's fill, where no press
-/// would ever show. [SettingsRow] does the same, for the same reason.
-class _SheetRow extends StatelessWidget {
- const _SheetRow({required this.action, required this.onTap});
-
- final PhoneSheetAction action;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- // ⚠️ **The danger INK, not [AppPalette.dangerFill].** The fill is darkened to carry white
- // lettering on top of it; used as the lettering itself it measured 3.4:1 on this sheet — under
- // the 4.5:1 floor, on the one row a reader most needs to read right. `colorScheme.error` is the
- // red tuned as ink on a dark surface: 4.8:1 on the card.
- final color = !action.enabled
- ? AppPalette.textFaint
- : action.destructive
- ? Theme.of(context).colorScheme.error
- : AppPalette.textPrimary;
- final value = action.value;
- return Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: action.enabled ? onTap : null,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
- child: Row(
- children: [
- Icon(action.icon, size: 20, color: color),
- const SizedBox(width: 14),
- Expanded(
- child: Text(
- action.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: color,
- fontSize: 16,
- fontWeight: FontWeight.w500,
- ),
- ),
- ),
- if (value != null) ...[
- const SizedBox(width: 12),
- // Capped rather than left to its own width: a value can be as
- // long as a model id, and a Row lays a non-flex child out before
- // it gives the label what is left — so an uncapped one would eat
- // the label first and then run off the end of the sheet.
- ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 150),
- child: Text(
- value,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- textAlign: TextAlign.end,
- style: TextStyle(
- color: action.valueColor ?? AppPalette.textSecondary,
- fontSize: 14,
- ),
- ),
- ),
- ],
- if (action.chevron)
- Padding(
- padding: const EdgeInsets.only(left: 4),
- child: Transform.translate(
- // Nudged right by the blank the glyph carries — see [kChevronInk] — so the
- // arrow ends on the row's margin, where a label or a value would.
- offset: const Offset(kChevronInk, 0),
- child: Icon(
- LucideIcons.chevronRight300,
- size: 20,
- color: AppPalette.textFaint,
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
-
/// A yes/no question before something that cannot be undone — stopping a harness, unlinking a
/// machine. Returns true only if the destructive button was the one pressed; Cancel, a tap on the
/// veil and Escape all answer no.
@@ -511,7 +451,10 @@ class _ConfirmDialog extends StatelessWidget {
return Dialog(
// 16 from a phone's edges, as the rename dialog: the sentence gets the width, up to the 360
// the card stops at on anything wider.
- insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
+ insetPadding: const EdgeInsets.symmetric(
+ horizontal: Tty.origin,
+ vertical: 24,
+ ),
child: Semantics(
scopesRoute: true,
namesRoute: true,
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 0eaf9f3e9..7d8b2586e 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -1,5 +1,3 @@
-import 'dart:async';
-
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -64,15 +62,17 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
WidgetsBinding.instance.addObserver(this);
final notices = widget.notifier.agentNotices.system;
notices.opened.addListener(_openNoticedAgent);
- // Signed in is the first moment a notice could be worth anything, so it is
- // the moment to ask. The OS keeps the answer; every later ask is a no-op.
- unawaited(notices.requestPermission());
+ // ⚠️ Not asked here any more. Signed in with nothing on screen, "Harness would like to send you
+ // notifications" is a question with no reason attached. It is asked the first time a harness
+ // is on screen — see `FocusHints.onDone` in `terminal_page.dart`.
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
- widget.notifier.agentNotices.system.opened.removeListener(_openNoticedAgent);
+ widget.notifier.agentNotices.system.opened.removeListener(
+ _openNoticedAgent,
+ );
_linkedMachineId.dispose();
_openAgentRequest.dispose();
for (final controller in _heroControllers.values) {
diff --git a/mobile/lib/phone/phone_tab_bar.dart b/mobile/lib/phone/phone_tab_bar.dart
index 164d6ace4..557b241cc 100644
--- a/mobile/lib/phone/phone_tab_bar.dart
+++ b/mobile/lib/phone/phone_tab_bar.dart
@@ -178,7 +178,7 @@ class _Badge extends StatelessWidget {
color: AppTheme.pick(Colors.white, const Color(0xFF181818)),
fontSize: 10,
height: 1.2,
- fontWeight: FontWeight.w700,
+ fontWeight: FontWeight.w600,
fontFeatures: AppFont.tabularFigures,
),
),
diff --git a/mobile/lib/phone/project_picker_sheet.dart b/mobile/lib/phone/project_picker_sheet.dart
deleted file mode 100644
index 0a6fe0d30..000000000
--- a/mobile/lib/phone/project_picker_sheet.dart
+++ /dev/null
@@ -1,216 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-
-import 'phone_search_field.dart';
-import 'sheet_list.dart';
-
-/// The folders a harness has been started in on this machine, searchable.
-///
-/// The desktop's project menu is a filter field over the same history — "Find a project by name or
-/// path" (`state/new_harness.dart`, `NewHarnessField.projectMenu`) — and this is that field on a
-/// phone. The three ways of naming a folder the machine does not know yet (Clone Repository, Open
-/// Folder, New Project) stay on the form itself, where the desktop also keeps them.
-///
-/// ⚠️ **By name AND by path, both.** A phone truncates a path to its last segment or two, so a
-/// query typed against what is on screen finds nothing if only the full path is matched; and a
-/// person who remembers `~/work/api` rather than `api` would find nothing if only the name were.
-/// Returns the folder chosen, or null.
-Future<String?> showProjectPickerSheet(
- BuildContext context, {
- required List<String> folders,
- required String? selected,
-}) => showModalBottomSheet<String>(
- context: context,
- useRootNavigator: true,
- showDragHandle: true,
- backgroundColor: AppPalette.panelBg,
- isScrollControlled: true,
- builder: (_) => _ProjectPicker(folders: folders, selected: selected),
-);
-
-class _ProjectPicker extends StatefulWidget {
- const _ProjectPicker({required this.folders, required this.selected});
-
- final List<String> folders;
- final String? selected;
-
- @override
- State<_ProjectPicker> createState() => _ProjectPickerState();
-}
-
-class _ProjectPickerState extends State<_ProjectPicker> {
- final _controller = TextEditingController();
- final _focus = FocusNode();
- String _query = '';
-
- @override
- void dispose() {
- _controller.dispose();
- _focus.dispose();
- super.dispose();
- }
-
- static String _name(String path) {
- final parts = path.split('/').where((part) => part.isNotEmpty);
- return parts.isEmpty ? path : parts.last;
- }
-
- List<String> get _matches {
- final query = _query.trim().toLowerCase();
- if (query.isEmpty) return widget.folders;
- return [
- for (final folder in widget.folders)
- if (folder.toLowerCase().contains(query)) folder,
- ];
- }
-
- /// Puts the keyboard away and takes the caret out of the field.
- ///
- /// ⚠️ **[FocusManager], not `_focus.unfocus()`.** The field is not always what holds the focus
- /// by the time this runs — the sheet is closing, or the tap landed on the list — and unfocusing
- /// a node that does not have it does nothing at all, which is exactly the bug: the sheet went
- /// and the keyboard stayed, standing over the form underneath.
- void _dismissKeyboard() => FocusManager.instance.primaryFocus?.unfocus();
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final matches = _matches;
- return GestureDetector(
- // ⚠️ A tap ANYWHERE that is not a row: the empty space under a short list, the sheet's own
- // margins, the space beside the field. Opaque so those taps land here rather than falling
- // through to whatever is behind the sheet; a row's own detector is nearer the tap and still
- // wins, so choosing a folder is unaffected.
- behavior: HitTestBehavior.opaque,
- onTap: _dismissKeyboard,
- child: SafeArea(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(
- kSheetInset,
- 0,
- kSheetInset,
- 10,
- ),
- child: PhoneSearchField(
- controller: _controller,
- focus: _focus,
- // ⚠️ **The way out, and the sheet had none.** It fills the screen once its list
- // is longer than a few rows, so the drag-down a short sheet is dismissed by is
- // nowhere near the thumb — and a person who opened it to look rather than to
- // choose was stuck until they picked a folder they did not want. The chevron is
- // where every other search bar on this phone keeps it.
- onBack: () {
- _dismissKeyboard();
- Navigator.of(context).pop();
- },
- // ⚠️ Not autofocused, for the reason the branch picker gives: a machine used for a
- // week has a handful of folders and the answer is already on screen, where a
- // keyboard would bury it.
- autofocus: false,
- hintText: 'Search recent folders',
- onChanged: (value) => setState(() => _query = value),
- onClear: () => setState(() {
- _controller.clear();
- _query = '';
- }),
- ),
- ),
- Flexible(
- child: matches.isEmpty
- ? Padding(
- padding: const EdgeInsets.fromLTRB(
- kSheetInset,
- 8,
- kSheetInset,
- 24,
- ),
- child: Text(
- widget.folders.isEmpty
- ? 'No folders yet. Open one, clone a repository, or '
- 'make a new project.'
- : 'No folder matches “${_query.trim()}”.',
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 13.5,
- ),
- ),
- )
- : ListView.builder(
- // Dragging the list is a way of saying "let me read this",
- // and iOS puts the keyboard away for it everywhere else.
- keyboardDismissBehavior:
- ScrollViewKeyboardDismissBehavior.onDrag,
- padding: EdgeInsets.fromLTRB(
- kSheetInset,
- 0,
- kSheetInset,
- MediaQuery.paddingOf(context).bottom + 16,
- ),
- itemCount: matches.length,
- itemBuilder: (context, index) {
- final folder = matches[index];
- final chosen = folder == widget.selected;
- return SheetRow(
- first: index == 0,
- last: index == matches.length - 1,
- leading: SheetTile(
- child: Icon(
- LucideIcons.folder300,
- size: 18,
- color: chosen
- ? AppPalette.accentOnSurface
- : AppPalette.textSecondary,
- ),
- ),
- title: Text(
- _name(folder),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: sheetRowTitleStyle(),
- ),
- // The path under the name, not instead of it: two
- // machines can hold `api`, and the folder is the only
- // thing that tells them apart.
- subtitle: Text(
- folder,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 12.5,
- ),
- ),
- chevron: false,
- selected: chosen,
- trailing: chosen
- ? Icon(
- LucideIcons.check300,
- size: 18,
- color: AppPalette.accent,
- )
- : null,
- onTap: () {
- HapticFeedback.selectionClick();
- // Before the pop, not after: once the route is gone
- // this State is unmounted and its context can no
- // longer be asked for anything.
- _dismissKeyboard();
- Navigator.of(context).pop(folder);
- },
- );
- },
- ),
- ),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/question_keys.dart b/mobile/lib/phone/question_keys.dart
new file mode 100644
index 000000000..ea0b2f401
--- /dev/null
+++ b/mobile/lib/phone/question_keys.dart
@@ -0,0 +1,168 @@
+import 'package:harness_mobile/terminal/question_pane.dart';
+
+/// One answer key on the prompt bar: what it says and the digit it presses.
+typedef QuestionKey = ({String label, String number});
+
+/// The keys for an open Claude/Codex dialog, as the status line draws them in prompt mode —
+/// ` 1 yes │ 2 always │ 3 no `.
+///
+/// A row's label is shortened to its first word or two: lowercased, cut at a `,` or `(`, and a row
+/// that means "don't ask again" / "allow all" is called `always` — the word a person would say.
+List<QuestionKey> questionKeys(QuestionPaneView view) => [
+ for (final row in view.rows) (label: _short(row.label), number: row.number),
+];
+
+String _short(String label) {
+ final lower = label.toLowerCase().trim();
+ if (lower.contains("don't ask again") ||
+ lower.contains('do not ask again') ||
+ lower.contains('allow all') ||
+ lower.contains('always')) {
+ return 'always';
+ }
+ final cut = lower.split(RegExp(r'[,(]')).first.trim();
+ final words = cut.split(RegExp(r'\s+'));
+ return words.length <= 2 ? cut : words.take(2).join(' ');
+}
+
+/// What a spoken reply means to an open dialog: the key it presses, and anything said after it
+/// ("no, use dist/ instead" → key 3, then "use dist/ instead" once the dialog has closed).
+///
+/// ⚠️ **Every word lands somewhere.** A number or an answer's own word presses that answer; a reply
+/// that starts like yes or no ("yeah do it", "ship it", "no wait") presses yes or no; anything else
+/// is words for the agent — the dialog's "tell Claude what to do differently" answer, with what
+/// was said sent once the dialog has closed. Null only when the dialog has no such answer — then
+/// nothing is sent at all: a reply must never reach a dialog as keystrokes and a blind Return.
+({String number, String? rest})? matchSpokenAnswer(
+ String spoken,
+ QuestionPaneView view,
+) {
+ final text = spoken.trim().toLowerCase().replaceAll(RegExp(r'[.!?]+$'), '');
+ if (text.isEmpty || view.rows.isEmpty) return null;
+ final keys = questionKeys(view);
+ String? numberWhere(bool Function(QuestionKey key) test) =>
+ keys.where(test).firstOrNull?.number;
+ final words = [
+ for (final word in text.split(RegExp(r"[^a-z0-9'’]+")))
+ if (word.isNotEmpty) word,
+ ];
+ if (words.isEmpty) return null;
+ String? after(int count) => _nonEmpty(
+ words.skip(count).join(' ').replaceFirst(RegExp(r'^(and|but|then)\s+'), ''),
+ );
+
+ const ordinals = {
+ 'one': '1',
+ 'first': '1',
+ 'two': '2',
+ 'second': '2',
+ 'to': '2',
+ 'too': '2',
+ 'three': '3',
+ 'third': '3',
+ 'four': '4',
+ 'fourth': '4',
+ 'five': '5',
+ };
+ // "option two", "number 3", "2", "two".
+ var lead = 0;
+ if (words.length > 1 && (words[0] == 'option' || words[0] == 'number')) {
+ lead = 1;
+ }
+ final digit = RegExp(r'^\d$').hasMatch(words[lead])
+ ? words[lead]
+ : ordinals[words[lead]];
+ if (digit != null && keys.any((key) => key.number == digit)) {
+ return (number: digit, rest: after(lead + 1));
+ }
+ const alwaysWords = {'always'};
+ const yesPhrases = {
+ 'go ahead',
+ 'do it',
+ 'ship it',
+ 'go for',
+ 'sounds good',
+ 'looks good',
+ 'let\'s go',
+ 'lets go',
+ 'why not',
+ };
+ const yesWords = {
+ 'yes',
+ 'yeah',
+ 'yep',
+ 'yup',
+ 'yea',
+ 'sure',
+ 'ok',
+ 'okay',
+ 'alright',
+ 'fine',
+ 'go',
+ 'approve',
+ 'approved',
+ 'proceed',
+ 'continue',
+ 'lgtm',
+ 'ship',
+ 'correct',
+ 'right',
+ 'affirmative',
+ };
+ const noWords = {
+ 'no',
+ 'nope',
+ 'nah',
+ 'stop',
+ 'wait',
+ "don't",
+ 'don’t',
+ 'dont',
+ 'cancel',
+ 'deny',
+ 'hold',
+ 'never',
+ 'negative',
+ };
+ final two = words.take(2).join(' ');
+ if (alwaysWords.contains(words.first) ||
+ two == 'yes always' ||
+ two == 'allow all') {
+ final always = numberWhere((key) => key.label == 'always');
+ if (always != null) return (number: always, rest: after(1));
+ }
+ if (yesPhrases.contains(two) || yesWords.contains(words.first)) {
+ final yes = numberWhere((key) => key.label.startsWith('yes'));
+ if (yes != null) {
+ final used = yesPhrases.contains(two) ? 2 : 1;
+ // "go for it" — the phrase's third word goes with it.
+ final extra = two == 'go for' && words.length > 2 && words[2] == 'it'
+ ? 1
+ : 0;
+ return (number: yes, rest: after(used + extra));
+ }
+ }
+ if (noWords.contains(words.first)) {
+ final no = numberWhere((key) => key.label.startsWith('no'));
+ if (no != null) return (number: no, rest: after(1));
+ }
+ // An answer said in its own words: "yes and don't ask again" / "no and tell claude".
+ for (final key in keys) {
+ if (key.label.length > 2 && text.startsWith(key.label)) {
+ return (number: key.number, rest: null);
+ }
+ }
+ // Anything else is words for the agent: the dialog's "tell it what to do instead" answer, with
+ // everything said as the message.
+ for (final row in view.rows) {
+ if (row.label.toLowerCase().contains('tell')) {
+ return (number: row.number, rest: _nonEmpty(spoken.trim()));
+ }
+ }
+ return null;
+}
+
+String? _nonEmpty(String? text) {
+ final trimmed = text?.trim();
+ return trimmed == null || trimmed.isEmpty ? null : trimmed;
+}
diff --git a/mobile/lib/phone/search_result_text.dart b/mobile/lib/phone/search_result_text.dart
index 7d24461ce..35c842ebb 100644
--- a/mobile/lib/phone/search_result_text.dart
+++ b/mobile/lib/phone/search_result_text.dart
@@ -5,6 +5,8 @@ import 'package:harness_mobile/core/fuzzy_match.dart';
import 'phone_destination.dart';
import 'phone_search_rank.dart';
+import 'package:harness_mobile/state/session_content_search.dart';
+
/// Which field earned each query term its score, and whether that field is one
/// of the row's names.
typedef PhoneFieldMatch = ({String field, String term, bool title});
@@ -170,7 +172,7 @@ class SearchResultText extends StatelessWidget {
var offset = 0;
for (final run in runs) {
final emphasis = run.matched
- ? const TextStyle(fontWeight: FontWeight.w700)
+ ? const TextStyle(fontWeight: FontWeight.w600)
: null;
if (insertIcon &&
iconOffset >= offset &&
@@ -207,3 +209,33 @@ class SearchResultText extends StatelessWidget {
);
}
}
+
+/// Where a session index found the words: what was asked reads like a prompt, a command like a
+/// shell line, and the agent's answer plainly — the desktop's `snippetLead`.
+String snippetLead(String field) => switch (field) {
+ 'ask' => '> ',
+ 'tools' => r'$ ',
+ _ => '',
+};
+
+/// A session index snippet split at its marks, matched words flagged — the desktop's
+/// `snippetRuns`.
+List<PhoneTextRun> snippetRuns(String snippet) {
+ final runs = <PhoneTextRun>[];
+ var rest = snippet;
+ while (rest.isNotEmpty) {
+ final open = rest.indexOf(kSnippetMarkOpen);
+ if (open < 0) {
+ runs.add((text: rest, matched: false));
+ break;
+ }
+ if (open > 0) runs.add((text: rest.substring(0, open), matched: false));
+ final close = rest.indexOf(kSnippetMarkClose, open + 1);
+ final end = close < 0 ? rest.length : close;
+ if (end > open + 1) {
+ runs.add((text: rest.substring(open + 1, end), matched: true));
+ }
+ rest = close < 0 ? '' : rest.substring(close + 1);
+ }
+ return runs;
+}
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index 65fc98e55..212b7400b 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -5,6 +5,8 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:harness_mobile/core/app_version.dart';
+import 'package:harness_mobile/demo/sample_mode.dart'
+ show SampleMode, SampleSession, openSampleMode;
import 'package:harness_mobile/core/device_name.dart';
import 'package:harness_mobile/shared/widgets/app_dialog.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -14,11 +16,15 @@ import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_theme_store.dart';
-import 'phone_header.dart';
+import 'machines_tab.dart';
+import 'phone_navigation.dart' show phoneRoute;
import 'phone_name_store.dart';
import 'phone_sheet.dart';
import 'settings_row.dart';
-import 'stats_entry.dart';
+import 'welcome/how_it_works.dart';
+import 'welcome/focus_hints.dart';
+import 'tty_controls.dart';
+import 'tty.dart';
import 'usage_entry.dart';
import 'voice_language.dart';
import 'voice_language_store.dart';
@@ -36,9 +42,8 @@ import 'voice_language_store.dart';
/// **Usage** used to be on that list, for a reason that was true of the desktop reader and not of
/// the setting: it counts by reading `~/.claude/projects`, `~/.codex` and OpenCode's SQLite file ON
/// THIS DISK, and a phone has none of them. What a phone can do is ask the machine that does — so
-/// the section is kept, and its two rows come from elsewhere: `usage_entry.dart` reads each linked
-/// machine's rate limits over `usage_read`, and `stats_entry.dart` reads the counters this app keeps
-/// about itself.
+/// the section is kept, and its row comes from elsewhere: `usage_entry.dart` reads each linked
+/// machine's rate limits over `usage_read`.
///
/// What a phone shows that the desktop splits across panes:
///
@@ -73,15 +78,53 @@ class SettingsPage extends StatelessWidget {
listenable: notifier,
builder: (context, _) {
AppTheme.watch(context);
+ final tty = Tty.of(context);
return Scaffold(
- backgroundColor: AppPalette.windowBg,
+ backgroundColor: tty.ground,
body: SafeArea(
bottom: false,
- child: Column(
- children: [
- PhoneHeader(large: large, title: 'Settings'),
- Expanded(child: _Body(notifier: notifier)),
- ],
+ // The terminal's face for every row below, as on every other screen of the phone.
+ // Through the theme, not only a DefaultTextStyle: every Material in the rows resets the
+ // default text style from the theme's text theme.
+ child: Theme(
+ data: Theme.of(context).copyWith(
+ textTheme: Theme.of(context).textTheme.apply(
+ fontFamily: tty.fontFamily,
+ fontFamilyFallback: tty.fontFallback,
+ ),
+ ),
+ child: DefaultTextStyle.merge(
+ style: TextStyle(
+ fontFamily: tty.fontFamily,
+ fontFamilyFallback: tty.fontFallback,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (!large)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ 0,
+ ),
+ child: TtyText(
+ 'Settings',
+ size: TtySize.display,
+ weight: FontWeight.w600,
+ ),
+ ),
+ Expanded(child: _Body(notifier: notifier)),
+ ],
+ ),
+ ),
),
),
);
@@ -97,23 +140,26 @@ class _Body extends StatelessWidget {
@override
Widget build(BuildContext context) => ListView(
padding: EdgeInsets.fromLTRB(
- 16,
+ Tty.origin,
// Zero: the first caption brings its own 22pt top, and any padding here would stack on it —
// the gap under the big "Settings" title would then be a header gap plus a between-groups
// gap, wider than every other gap on the screen.
0,
- 16,
+ Tty.origin,
MediaQuery.paddingOf(context).bottom + 24,
),
children: [
- const SettingsCaption('Account'),
+ SettingsCaption(_sample(context) == null ? 'Account' : 'Sample'),
SettingsGroup(
children: [
+ _accountRow(context),
+ // The computers this phone reaches — here rather than a menu of their own: linking one is
+ // a once-a-while errand, and Find already reaches every agent on them.
SettingsRow(
- leading: _Avatar(notifier: notifier),
- title: notifier.currentUser?.displayName ?? 'Signed in',
- detail: notifier.currentUser?.email,
- onTap: () => _showAccountSheet(context, notifier),
+ title: 'Computers',
+ onTap: () => Navigator.of(context).push(
+ phoneRoute((_) => MachinesTab(notifier: notifier, large: false)),
+ ),
),
],
),
@@ -124,13 +170,14 @@ class _Body extends StatelessWidget {
const SettingsCaption('Usage'),
SettingsGroup(
children: [
+ // No Stats row: counters this app keeps about itself are nobody's daily question.
buildUsageSettingsRow(context, notifier),
- buildStatsSettingsRow(context, notifier),
],
),
const SettingsCaption('Terminal'),
SettingsGroup(
children: [
+ _FontPreview(),
_PhoneNameRow(notifier: notifier),
_FontRow(),
_SizeRow(),
@@ -147,14 +194,61 @@ class _Body extends StatelessWidget {
SettingsGroup(children: [_VoiceLanguageRow()]),
const SettingsCaption('Appearance'),
SettingsGroup(children: [_PaletteRow(), _TextSizeRow()]),
- const SettingsNote(
- 'Harness is dark-only, so a palette picks the shade rather than the mode.',
+ const SettingsCaption('Help'),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ title: 'How Harness works',
+ onTap: () => unawaited(openHowItWorks(context)),
+ ),
+ // The offline sample, from inside the real app too — to show somebody, or to try a
+ // gesture without touching a real harness. Not offered inside the sample itself.
+ if (_sample(context) == null)
+ SettingsRow(
+ title: 'Try the sample',
+ onTap: () => unawaited(openSampleMode(context)),
+ ),
+ SettingsRow(
+ title: 'Show the tips again',
+ onTap: () {
+ unawaited(FocusHintsSeen.shared.forget());
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ const SnackBar(
+ content: Text('The tips come back on the next harness.'),
+ ),
+ );
+ },
+ ),
+ ],
),
const SettingsCaption('About'),
SettingsGroup(children: const [_VersionRow(), _BuildRow()]),
],
);
+ /// The sample this page is in, or null in the real app — see `lib/demo/sample_mode.dart`.
+ SampleSession? _sample(BuildContext context) =>
+ SampleMode.maybeOf(context) ?? SampleMode.ofNotifier(notifier);
+
+ /// Who is signed in — or, in sample mode, which has no account to show or sign out of, the
+ /// way back out of it.
+ Widget _accountRow(BuildContext context) {
+ final sample = _sample(context);
+ if (sample != null) {
+ return SettingsRow(
+ key: const ValueKey('settings-leave-sample'),
+ title: 'Leave sample',
+ onTap: () => sample.leave(),
+ );
+ }
+ return SettingsRow(
+ leading: _Avatar(notifier: notifier),
+ title: notifier.currentUser?.displayName ?? 'Signed in',
+ detail: notifier.currentUser?.email,
+ onTap: () => _showAccountSheet(context, notifier),
+ );
+ }
+
void _showAccountSheet(BuildContext context, AppNotifier notifier) {
showPhoneSheet(
context,
@@ -249,7 +343,6 @@ class _PhoneNameRow extends StatelessWidget {
return SettingsRow(
key: const ValueKey('settings-phone-name'),
title: 'This phone',
- detail: 'How a desktop names this phone when it takes a terminal',
value: notifier.phoneClientDescriptor().name,
onTap: () => unawaited(
showAppDialog<void>(
@@ -329,6 +422,42 @@ class _PhoneNameDialogState extends State<_PhoneNameDialog> {
}
}
+/// One terminal line in the chosen face and size — what Font and Size change, live, above them.
+class _FontPreview extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) => ValueListenableBuilder(
+ valueListenable: terminalFontStore,
+ builder: (context, font, _) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ TextStyle ink(Color color) => TextStyle(
+ fontFamily: font.fontFamily,
+ fontFamilyFallback: font.fontFamilyFallback,
+ fontSize: font.fontSize,
+ height: 1.2,
+ color: color,
+ );
+ return ExcludeSemantics(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(13, 14, 13, 14),
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(text: '~/web ', style: ink(tty.faint)),
+ TextSpan(text: '❯ ', style: ink(tty.green)),
+ TextSpan(text: 'claude "fix the login"', style: ink(tty.text)),
+ ],
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
+ ),
+ ),
+ );
+ },
+ );
+}
+
/// The terminal typeface. A sheet rather than a dropdown: a phone has room for the whole list.
class _FontRow extends StatelessWidget {
@override
@@ -395,9 +524,14 @@ class _TerminalThemeRow extends StatelessWidget {
valueListenable: terminalThemeStore,
builder: (context, choice, _) {
AppTheme.watch(context);
+ // "Same as the app" names a rule; the palette it resolves to names a colour.
+ String label(TerminalThemeChoice option) =>
+ option == TerminalThemeChoice.matchApp
+ ? appearancePrefsStore.value.palette.label
+ : option.label;
return SettingsRow(
title: 'Colors',
- value: choice.label,
+ value: label(choice),
onTap: () => showPhoneSheet(
context,
title: 'Terminal colors',
@@ -407,7 +541,7 @@ class _TerminalThemeRow extends StatelessWidget {
icon: option == choice
? LucideIcons.check300
: LucideIcons.palette300,
- label: option.label,
+ label: label(option),
onTap: () => unawaited(terminalThemeStore.set(option)),
),
],
@@ -442,7 +576,7 @@ class _PaletteRow extends StatelessWidget {
icon: palette == prefs.palette
? LucideIcons.check300
: LucideIcons.swatchBook300,
- label: '${palette.label} · ${palette.description}',
+ label: palette.label,
onTap: () =>
unawaited(appearancePrefsStore.setPalette(palette)),
),
@@ -486,7 +620,7 @@ class _VersionRow extends StatelessWidget {
future: runningAppVersion(),
builder: (context, snapshot) {
AppTheme.watch(context);
- return SettingsRow(title: 'Version', value: snapshot.data ?? '—');
+ return SettingsRow(title: 'Version', value: snapshot.data ?? '');
},
);
}
@@ -519,14 +653,10 @@ class _BuildRow extends StatelessWidget {
builder: (context, snapshot) {
AppTheme.watch(context);
final info = snapshot.data;
- // Empty rather than missing on Linux/desktop dev builds, where nothing stamps it — the em
- // dash covers both, so a blank string never renders as a row with no value.
+ // Empty on Linux/desktop dev builds, where nothing stamps it: the row says nothing rather
+ // than a dash.
final build = info?.buildNumber ?? '';
- return SettingsRow(
- title: 'Build',
- value: build.isEmpty ? '—' : build,
- detail: info?.packageName,
- );
+ return SettingsRow(title: 'Build', value: build);
},
);
}
diff --git a/mobile/lib/phone/settings_row.dart b/mobile/lib/phone/settings_row.dart
index c7aaa4d39..f33559f16 100644
--- a/mobile/lib/phone/settings_row.dart
+++ b/mobile/lib/phone/settings_row.dart
@@ -58,14 +58,10 @@ class SettingsCaption extends StatelessWidget {
// that group than to the one it follows. Equal gaps either side would leave every caption
// floating between two cards with nothing to say which it labels.
padding: const EdgeInsets.fromLTRB(4, 22, 4, 8),
+ // Lowercase and 13pt, the way Find heads its sections (`needs you`, `recent`).
child: Text(
- text.toUpperCase(),
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 11.5,
- fontWeight: FontWeight.w600,
- letterSpacing: 0.5,
- ),
+ text.toLowerCase(),
+ style: TextStyle(color: AppPalette.textFaint, fontSize: 13),
),
);
}
@@ -111,10 +107,10 @@ class SettingsGroup extends StatelessWidget {
// row happens to need. Belt and braces with the `stretch` below: the alignment makes the rows
// fill the card, this makes the card fill the list.
width: double.infinity,
+ // Filled, not outlined: one raised step off the page, like the phone's fields.
decoration: BoxDecoration(
color: AppGlass.rowFill,
borderRadius: BorderRadius.circular(AppCard.radius),
- border: Border.all(color: AppGlass.hair),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppCard.radius),
diff --git a/mobile/lib/phone/sheet_list.dart b/mobile/lib/phone/sheet_list.dart
index 4b8424942..051674dda 100644
--- a/mobile/lib/phone/sheet_list.dart
+++ b/mobile/lib/phone/sheet_list.dart
@@ -403,7 +403,7 @@ class SheetGlyphTile extends StatelessWidget {
style: phoneBoxMonoStyle(
size: 14,
color: AppPalette.textPrimary,
- weight: FontWeight.w700,
+ weight: FontWeight.w600,
).copyWith(height: 1),
),
);
diff --git a/mobile/lib/phone/sheet_search_row.dart b/mobile/lib/phone/sheet_search_row.dart
index 0139c0e55..9e56c7e6a 100644
--- a/mobile/lib/phone/sheet_search_row.dart
+++ b/mobile/lib/phone/sheet_search_row.dart
@@ -89,6 +89,10 @@ class SheetSearchRow extends StatelessWidget {
PhoneDestinationKind.project => const SheetGlyphTile('#'),
PhoneDestinationKind.command => const SheetGlyphTile('>'),
PhoneDestinationKind.mode => SheetGlyphTile(_modeGlyph(row) ?? '?'),
+ PhoneDestinationKind.external => SheetEngineTile(
+ engine: row.engine,
+ displayName: row.external?.engineLabel,
+ ),
};
/// A `?` row's own character — the one a tap on it puts in the field.
diff --git a/mobile/lib/phone/stats_entry.dart b/mobile/lib/phone/stats_entry.dart
deleted file mode 100644
index 758c78c82..000000000
--- a/mobile/lib/phone/stats_entry.dart
+++ /dev/null
@@ -1,41 +0,0 @@
-import 'package:flutter/material.dart';
-
-import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/stats/harness_stats.dart';
-
-import 'phone_navigation.dart';
-import 'settings_row.dart';
-import 'stats_page.dart';
-
-/// The Settings row that opens [StatsPage].
-///
-/// A function rather than a widget class, and it lives here rather than in the settings list, for
-/// one reason: that list builds every row inline, so a feature owning a page of its own would
-/// otherwise have its row wired up in a file that knows nothing else about it. This keeps the row,
-/// the page and the counters behind them together — the settings list only has to call it.
-///
-/// [notifier] is unused today and deliberately still taken: every other entry point on that list is
-/// handed one, and a row that later wants the app model — a count of live agents beside the figure,
-/// say — should not change the shape of the call to get it.
-Widget buildStatsSettingsRow(BuildContext context, AppNotifier notifier) =>
- // Subscribed to the counters rather than reading them once: the settings list rebuilds on the
- // app model, which does not move when an agent is spawned from another tab, so the figure below
- // would otherwise sit at whatever it was when Settings was first drawn.
- ListenableBuilder(
- listenable: harnessStats,
- builder: (context, _) {
- final summary = harnessStats.summary;
- return SettingsRow(
- title: 'Stats',
- // The headline figure on the row itself, so the list answers "has this counted
- // anything?" without a push. Empty reads as an em dash rather than "0 agents", which
- // looks like a figure that was measured and came out zero.
- value: summary.isEmpty
- ? '—'
- : '${formatStatCount(summary.agentsSpawned)} '
- '${summary.agentsSpawned == 1 ? 'agent' : 'agents'}',
- onTap: () =>
- Navigator.of(context).push(phoneRoute((_) => const StatsPage())),
- );
- },
- );
diff --git a/mobile/lib/phone/terminal_action_column.dart b/mobile/lib/phone/terminal_action_column.dart
index f0e0cc874..a7029be00 100644
--- a/mobile/lib/phone/terminal_action_column.dart
+++ b/mobile/lib/phone/terminal_action_column.dart
@@ -1,5 +1,4 @@
import 'package:flutter/material.dart';
-import 'package:flutter/rendering.dart' show OverflowBoxFit;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/notify/agent_unread.dart';
@@ -13,7 +12,6 @@ import 'voice_input_controller.dart';
import 'voice_mic_button.dart';
import 'voice_mic_face.dart';
import 'voice_mic_fab.dart';
-import 'voice_status_pill.dart';
/// The terminal's floating controls, stacked in its bottom-right corner:
/// the mic, then Search.
@@ -47,10 +45,14 @@ class TerminalActionColumn extends StatefulWidget {
required this.onSearch,
this.unread,
this.searchOnly = false,
+ this.working = false,
});
final VoiceInputController voice;
+ /// The agent is working: the mic wears a ring — see `VoiceMicCore.working`.
+ final bool working;
+
/// Agents that finished while you were on this one. Search is where they are
/// reached from, so it wears their count — the dial's bell pill. Null draws
/// the plain button.
@@ -78,9 +80,13 @@ class TerminalActionColumn extends StatefulWidget {
/// How far the column sits from the terminal's right and bottom edges.
static const double inset = VoiceMicFab.inset;
- /// How far the column sits above the terminal's bottom edge — higher than
- /// [inset], so Search clears the agent's own status line under it.
- static const double bottomInset = 172;
+ /// How far the orb's slot sits above the foot of the page. Low and centred, where Siri's orb
+ /// stands over the dock — below the agent's prompt rather than on it — and the terminal runs full
+ /// screen under it.
+ ///
+ /// Measured off Siri: its orb's centre stands about 76pt above the foot of an iPhone 14, so
+ /// this slot's foot sits half the slot below that.
+ static const double orbBottom = 76 - VoiceMicButton.extent / 2;
/// How far Search sits from the terminal's TOP edge while the keyboard is up
/// — see [searchOnly].
@@ -93,30 +99,6 @@ class TerminalActionColumn extends StatefulWidget {
/// That is the whole reason it moves rather than staying where it was.
static const double topInset = TerminalHeader.height + 8;
- /// The DRAWN gap between one circle and the next, the same all the way down.
- ///
- /// ⚠️ No smaller than the mic's overhang plus a button's, less the slack
- /// between the mic's slot and its drawn face — any closer and the mic's
- /// target would swallow the top of Search's.
- static const double _gap = 22;
-
- /// The mic's slot is larger than its drawn circle, so the gap under the slot
- /// is [_gap] less that slack.
- static const double _underMic =
- _gap - (VoiceMicButton.extent - VoiceMicCore.diameter) / 2;
-
- /// How far the capsule's right end sits in from the mic's slot: the slack
- /// between the slot and the circle, so the circle closes the capsule exactly.
- static const double _capsuleInset =
- (VoiceMicButton.extent - VoiceMicCore.diameter) / 2;
-
- /// The capsule's widest, however wide the phone: a notice is easier to read
- /// in two lines of a sensible length than in one line across a tablet.
- static const double _capsuleMaxWidth = 360;
-
- /// What the capsule leaves clear at the terminal's left edge.
- static const double _capsuleLeftMargin = 16;
-
@override
State<TerminalActionColumn> createState() => _TerminalActionColumnState();
}
@@ -143,86 +125,34 @@ class _TerminalActionColumnState extends State<TerminalActionColumn> {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- // One backdrop read for the buttons' blurs — see [FloatingGlass].
- return BackdropGroup(child: _column(context, widget.session));
+ return _column(context, widget.session);
}
Widget _column(BuildContext context, TerminalSession? session) {
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.end,
- children: [
- if (widget.searchOnly)
- const SizedBox.shrink()
- else if (session != null)
- _capsule(context, session)
- else
- // Still attaching: the mic in its place, dimmed and dead.
- const VoiceMicButton(face: VoiceMicFace.talk, onPressed: null),
- if (!widget.searchOnly)
- const SizedBox(height: TerminalActionColumn._underMic),
- _centred(
- _withUnread(
- TerminalRoundAction(
- key: const ValueKey('terminal-search'),
- icon: LucideIcons.search300,
- label: 'Search harnesses and machines',
- onTap: widget.onSearch,
- ),
+ // ⚠️ **Search floats here only while the keyboard is up.** With it down, Find is a swipe right
+ // or a tap on the agent's name; with the keyboard up, Find rides up here, top right.
+ if (widget.searchOnly) {
+ return _centred(
+ _withUnread(
+ TerminalRoundAction(
+ key: const ValueKey('terminal-search'),
+ icon: LucideIcons.search300,
+ label: 'Find an agent',
+ onTap: widget.onSearch,
),
),
- ],
- );
- }
-
- /// The mic, with the capsule body under it reaching out to the left.
- ///
- /// ⚠️ **Held at the mic's height.** A notice that wraps makes the body
- /// taller than the mic's slot, and a row that grew with it would lift the mic
- /// — the one control the thumb is on — every time a sentence ran long. The
- /// body overflows the row evenly above and below instead.
- Widget _capsule(BuildContext context, TerminalSession session) {
- final maxWidth =
- (MediaQuery.sizeOf(context).width -
- TerminalActionColumn.inset -
- TerminalActionColumn._capsuleInset -
- TerminalActionColumn._capsuleLeftMargin)
- .clamp(
- VoiceMicCore.diameter,
- TerminalActionColumn._capsuleMaxWidth,
- );
- return SizedBox(
- height: VoiceMicButton.extent,
- child: Stack(
- alignment: Alignment.centerRight,
- clipBehavior: Clip.none,
- children: [
- Padding(
- padding: const EdgeInsets.only(
- right: TerminalActionColumn._capsuleInset,
- ),
- child: OverflowBox(
- fit: OverflowBoxFit.deferToChild,
- maxHeight: double.infinity,
- alignment: Alignment.centerRight,
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: maxWidth),
- child: VoiceStatusPill(
- voice: widget.voice,
- slipped: _slipped,
- micClearance: VoiceMicCore.diameter,
- ),
- ),
- ),
- ),
- // Last, so it paints over the body's end and takes the taps there.
- VoiceMicFab(
- voice: widget.voice,
- session: session,
- onSlipChanged: _onSlipChanged,
- ),
- ],
- ),
+ );
+ }
+ // Still attaching: the mic in its place, dimmed and dead.
+ if (session == null) {
+ return const VoiceMicButton(face: VoiceMicFace.talk, onPressed: null);
+ }
+ // The mic alone: what it is doing is said beside it — see `voice_bar_line.dart`.
+ return VoiceMicFab(
+ voice: widget.voice,
+ session: session,
+ onSlipChanged: _onSlipChanged,
+ working: widget.working,
);
}
diff --git a/mobile/lib/phone/terminal_header.dart b/mobile/lib/phone/terminal_header.dart
index a1c622067..6b705ffdf 100644
--- a/mobile/lib/phone/terminal_header.dart
+++ b/mobile/lib/phone/terminal_header.dart
@@ -41,6 +41,7 @@ class TerminalHeader extends StatelessWidget {
required this.status,
this.machineName,
this.trailing = const [],
+ this.onFind,
});
/// The agent this terminal belongs to. Null while it is still loading.
@@ -57,15 +58,24 @@ class TerminalHeader extends StatelessWidget {
/// the stream is read-only.
final List<Widget> trailing;
+ /// A tap on the mark or the names: Find, the list of agents. The name then wears a `⌄`, which is
+ /// how iOS says a title opens a list — the visible door to what a swipe right also opens. Null
+ /// leaves the names inert.
+ final VoidCallback? onFind;
+
/// The row's height, not counting its insets.
///
/// Two lines of type: 15pt name over 12.5pt folder, with the engine mark
/// centred against the pair.
- static const double rowHeight = 40;
+ ///
+ /// ONE line now — the agent's name — where it was two with the machine, folder and branch under
+ /// it. The header floats over the terminal's top rows, so every point it gives up is text; where
+ /// the agent runs is in the ⋮ sheet and on its row in Find.
+ static const double rowHeight = 28;
static const double sideInset = 14;
- static const double topInset = 6;
- static const double bottomInset = 8;
+ static const double topInset = 4;
+ static const double bottomInset = 6;
/// The whole header, insets and divider included — what floats over the
/// terminal's top rows while it is shown.
@@ -73,7 +83,7 @@ class TerminalHeader extends StatelessWidget {
/// The engine mark's size. Big enough to carry the status dot on its corner
/// without the dot hiding it.
- static const double markSize = 28;
+ static const double markSize = 20;
@override
Widget build(BuildContext context) {
@@ -90,14 +100,33 @@ class TerminalHeader extends StatelessWidget {
height: rowHeight,
child: Row(
children: [
- BadgedEngineMark(
- agent: agent,
- status: status,
- ring: AppPalette.windowBg,
- ),
- const SizedBox(width: 11),
Expanded(
- child: _Identity(agent: agent, machineName: machineName),
+ child: Semantics(
+ button: onFind != null,
+ label: onFind == null ? null : 'Find an agent',
+ child: GestureDetector(
+ key: const ValueKey('terminal-find'),
+ behavior: HitTestBehavior.opaque,
+ onTap: onFind,
+ child: Row(
+ children: [
+ BadgedEngineMark(
+ agent: agent,
+ status: status,
+ ring: AppPalette.windowBg,
+ ),
+ const SizedBox(width: 11),
+ Expanded(
+ child: _Identity(
+ agent: agent,
+ machineName: machineName,
+ opensFind: onFind != null,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
),
...trailing,
],
@@ -345,41 +374,59 @@ class _GlintPainter extends CustomPainter {
/// and the branch [AgentProject.shownBranch]. See [TerminalPlaceLine] for how
/// the three share the width.
class _Identity extends StatelessWidget {
- const _Identity({required this.agent, required this.machineName});
+ const _Identity({
+ required this.agent,
+ required this.machineName,
+ this.opensFind = false,
+ });
final Agent? agent;
final String? machineName;
+ /// Whether a tap here opens Find — the name then wears a `⌄`.
+ final bool opensFind;
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
final agent = this.agent;
- final project = agent?.project;
+ // The name alone, and the machine after it only in the faint face — one line. The folder and
+ // branch are in the ⋮ sheet.
final machineName = this.machineName;
- final hasPlace =
- project != null || (machineName != null && machineName.isNotEmpty);
- return Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
+ return Row(
children: [
- Text(
- agent?.displayName ?? 'Harness',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 15,
- fontWeight: FontWeight.w600,
- height: 1.2,
+ Flexible(
+ child: Text(
+ agent?.displayName ?? 'Harness',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 15,
+ fontWeight: FontWeight.w600,
+ height: 1.2,
+ ),
),
),
- if (hasPlace) ...[
- const SizedBox(height: 2),
- TerminalPlaceLine(
- machine: machineName,
- folder: project?.label,
- branch: project?.shownBranch,
- style: _placeStyle,
+ if (opensFind)
+ Padding(
+ padding: const EdgeInsets.only(left: 3),
+ child: Icon(
+ LucideIcons.chevronDown,
+ size: 15,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ if (machineName != null && machineName.isNotEmpty) ...[
+ const SizedBox(width: 8),
+ Flexible(
+ flex: 0,
+ child: Text(
+ machineName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _placeStyle,
+ ),
),
],
],
diff --git a/mobile/lib/phone/terminal_input_dock.dart b/mobile/lib/phone/terminal_input_dock.dart
index fcfc6462c..3d626e390 100644
--- a/mobile/lib/phone/terminal_input_dock.dart
+++ b/mobile/lib/phone/terminal_input_dock.dart
@@ -125,6 +125,8 @@ class _TerminalInputDockState extends State<TerminalInputDock>
onTakePhoto: widget.onTakePhoto,
questionOpen: widget.questionOpen,
hints: widget.hints,
+ ctrlArmed: widget.session.controlArmed,
+ onArmCtrl: widget.session.armControl,
),
),
builder: (context, child) {
diff --git a/mobile/lib/phone/terminal_key_bar.dart b/mobile/lib/phone/terminal_key_bar.dart
index 6b6440964..9b26bc7eb 100644
--- a/mobile/lib/phone/terminal_key_bar.dart
+++ b/mobile/lib/phone/terminal_key_bar.dart
@@ -9,6 +9,7 @@ import 'package:harness_mobile/terminal/key_hints.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'phone_sheet.dart';
+import 'tty.dart';
/// The keys a phone keyboard does not have, in a strip above the one it does.
///
@@ -60,10 +61,18 @@ class TerminalKeyBar extends StatefulWidget {
this.onTakePhoto,
this.questionOpen = false,
this.hints = const [],
+ this.ctrlArmed,
+ this.onArmCtrl,
});
final Terminal terminal;
+ /// `ctrl` as the SESSION holds it, so an armed `ctrl` is spent by the next letter typed on the
+ /// phone's own keyboard too (`TerminalSession.armControl`), not only by this row's keys. Null
+ /// keeps the modifier on the row alone.
+ final bool? ctrlArmed;
+ final ValueChanged<bool>? onArmCtrl;
+
/// An agent's question dialog is on the pane: `/` gives its slot to `⏎` —
/// see the class docblock.
final bool questionOpen;
@@ -157,7 +166,22 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
bool _ctrl = false;
bool _shift = false;
- void _toggleCtrl() => setState(() => _ctrl = !_ctrl);
+ bool get _ctrlLit => widget.ctrlArmed ?? _ctrl;
+
+ void _toggleCtrl() {
+ if (widget.onArmCtrl case final arm?) {
+ arm(!_ctrlLit);
+ return;
+ }
+ setState(() => _ctrl = !_ctrl);
+ }
+
+ /// Puts both modifiers down — the session's `ctrl` too.
+ void _disarm() {
+ if (_ctrlLit) widget.onArmCtrl?.call(false);
+ if (_ctrl || _shift) setState(() => _ctrl = _shift = false);
+ }
+
void _toggleShift() => setState(() => _shift = !_shift);
/// Sends [key] with whatever is armed, and puts the modifiers down.
@@ -166,9 +190,10 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
/// the bar takes, so an armed modifier can never survive a keystroke and land
/// on the one after it.
void _sendKey(TerminalKey key, {bool edits = false}) {
- widget.terminal.keyInput(key, ctrl: _ctrl, shift: _shift);
+ final ctrl = _ctrlLit, shift = _shift;
+ _disarm();
+ widget.terminal.keyInput(key, ctrl: ctrl, shift: shift);
if (edits) widget.onPromptEdited?.call();
- if (_ctrl || _shift) setState(() => _ctrl = _shift = false);
}
/// Presses the chord a hint named, as the pane printed it — nothing else:
@@ -182,9 +207,9 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
/// between a question and the prompt, and the buffer still holds words typed
/// into the one just left.
void _sendHint(KeyHint hint) {
+ _disarm();
hint.chord.send(widget.terminal);
widget.onPromptEdited?.call();
- if (_ctrl || _shift) setState(() => _ctrl = _shift = false);
}
@override
@@ -194,6 +219,15 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// history, move through a menu.
final keys = <Widget>[
_key(label: 'esc', onTap: () => _sendKey(TerminalKey.escape)),
+ // The other key a terminal person reaches for without looking: stop, now.
+ _key(
+ label: '^C',
+ semanticLabel: 'Control C',
+ onTap: () {
+ _disarm();
+ widget.terminal.keyInput(TerminalKey.keyC, ctrl: true);
+ },
+ ),
// Completes a path or a command, and moves through Claude Code's menus.
_key(label: 'tab', onTap: () => _sendKey(TerminalKey.tab, edits: true)),
// ⚠️ **The two modifiers stand together, before the keys they modify.**
@@ -202,25 +236,32 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// for in sequence (`ctrl` then an arrow) crossed the whole strip. Side by
// side and to the LEFT of the arrows, the row reads in the order it is
// pressed.
- _key(label: 'shift', armed: _shift, onTap: _toggleShift),
- _key(label: 'ctrl', armed: _ctrl, onTap: _toggleCtrl),
+ // The keyboard's own mark, so it fits a key at the size of the others.
+ _key(
+ label: '⇧',
+ semanticLabel: 'shift',
+ armed: _shift,
+ onTap: _toggleShift,
+ ),
+ // `ctrl` in words: `⌃` reads as an up arrow beside the arrows.
+ _key(label: 'ctrl', armed: _ctrlLit, onTap: _toggleCtrl),
_key(
- icon: LucideIcons.arrowLeft300,
+ label: '←',
semanticLabel: 'Left',
onTap: () => _sendKey(TerminalKey.arrowLeft),
),
_key(
- icon: LucideIcons.arrowUp300,
+ label: '↑',
semanticLabel: 'Up',
onTap: () => _sendKey(TerminalKey.arrowUp),
),
_key(
- icon: LucideIcons.arrowDown300,
+ label: '↓',
semanticLabel: 'Down',
onTap: () => _sendKey(TerminalKey.arrowDown),
),
_key(
- icon: LucideIcons.arrowRight300,
+ label: '→',
semanticLabel: 'Right',
onTap: () => _sendKey(TerminalKey.arrowRight),
),
@@ -228,7 +269,7 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// after the arrows, which is the order a dialog is answered in.
if (widget.questionOpen)
_key(
- icon: LucideIcons.cornerDownLeft300,
+ label: '⏎',
semanticLabel: 'Enter',
// Sent as the key, not as text: the keyboard's buffer holds nothing
// a dialog cares about, and Return is `\r` to every TUI here.
@@ -244,14 +285,14 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
final apart = <Widget>[
if (_canSendImage)
_key(
- icon: LucideIcons.image300,
+ label: 'img',
semanticLabel: 'Send image',
onTap: () => _sendImage(context),
),
// The way back to a full screen of output, which on a phone is the only
// way to read one.
_key(
- icon: LucideIcons.chevronDown300,
+ label: '▾',
semanticLabel: 'Hide keyboard',
alwaysEnabled: true,
onTap: widget.onDismissKeyboard,
@@ -265,11 +306,11 @@ class _TerminalKeyBarState extends State<TerminalKeyBar> {
// would leave with it on the first `esc`.
child: DecoratedBox(
decoration: BoxDecoration(
- color: AppPalette.panelBg,
- border: Border(top: BorderSide(color: AppGlass.hair)),
+ color: Tty.of(context).ground,
+ border: Border(top: BorderSide(color: Tty.of(context).dim)),
),
child: Padding(
- padding: const EdgeInsets.all(6),
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
// Held out of the app-wide text scale like the composer's own type:
// at a large scale the keys stop fitting the row.
child: MediaQuery.withNoTextScaling(
@@ -510,13 +551,18 @@ class _KeyCapState extends State<_KeyCap> {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- final lit = (_down || widget.armed) && widget.live;
+ final tty = Tty.of(context);
final hint = widget.hint;
- final foreground = lit
- ? AppPalette.accentOnSurface
+ // A terminal's keys: plain words and the font's own arrows, no caps. Armed (ctrl, shift) is
+ // reverse video, as a terminal marks a mode; pressed is fzf's selection ground, on the way
+ // down — no fade.
+ final armed = widget.armed && widget.live;
+ final pressed = _down && widget.live;
+ final foreground = armed
+ ? tty.ground
: widget.live
- ? AppPalette.textPrimary
- : AppPalette.textFaint;
+ ? tty.text
+ : tty.dim;
return GestureDetector(
behavior: HitTestBehavior.opaque,
// ⚠️ The tap still fires from `onTap`, not from these: a finger that
@@ -526,41 +572,25 @@ class _KeyCapState extends State<_KeyCap> {
onTapUp: (_) => _set(false),
onTapCancel: () => _set(false),
onTap: widget.onTap,
- child: AnimatedContainer(
- // Quick enough to read as the key answering the finger rather than
- // fading after it.
- duration: const Duration(milliseconds: 90),
- curve: Curves.easeOut,
- height: 34,
+ child: Container(
+ height: 40,
alignment: Alignment.center,
- decoration: BoxDecoration(
- color: lit
- ? AppPalette.accent.withValues(alpha: 0.24)
- : AppGlass.surfaceFill,
- borderRadius: BorderRadius.circular(7),
- border: Border.all(
- color: lit ? AppPalette.accentOnSurface : AppGlass.lift,
- ),
- ),
+ color: armed
+ ? tty.text
+ : pressed
+ ? tty.selected
+ : Colors.transparent,
child: hint != null
- ? _hintFace(hint, foreground: foreground, lit: lit)
- : widget.icon != null
- ? Icon(widget.icon, size: 16, color: foreground)
- // Shrinks rather than clips: ten keys share a phone's width, and
- // `clear` is the widest word among them.
+ ? _hintFace(hint, foreground: foreground, lit: armed || pressed)
+ // Shrinks rather than clips: ten keys share a phone's width.
: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 3),
+ padding: const EdgeInsets.symmetric(horizontal: 2),
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
- widget.label!,
+ widget.label ?? '',
maxLines: 1,
- style: TextStyle(
- fontSize: 13,
- height: 1,
- color: foreground,
- fontWeight: FontWeight.w500,
- ),
+ style: tty.style(color: foreground),
),
),
),
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 4d391ea0a..623c3f9e3 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -1,15 +1,20 @@
import 'dart:async';
+import 'dart:ui' as ui;
// `defaultTargetPlatform` — the navigation bar this page keeps clear of is
// Android's alone; see [_TerminalPageState._navigationBar].
-import 'package:flutter/foundation.dart' show defaultTargetPlatform;
+import 'package:flutter/foundation.dart'
+ show ValueListenable, defaultTargetPlatform;
import 'package:flutter/material.dart';
// `PlatformException` — a refused camera permission arrives as one, and it is
// the one picker failure with something the person can do about it.
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:flutter/scheduler.dart';
+import 'package:xterm/xterm.dart' show Terminal, TerminalKey, TerminalStyle;
+import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/core/models.dart' show Agent, AgentProject;
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/skeleton.dart';
@@ -29,21 +34,30 @@ import 'package:harness_mobile/widgets/terminal_panel.dart';
import 'agent_model_sections.dart';
import 'agent_model_sheet.dart';
-import 'agents_list_page.dart';
+import 'agents_page.dart' show openNewAgent;
import 'delete_agent.dart';
import 'held_height.dart';
-import 'machines_tab.dart';
-import 'phone_navigation.dart' show phoneRoute;
import 'phone_sheet.dart';
import 'phone_status.dart';
import 'settings_page.dart';
-import 'status_pill.dart';
import 'terminal_action_column.dart';
import 'terminal_chrome_scroll.dart';
import 'terminal_header.dart';
-import 'terminal_header_action.dart';
import 'terminal_input_dock.dart';
import 'terminal_search.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+import 'question_keys.dart';
+import 'voice_bar_line.dart';
+import 'voice_mic_button.dart';
+import 'phone_navigation.dart';
+import 'phone_search_catalog.dart' show phoneAgentId;
+import 'agent_index.dart';
+import 'terminal_title.dart';
+import 'welcome/focus_hints.dart';
+
+import 'package:harness_mobile/demo/sample_mode.dart';
+
import 'voice_input_controller.dart';
/// One agent's terminal, filling the phone. The header says whose it is and whether it is live;
@@ -60,6 +74,7 @@ class TerminalPage extends StatefulWidget {
required this.agentId,
required this.voice,
this.isActive = true,
+ this.sideSwipes = true,
});
final AppNotifier notifier;
@@ -82,6 +97,12 @@ class TerminalPage extends StatefulWidget {
/// SIGWINCH to three remote shells at once.
final bool isActive;
+ /// Whether a sideways swipe on the terminal opens Find (right) or a new agent (left).
+ ///
+ /// Off for a page inside a pager of agents (`AgentSwipeHost` with neighbours), where the sideways
+ /// axis is the pager's: the terminal's own detector sits deeper and would win every drag.
+ final bool sideSwipes;
+
@override
State<TerminalPage> createState() => _TerminalPageState();
}
@@ -576,6 +597,11 @@ class _TerminalPageState extends State<TerminalPage>
if (watcher == null || _keyboardSettling) return;
if (!(_readFacts().session?.acceptsInput ?? false)) return;
final view = watcher.view;
+ // ⚠️ **A dialog the bar can answer raises nothing.** Its answers are keys on the status line
+ // and words said to the mic (prompt mode); a keyboard would cover both, and push the bar that
+ // holds them off the screen. Only a dialog the bar cannot answer — multi-select — still asks
+ // for the keyboard's keys.
+ if (view != null && view.answerable && !view.multi) return;
if (view != null && view.answerable) {
final key = view.fingerprint;
if (_questionRaisedFor == key) return;
@@ -744,6 +770,15 @@ class _TerminalPageState extends State<TerminalPage>
@override
void dispose() {
+ _endCardTimer?.cancel();
+ // A take started here must not come back to a page that is gone.
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ if (session?.voiceDeliver == _deliverVoice) session?.voiceDeliver = null;
+ _barMessageTimer?.cancel();
+ _barMessage.dispose();
+ _scrollback.dispose();
widget.notifier.removeListener(_onNotifier);
_questionWatcher?.removeListener(_onQuestionPane);
_questionWatcher?.dispose();
@@ -775,13 +810,369 @@ class _TerminalPageState extends State<TerminalPage>
});
}
- /// Opens the account-wide agent list.
+ /// Harnesses other than this one that are asking something — the title's `api-fix asking`,
+ /// or `2 asking` when there are several. Null when none are.
+ String? _askingElsewhere() {
+ final asking = [
+ for (final entry in visibleAgents(agentIndex(widget.notifier)))
+ if (entry.isWaiting &&
+ !(entry.machineId == widget.machineId &&
+ entry.agent.id == widget.agentId))
+ entry,
+ ];
+ if (asking.isEmpty) return null;
+ if (asking.length > 1) return '${asking.length} asking';
+ return '${_windowName(asking.single.agent.displayName)} asking';
+ }
+
+ /// In the sample, the one thing to try next — `refactor-db needs you →` — following what has
+ /// been done: go to the harness that is asking, answer it, start one of your own. No counter:
+ /// the dot beside it glides the way the swipe goes. Null outside the sample, and once the sample
+ /// is done.
+ ({String text, int glide})? _sampleGuide() {
+ final sample = SampleMode.maybeOf(context);
+ if (sample == null || sample.endCardSeen) return null;
+ final (step, text, glide) = switch (null) {
+ _ when widget.agentId.startsWith('sample-new-') => (
+ 4,
+ '✓ yours is running',
+ 0,
+ ),
+ _ when _questionWatcher?.view != null => (
+ 2,
+ 'say “yes”, or tap an answer',
+ 0,
+ ),
+ _ when _askingElsewhere() != null => (
+ 1,
+ '${_askingElsewhere()!.replaceFirst(' asking', '')} needs you →',
+ 1,
+ ),
+ _ => (3, '← start one of your own', -1),
+ };
+ if (step == 4) _scheduleEndCard(sample);
+ // A step done: a tick you can feel, once.
+ if (_guideStep != null && step > _guideStep!) {
+ HapticFeedback.mediumImpact();
+ }
+ _guideStep = step;
+ return (text: text, glide: glide);
+ }
+
+ int? _guideStep;
+
+ bool _showEndCard = false;
+ Timer? _endCardTimer;
+
+ void _scheduleEndCard(SampleSession sample) {
+ if (_endCardTimer != null || sample.endCardSeen) return;
+ _endCardTimer = Timer(const Duration(seconds: 8), () {
+ if (!mounted || sample.endCardSeen) return;
+ sample.endCardSeen = true;
+ setState(() => _showEndCard = true);
+ });
+ }
+
+ /// Back to the harness used before this one ON THIS PHONE — holding the title's name, vim's
+ /// `:b#`. This phone's own visits first (the order its landings are remembered in); the
+ /// account's last-used order only when it has none yet.
+ void _openLastHarness() {
+ final entries = visibleAgents(agentIndex(widget.notifier));
+ bool here(AgentEntry entry) =>
+ entry.machineId == widget.machineId && entry.agent.id == widget.agentId;
+ final byId = {
+ for (final entry in entries)
+ phoneAgentId(entry.machineId, entry.agent.id): entry,
+ };
+ AgentEntry? last;
+ for (final id in widget.notifier.searchHistory.recent) {
+ final entry = byId[id];
+ if (entry != null && !here(entry) && entry.isOpenable) {
+ last = entry;
+ break;
+ }
+ }
+ last ??= (entries..sort(compareMonitorOrder))
+ .where((entry) => !here(entry) && entry.isOpenable)
+ .firstOrNull;
+ if (last == null) {
+ _flash('no other harness yet', error: true);
+ return;
+ }
+ HapticFeedback.selectionClick();
+ openAgent(context, widget.notifier, last.machineId, last.agent.id);
+ }
+
+ /// `machine:folder` for the title — where the agent works.
+ static String? _placeOf(Agent? agent, MachineState? machine) {
+ final folder = agent?.project?.name;
+ final name = machine?.machine.displayName;
+ if (folder == null || folder.isEmpty) return name;
+ return name == null ? folder : '$name:$folder';
+ }
+
+ /// vim's message line, for a moment — see [_flash].
+ final _barMessage = ValueNotifier<({String text, bool error})?>(null);
+ Timer? _barMessageTimer;
+
+ /// Says what went wrong, above the mic for two seconds, the way tmux's `display-message` does.
+ /// Nothing that went right is said: its effect is on screen, and a tap is felt.
+ void _flash(String text, {bool error = false}) {
+ _barMessageTimer?.cancel();
+ _barMessage.value = (text: text, error: error);
+ _barMessageTimer = Timer(const Duration(seconds: 2), () {
+ if (mounted) _barMessage.value = null;
+ });
+ }
+
+ /// The two answers beside the mic while a question is open — its first (`1 yes`) and its last
+ /// (`3 no`). The ones between are a tap on their own line in the terminal, where what they
+ /// mean is written in full ([_onLineTap]). Null when there is nothing to press: a question
+ /// that takes several answers, or one only partly on screen.
+ (QuestionKey, QuestionKey?)? _answerKeys(QuestionPaneView view) {
+ if (!view.answerable || view.multi) return null;
+ final keys = questionKeys(view);
+ if (keys.isEmpty) return null;
+ return (keys.first, keys.length > 1 ? keys.last : null);
+ }
+
+ /// The mic's centre, up from the terminal's foot: where Siri's orb stands, just over the home
+ /// strip — where the thumb already is. Fixed in points, not rows: the terminal's size must not
+ /// move it.
+ double get _micCenter =>
+ (_windowBottomInset > 0 ? _windowBottomInset : 12) +
+ 4 +
+ VoiceMicButton.extent / 2;
+
+ /// The foot of the line above the mic, where what is going on is said — a take, a message, the
+ /// sample's next step. See [_statusLine].
+ double get _statusBottom => _micCenter + VoiceMicButton.extent / 2 + 4;
+
+ /// How far up from the terminal's foot its last line is held while followed: just over the
+ /// home strip, and no further. The terminal fills the screen; the mic floats over it, the way
+ /// Siri's orb floats over the home screen (the owner: "we need to fill the screen 100%").
+ ///
+ /// ⚠️ **Except while the agent asks.** Its answers are the lines at its foot, and the keys
+ /// beside the mic would sit on them: the question lifts clear of the keys until it is answered.
+ double get _clearAboveMic =>
+ _questionWatcher?.view != null ? _statusBottom + 22 : _windowBottomInset;
+
+ /// The line above the mic, highest first: what a take is doing, a two-second message (`✓ 1
+ /// yes`, or an error in red), a question with no keys to offer, the sample's next step. Null
+ /// when there is nothing to say.
+ Widget? _statusLine() {
+ final tty = Tty.of(context);
+ if (voiceStatus(widget.voice, tty) case final said?) {
+ return _StatusLine(text: said.text, color: said.color);
+ }
+ if (_barMessage.value case final message?) {
+ return _StatusLine(
+ text: message.text,
+ color: message.error ? tty.red : tty.green,
+ );
+ }
+ final view = _questionWatcher?.view;
+ if (view != null && _answerKeys(view) == null) {
+ return _StatusLine(text: 'answer on screen', color: tty.yellow);
+ }
+ if (_sampleGuide() case final guide?) {
+ return _StatusLine(text: guide.text, glide: guide.glide, dot: true);
+ }
+ return null;
+ }
+
+ /// [_answerKeys] while they can be pressed here: not over the keyboard, nor while recording.
+ (QuestionKey, QuestionKey?)? get _answersBesideMic {
+ final view = _questionWatcher?.view;
+ if (view == null || _ownsInput || _keyBarUp) return null;
+ if (VoiceLine.shows(widget.voice)) return null;
+ return _answerKeys(view);
+ }
+
+ /// A tap on a row of the terminal while a question is open: on an answer's own line —
+ /// `❯ 1. Yes`, ` 2. Yes, and don't ask again` — it presses that answer.
+ bool _onLineTap(String line) {
+ final view = _questionWatcher?.view;
+ if (view == null || !view.answerable || view.multi) return false;
+ final number = _optionLine.firstMatch(line)?.group(1);
+ if (number == null) return false;
+ for (final key in questionKeys(view)) {
+ if (key.number == number) {
+ HapticFeedback.selectionClick();
+ _answer(view, key);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static final _optionLine = RegExp(r'^\s*(?:[❯›>]\s*)?(\d{1,2})[.)]\s');
+
+ /// Presses an answer: its digit, and Return only where the dialog asks for one (Codex's
+ /// `request_user_input`) — a chosen Return, never a blind one.
+ void _answer(QuestionPaneView view, QuestionKey key) {
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ if (session == null) return;
+ session.terminal.textInput(key.number);
+ if (view.enterSubmits) session.terminal.keyInput(TerminalKey.enter);
+ }
+
+ /// Where a voice take goes: to the agent's prompt — or, while the agent's question is open, to
+ /// that question, as its answer or not at all. Nothing is echoed when it lands: the words appear
+ /// in the prompt, and a tap is felt. Only what went wrong is said (see [_flash]).
+ Future<bool> _deliverVoice(String text) async {
+ final session = await _sessionForInput();
+ if (session == null) return false;
+ if (_questionWatcher?.view != null) return _answerByVoice(session, text);
+ final sent = 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;
+ }
+
+ /// The pane's session, able to take input — taken back first when another client took the
+ /// terminal (the desktop, on a click there) while the take was being spoken. Speaking to a
+ /// harness is as plain a claim on it as a tap or a scroll. Null when it cannot be had in 6s.
+ Future<TerminalSession?> _sessionForInput() async {
+ TerminalSession? current() =>
+ widget.notifier.paneOfAgent(widget.machineId, widget.agentId)?.session;
+ if (current() case final session? when session.acceptsInput) return session;
+ appLog.info('voice', 'terminal not ours at send — taking it back');
+ await _takeControl();
+ for (var waited = 0; waited < 60 && mounted; waited++) {
+ if (current() case final session? when session.acceptsInput) {
+ return session;
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ appLog.warn('voice', 'terminal not back in 6s — take kept');
+ return null;
+ }
+
+ /// A voice take while the agent's question is open: it answers the question or it is not sent.
+ Future<bool> _answerByVoice(TerminalSession session, String text) async {
+ final view = _questionWatcher?.view;
+ if (view == null) return session.sendComposerText(text);
+ if (!view.answerable || view.multi) {
+ _flash('✗ answer on screen', error: true);
+ return false;
+ }
+ final match = matchSpokenAnswer(text, view);
+ if (match == null) {
+ _flash('✗ no match — tap an answer', error: true);
+ return false;
+ }
+ final key = questionKeys(view).firstWhere((k) => k.number == match.number);
+ _answer(view, key);
+ // "no, use dist/ instead": the rest goes to the agent once its question has closed.
+ if (match.rest case final rest?) {
+ Timer(const Duration(milliseconds: 900), () {
+ if (!mounted || _questionWatcher?.view != null) return;
+ unawaited(session.sendComposerText(rest));
+ });
+ }
+ return true;
+ }
+
+ /// Whether the agent on screen is working — the mic wears its ring, and the menu offers Interrupt.
+ bool get _agentWorking =>
+ visibleAgents(agentIndex(widget.notifier))
+ .where(
+ (entry) =>
+ entry.machineId == widget.machineId &&
+ entry.agent.id == widget.agentId,
+ )
+ .firstOrNull
+ ?.isWorking ??
+ false;
+
+ /// A window name the way tmux shortens one: the first dozen characters.
+ static String _windowName(String name) =>
+ name.length <= 12 ? name : name.substring(0, 12);
+
+ /// Where the reader is while scrolled up in the history — see [_CopyModePosition].
+ final _scrollback = ValueNotifier<({int above, int total})?>(null);
+
+ /// Bumped by the position's tap to take the terminal back to the end.
+ int _jumpToEnd = 0;
+
+ /// How far left a drag has gone, for the swipe that opens a new agent.
+ double _swipedLeft = 0;
+
+ /// Whether the drag under way is pulling Find in — it then drives the slide.
+ bool _swipingFind = false;
+
+ /// A sideways drag this far left opens a new agent on letting go.
+ static const double _newAgentReach = 64;
+
+ /// A sideways fling at least this fast counts whatever distance it covered.
+ static const double _swipeFlick = 300;
+
+ void _onSwipeStart(DragStartDetails _) {
+ _swipedLeft = 0;
+ _swipingFind = false;
+ }
+
+ /// A drag's first move right pulls Find in, and from then on Find follows the finger; a drag
+ /// that starts left is counted toward a new agent instead.
+ void _onSwipeUpdate(DragUpdateDetails details) {
+ final dx = details.primaryDelta ?? 0;
+ if (!_swipingFind) {
+ if (_searching) return;
+ if (dx <= 0 || _swipedLeft > 0) {
+ _swipedLeft -= dx;
+ return;
+ }
+ _openSearch(animate: false);
+ _swipingFind = true;
+ }
+ final width = TerminalSearchOverlay.drawerWidth(
+ MediaQuery.sizeOf(context).width,
+ );
+ _searchOpen.value += dx / width;
+ }
+
+ /// Let go: Find stays if it was flung or is a third of the way out, and goes back otherwise. A
+ /// third, not half: Find is the whole screen wide, and half of it is a long reach for a thumb.
+ /// A drag left far enough, or flung, opens a new agent.
+ void _onSwipeEnd(DragEndDetails details) {
+ final velocity = details.primaryVelocity ?? 0;
+ if (_swipingFind) {
+ _swipingFind = false;
+ if (velocity >= _swipeFlick ||
+ (velocity > -_swipeFlick && _searchOpen.value > 0.3)) {
+ _searchOpen.forward();
+ } else {
+ _closeSearch();
+ }
+ return;
+ }
+ if (_swipedLeft >= _newAgentReach || velocity <= -_swipeFlick) {
+ unawaited(_newAgentHere());
+ }
+ }
+
+ void _onSwipeCancel() {
+ if (!_swipingFind) return;
+ _swipingFind = false;
+ _closeSearch();
+ }
+
+ /// A new agent, on the machine of the one on screen — the form slides in from the right, the way
+ /// a swipe left asks for.
///
- /// Awaited: the list is backed out of as often as it is tapped through, and
- /// this page gets no rebuild when it lands back on top.
- Future<void> _openAgentList() async {
- await Navigator.of(context)
- .push(phoneRoute((_) => AgentsListPage(notifier: widget.notifier)));
+ /// Rebuilt on the way back, as after every page pushed over this one: its chrome reads whether it
+ /// is the top route.
+ Future<void> _newAgentHere() async {
+ dismissKeyboardForSwipe();
+ await openNewAgent(
+ context,
+ widget.notifier,
+ widget.machineId,
+ voice: widget.voice,
+ );
if (mounted) setState(() {});
}
@@ -792,7 +1183,7 @@ class _TerminalPageState extends State<TerminalPage>
/// yet.** The sheet's field raises one the moment it is tapped, and by then
/// the terminal must already be ignoring it — see [_heldForSearch] for what
/// it does with that keyboard otherwise.
- void _openSearch() {
+ void _openSearch({bool animate = true}) {
if (_searching) return;
_keyboardBeforeSearch = _keyboardIsUp;
_keyboardUpAtSearch = _keyboardUp;
@@ -812,7 +1203,7 @@ class _TerminalPageState extends State<TerminalPage>
// typed into the shell.
_keyboardRequested = false;
});
- _searchOpen.forward();
+ if (animate) _searchOpen.forward();
}
/// Sends the sheet back down, and takes it down once it is gone.
@@ -822,7 +1213,11 @@ class _TerminalPageState extends State<TerminalPage>
/// all arrive while the reverse is already running — a second `reverse()`
/// restarts it from wherever it had got to, and the sheet visibly bounces.
void _closeSearch() {
- if (!_searching || _searchOpen.status == AnimationStatus.reverse) return;
+ if (!_searching ||
+ (_searchOpen.isAnimating &&
+ _searchOpen.status == AnimationStatus.reverse)) {
+ return;
+ }
// ⚠️ **The keyboard up now is the SEARCH field's, not the terminal's.** Its
// inset set [_keyboardIsUp], and left standing, the terminal read that as
// its own the moment search came down — closing the sheet, Back or opening
@@ -1294,7 +1689,6 @@ class _TerminalPageState extends State<TerminalPage>
!agentGone &&
(_reclaiming == _Reclaim.reconnect ||
(machine != null && phoneMachineRedialling(machine)));
- final reclaim = phoneReclaimAction(session, reconnecting: reconnecting);
// Read-only either way — the terminal was never this pane's (a watcher) or was taken from it.
// `_AgentGone` owns the page when the agent itself is missing, so this stays out of its way.
final blocked =
@@ -1316,11 +1710,6 @@ class _TerminalPageState extends State<TerminalPage>
session,
(id) => widget.notifier.stateOf(id)?.machine.displayName,
);
- final takeoverNotice = phoneTakeoverNotice(session, takerName);
- final holderName = phoneHolderName(
- session,
- (id) => widget.notifier.stateOf(id)?.machine.displayName,
- );
final headerStatus = phoneSessionSummary(
session,
takerName: takerName,
@@ -1338,6 +1727,9 @@ class _TerminalPageState extends State<TerminalPage>
// that frame goes out device-and-loopback only — a phone attached over the
// relay never receives it. See [QuestionPaneWatcher].
_syncQuestionWatcher(agent?.engine, session);
+ // 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;
// Read once: the body reserves it, and search subtracts what the body
// already took. See [_navigationBar].
final navigationBar = _navigationBar;
@@ -1430,179 +1822,230 @@ class _TerminalPageState extends State<TerminalPage>
// — not over the whole page. Stacked any higher it
// would hang over the key bar while the keyboard is
// up, which is the one row the thumb is working.
- child: Stack(
- children: [
- Positioned.fill(
- // ⚠️ The chrome is driven from OUT HERE, not
- // from inside the panel. xterm's own
- // [Scrollable] is several widgets down and is
- // remounted whenever the agent changes;
- // listening for its notifications as they
- // bubble past is what survives that, and costs
- // the panel no knowledge of the page's chrome.
- child:
- NotificationListener<ScrollNotification>(
- onNotification: _chrome.onNotification,
- child: agentGone
- ? _AgentGone(
- name: _cachedAgentName,
- onPickAnother:
- _pickAnotherAgent,
- )
- : pane == null || session == null
- ? _Attaching(key: _skeletonKey)
- : TerminalPanel(
- key: ValueKey(pane.id),
- notifier: widget.notifier,
- session: session,
- // Only the page on screen takes the keyboard — see
- // [TerminalPage.isActive]. `visible` is the same answer for the
- // panel's other half: a page parked beside this one releases
- // focus, stops rendering and stops resizing its remote shell.
- //
- // Whether it also HOLDS one that is already
- // up is a separate question, and the pager asks
- // it on every swipe — see [_shouldFocus].
- focused: _shouldFocus,
- // Asks again when `focused` did
- // not move — coming back from
- // another app. See
- // [didChangeAppLifecycleState].
- focusRequest: _focusRequest,
- visible: widget.isActive,
- // Hold the remote resize while the keyboard
- // slides. Separate from `visible` because this
- // must NOT release focus — the animation being
- // waited on is the one that focus started.
- //
- // The keyboard is the only thing left that
- // moves this pane's height: the header slides
- // OVER the terminal rather than out of its
- // column — see [_SlideAway].
- //
- // ⚠️ Held for as long as search is open, too:
- // its keyboard is typing a query over a faded
- // terminal, and resizing the agent's shell for
- // it redrew the whole TUI on the way in and
- // again on the way out.
- settling:
- _keyboardSettling ||
- _heldForSearch,
- // ⚠️ The tap is taken in the panel, not by a
- // `Listener` over it. xterm's own `_onTapDown`
- // calls `requestKeyboard()`, so anything that
- // merely ALSO reacted to the tap would raise
- // the keyboard before the words said were typed
- // into the prompt — and a re-armed claim on top
- // of it was measured asking Android twice per
- // tap, which answers a show mid-animation by
- // cancelling and restarting it. Null while the
- // keyboard is up or coming, so the tap is
- // xterm's and the keyboard stays.
- //
- // ⚠️ A tap on a pane that cannot take input
- // asks for the TERMINAL, not the keyboard:
- // raising one over a read-only pane offers
- // a prompt that silently swallows every
- // letter. The band above says why, so the
- // tap takes the person to its button. See
- // [_ControlBanner].
- onInputTap: blocked
- ? () => unawaited(
- _takeControl(),
- )
- : _shouldFocus
- ? null
- : () => unawaited(
- _raiseKeyboard(session),
- ),
- showHeader: false,
- // No composer, and so no grip above it: the
- // page hands the pane its full height and the
- // software keyboard drives the terminal
- // directly. The mic's send is what kept the
- // composer's batched turn.
- ),
- ),
- ),
- // ⚠️ **The skeleton is laid OVER the live panel, not
- // swapped in for it, and that is not a stylistic
- // choice.** [TerminalPanel.initState] calls
- // `session.attachViewport`, which is how the machine
- // learns how many rows and columns to draw; a page
- // that showed a skeleton INSTEAD would leave the
- // session with no viewport, and the first keyframe
- // would arrive sized for nothing.
- //
- // So the panel mounts, measures and resizes as always,
- // and this covers the empty emulator buffer it paints
- // meanwhile. `session == null` upstream keeps its own
- // branch for the frames before a session exists at all.
- //
- // ⚠️ **This is also the bug that made the skeleton
- // invisible.** The only gate used to be `session ==
- // null`, and `selectAgent` creates the pane and the
- // session in one frame — so the branch above was
- // essentially never taken, and what a person actually
- // waited in front of was a mounted terminal with an
- // empty buffer: a black rectangle, for as long as the
- // keyframe took.
- //
- // ⚠️ **A page on a terminal another app holds still
- // renders.** It attaches as a WATCHER — live output,
- // no typing (see [TerminalSession.watching]) — so the
- // keyframe this covers arrives exactly as it does for
- // any other page, and nothing here needs to know the
- // difference. The header says who has it and offers
- // "Take control"; the body is the terminal.
- if (session != null &&
- !session.hasRenderedFrame)
+ //
+ // ⚠️ **The two sideways swipes live here, on the
+ // terminal and nowhere else** — Snapchat's layout:
+ // right pulls Find in from the left edge, left opens
+ // a new agent. The terminal scrolls vertically and
+ // selects only with a mouse, so the horizontal axis
+ // is free; the key bar below scrolls its hints
+ // sideways and keeps that for itself.
+ child: GestureDetector(
+ // Translucent: the terminal may sit lower than its box (see
+ // [_AnchoredTerminal]), and a swipe on the rows above it counts.
+ behavior: HitTestBehavior.translucent,
+ onHorizontalDragStart: widget.sideSwipes
+ ? _onSwipeStart
+ : null,
+ onHorizontalDragUpdate: widget.sideSwipes
+ ? _onSwipeUpdate
+ : null,
+ onHorizontalDragEnd: widget.sideSwipes
+ ? _onSwipeEnd
+ : null,
+ onHorizontalDragCancel: widget.sideSwipes
+ ? _onSwipeCancel
+ : null,
+ child: Stack(
+ children: [
Positioned.fill(
- child: _Attaching(key: _skeletonKey),
- ),
- // The mic and Search, floating in the
- // terminal's bottom-right corner — see
- // [TerminalActionColumn].
- //
- // ⚠️ Hidden while this page owns the keyboard.
- // Typing is the other way of saying what the mic
- // says, the key bar is already under the thumb, and
- // a column floating over the prompt being typed into
- // would be in the way of both.
- // ⚠️ **Search stays while the keyboard is up; the
- // mic goes.** Typing says what the mic says, so
- // with a keyboard on screen the two are one
- // errand and the key bar is already under the
- // thumb. Search is not: another harness, another
- // machine, and nothing on the key bar reaches
- // them — so hiding the column whole meant
- // putting the keyboard away first just to look
- // something up.
- //
- // It moves to the TOP of the pane rather than
- // staying put. Down here it floats over the
- // prompt being typed into, which is exactly
- // what the keyboard is for; up there it covers
- // the oldest rows on screen.
- Positioned(
- right: TerminalActionColumn.inset,
- top: _ownsInput
- ? TerminalActionColumn.topInset
- : null,
- bottom: _ownsInput
- ? null
- : TerminalActionColumn.bottomInset,
- child: TerminalActionColumn(
- voice: widget.voice,
- session: session,
- onSearch: _openSearch,
- searchOnly: _ownsInput,
- unread: widget.notifier.agentNotices.unread,
+ top: 0,
+ // The agent's last line sits at the foot while the
+ // output is followed — see [_AnchoredTerminal]. A move,
+ // not a resize: a resize would redraw the agent's whole
+ // TUI, and reading back uses every row.
+ child: ClipRect(
+ child: _AnchoredTerminal(
+ terminal: session?.terminal,
+ enabled: !_keyBarUp && !_ownsInput,
+ reading: _scrollback,
+ clearBottom: _clearAboveMic,
+ // ⚠️ The chrome is driven from OUT HERE, not
+ // from inside the panel. xterm's own
+ // [Scrollable] is several widgets down and is
+ // remounted whenever the agent changes;
+ // listening for its notifications as they
+ // bubble past is what survives that, and costs
+ // the panel no knowledge of the page's chrome.
+ child:
+ NotificationListener<
+ ScrollNotification
+ >(
+ // A scroll on a terminal held elsewhere takes it,
+ // as a tap does: no button to find first.
+ onNotification: (notification) {
+ if (blocked &&
+ notification
+ is ScrollStartNotification &&
+ notification.dragDetails !=
+ null) {
+ unawaited(_takeControl());
+ }
+ return _chrome.onNotification(
+ notification,
+ );
+ },
+ child: agentGone
+ ? _AgentGone(
+ name: _cachedAgentName,
+ onPickAnother:
+ _pickAnotherAgent,
+ )
+ : pane == null ||
+ session == null
+ ? _Attaching(
+ key: _skeletonKey,
+ )
+ : TerminalPanel(
+ key: ValueKey(pane.id),
+ notifier: widget.notifier,
+ session: session,
+ // Only the page on screen takes the keyboard — see
+ // [TerminalPage.isActive]. `visible` is the same answer for the
+ // panel's other half: a page parked beside this one releases
+ // focus, stops rendering and stops resizing its remote shell.
+ //
+ // Whether it also HOLDS one that is already
+ // up is a separate question, and the pager asks
+ // it on every swipe — see [_shouldFocus].
+ focused: _shouldFocus,
+ // Asks again when `focused` did
+ // not move — coming back from
+ // another app. See
+ // [didChangeAppLifecycleState].
+ focusRequest:
+ _focusRequest,
+ visible: widget.isActive,
+ // Hold the remote resize while the keyboard
+ // slides. Separate from `visible` because this
+ // must NOT release focus — the animation being
+ // waited on is the one that focus started.
+ //
+ // The keyboard is the only thing left that
+ // moves this pane's height: the header slides
+ // OVER the terminal rather than out of its
+ // column — see [_SlideAway].
+ //
+ // ⚠️ Held for as long as search is open, too:
+ // its keyboard is typing a query over a faded
+ // terminal, and resizing the agent's shell for
+ // it redrew the whole TUI on the way in and
+ // again on the way out.
+ settling:
+ _keyboardSettling ||
+ _heldForSearch,
+ // ⚠️ The tap is taken in the panel, not by a
+ // `Listener` over it. xterm's own `_onTapDown`
+ // calls `requestKeyboard()`, so anything that
+ // merely ALSO reacted to the tap would raise
+ // the keyboard before the words said were typed
+ // into the prompt — and a re-armed claim on top
+ // of it was measured asking Android twice per
+ // tap, which answers a show mid-animation by
+ // cancelling and restarting it. Null while the
+ // keyboard is up or coming, so the tap is
+ // xterm's and the keyboard stays.
+ //
+ // ⚠️ A tap on a pane that cannot take input
+ // takes the TERMINAL first, not the
+ // keyboard: raising one over a read-only
+ // pane offers a prompt that silently
+ // swallows every letter.
+ onInputTap: blocked
+ ? () => unawaited(
+ _takeControl(),
+ )
+ : _shouldFocus
+ ? null
+ : () => unawaited(
+ _raiseKeyboard(
+ session,
+ ),
+ ),
+ onLineTap: _onLineTap,
+ showHeader: false,
+ // tmux's copy-mode position while
+ // reading back — see [_CopyModePosition].
+ scrollback: _scrollback,
+ jumpToEndRequest:
+ _jumpToEnd,
+ // No composer, and so no grip above it: the
+ // page hands the pane its full height and the
+ // software keyboard drives the terminal
+ // directly. The mic's send is what kept the
+ // composer's batched turn.
+ ),
+ ),
+ ),
+ ),
),
- ),
- ],
+ // ⚠️ **The skeleton is laid OVER the live panel, not
+ // swapped in for it, and that is not a stylistic
+ // choice.** [TerminalPanel.initState] calls
+ // `session.attachViewport`, which is how the machine
+ // learns how many rows and columns to draw; a page
+ // that showed a skeleton INSTEAD would leave the
+ // session with no viewport, and the first keyframe
+ // would arrive sized for nothing.
+ //
+ // So the panel mounts, measures and resizes as always,
+ // and this covers the empty emulator buffer it paints
+ // meanwhile. `session == null` upstream keeps its own
+ // branch for the frames before a session exists at all.
+ //
+ // ⚠️ **This is also the bug that made the skeleton
+ // invisible.** The only gate used to be `session ==
+ // null`, and `selectAgent` creates the pane and the
+ // session in one frame — so the branch above was
+ // essentially never taken, and what a person actually
+ // waited in front of was a mounted terminal with an
+ // empty buffer: a black rectangle, for as long as the
+ // keyframe took.
+ //
+ // ⚠️ **A page on a terminal another app holds still
+ // renders.** It attaches as a WATCHER — live output,
+ // no typing (see [TerminalSession.watching]) — so the
+ // keyframe this covers arrives exactly as it does for
+ // any other page, and nothing here needs to know the
+ // difference. The header says who has it and offers
+ // "Take control"; the body is the terminal.
+ if (session != null && !session.hasScreen)
+ Positioned.fill(
+ child: _Attaching(key: _skeletonKey),
+ ),
+ // The mic and Search, floating in the
+ // terminal's bottom-right corner — see
+ // [TerminalActionColumn].
+ //
+ // ⚠️ Hidden while this page owns the keyboard.
+ // Typing is the other way of saying what the mic
+ // says, the key bar is already under the thumb, and
+ // a column floating over the prompt being typed into
+ // would be in the way of both.
+ // ⚠️ **Search stays while the keyboard is up; the
+ // mic goes.** Typing says what the mic says, so
+ // with a keyboard on screen the two are one
+ // errand and the key bar is already under the
+ // thumb. Search is not: another harness, another
+ // machine, and nothing on the key bar reaches
+ // them — so hiding the column whole meant
+ // putting the keyboard away first just to look
+ // something up.
+ //
+ // It moves to the TOP of the pane rather than
+ // staying put. Down here it floats over the
+ // prompt being typed into, which is exactly
+ // what the keyboard is for; up there it covers
+ // the oldest rows on screen.
+ ],
+ ),
),
),
+ // Nothing at the foot: the terminal is the screen. What vim
+ // would say on its last line — a take, a message — is said on
+ // the line above the mic. See [_statusLine].
+ // ⚠️ No strip kept for the home indicator: the terminal runs
+ // under it, to the glass, as a page does in Safari.
// The bottom of this page IS just above the keyboard:
// `PhoneShell`'s Scaffold has already resized for it —
// the same resize that empties this page's MediaQuery
@@ -1637,127 +2080,187 @@ class _TerminalPageState extends State<TerminalPage>
],
),
),
- // The header, laid OVER the terminal rather than above it in the
- // column.
- //
- // ⚠️ **Over, not beside, and that is what keeps scrolling smooth.**
- // It used to shrink out of the column and hand its height to the
- // terminal. Every fold then changed the terminal's row count: a
- // `terminal_resize` and a real SIGWINCH on the far machine, a
- // keyframe back carrying up to 500 lines of history to re-parse on
- // this thread, and the agent's whole screen redrawn — once as the
- // header left, once as it came back, on every change of scroll
- // direction. The renderer was held frozen for each slide on top of
- // that, so a fling stopped dead for a third of a second.
- //
- // Laid over, the terminal keeps one height whatever the header
- // does. The rows under it are the oldest on the screen, and the
- // first push of a scroll is what slides it away from them.
- //
- // Nothing stands in for it while it is gone: `⋯` comes back with
- // the header on the first scroll the other way.
+ // The title — the agent, then machine:folder and branch — over the
+ // terminal's top rows. It slides away while the history is read back
+ // and returns at the end of the output. See [TerminalTitle].
Positioned(
top: 0,
left: 0,
right: 0,
child: _SlideAway(
progress: _chrome.header,
- // Opaque: the terminal is underneath now, and the row has to
- // read as the same bar it was when the two were stacked.
- child: ColoredBox(
- color: AppPalette.windowBg,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- TerminalHeader(
- agent: agent,
- status: headerStatus,
- machineName: machine?.machine.displayName,
- trailing: [
- // Read-only is a state to get OUT of, so its way
- // out is a labelled button in the header rather
- // than a line in the actions sheet: the sheet is
- // where you go having decided to do something,
- // and this is the thing telling you that typing
- // will go nowhere until you do.
- // ⚠️ **Not while the band is up.** The band below
- // carries the same words and the same button, a
- // finger's width under this one, and two "Take
- // control"s stacked read as two different offers.
- // The band is the better of the two — it says WHY
- // typing stopped, and by whom — so this one gives
- // way to it.
- //
- // Kept for the states the band does not cover:
- // "Reconnect", for a stream that died with nobody
- // else involved. See [_ControlBanner]. Gone while
- // that stream is already coming back — see
- // `reconnecting` above.
- if (reclaim != null &&
- !blocked &&
- _reclaiming == null)
- _ReclaimButton(
- action: reclaim,
- // The same call the band's button makes — see
- // [_takeControl].
- onPressed: () =>
- unawaited(_takeControl()),
- ),
- // ⚠️ **No tabs mark here.** The account's tabs
- // are the first thing the floating Search button
- // opens, above the thumb — see
- // [TerminalSearchOverlay] — and a mark up here
- // for the same panel was a second door to it.
- // Null while the agent is not loaded: there is
- // nothing to act on yet, and a menu of actions
- // that all fail is worse than no menu.
- if (agent != null)
- TerminalHeaderAction(
- // Stood up, not laid flat: three dots in a
- // column is the narrower mark AND the one a
- // phone means by "more actions", so it reads
- // as a menu rather than as a truncation.
- icon: LucideIcons.ellipsisVertical300,
- size: 21,
- tooltip: 'Harness actions',
- // Last in the row, so its padding stops at
- // the header's own right inset.
- last: true,
- onPressed: () => _showActions(
- machineName:
- machine?.machine.displayName ?? '',
- agent: agent,
- status: headerStatus,
- ),
- ),
- ],
- ),
- // The hairline, carrying a sweep while the header
- // reads as a wait — Attaching, Resyncing,
- // Reconnecting. See [TerminalHeaderRule].
- TerminalHeaderRule(
- busy: headerStatus.tone == PhoneTone.busy,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TerminalTitle(
+ name:
+ agent?.displayName ?? _cachedAgentName ?? '',
+ place: _placeOf(agent, machine),
+ branch: agent?.project?.branch,
+ // In the sample the guide line says it, once is enough.
+ asking: SampleMode.maybeOf(context) != null
+ ? null
+ : _askingElsewhere(),
+ onHold: _openLastHarness,
+ onFind: _openSearch,
+ onTap: () {
+ if (agent == null) return;
+ _showActions(
+ machineName:
+ machine?.machine.displayName ?? '',
+ agent: agent,
+ status: headerStatus,
+ );
+ },
+ ),
+ // ⚠️ No "take control" band: a tap or a scroll on a terminal held
+ // elsewhere takes it — see `onInputTap` and [_onScrollTakeControl].
+ ],
+ ),
+ ),
+ ),
+ // tmux's copy-mode position, top right, while reading back
+ // through the history: `[42/1380]`. One tap is back at the end.
+ Positioned(
+ // The pane's own row 0, flush right, as tmux draws it.
+ top: 0,
+ right: 0,
+ child: ValueListenableBuilder<({int above, int total})?>(
+ valueListenable: _scrollback,
+ builder: (context, position, _) =>
+ position == null || _ownsInput
+ ? const SizedBox.shrink()
+ : _CopyModePosition(
+ above: position.above,
+ total: position.total,
+ onTap: () {
+ _scrollback.value = null;
+ setState(() => _jumpToEnd++);
+ },
),
- // ⚠️ Inside the header's own slide, not under it: the two are one bar as far
- // as a scroll is concerned, and a band left behind while the header left
- // would sit on the output with nothing above it.
- //
- // Up for a take in flight, not for a reconnect: that one is the header's
- // own wait, and a band over it said "Taking control…" of a stream nobody
- // else held. See [_reclaiming].
- if (blocked || _reclaiming == _Reclaim.control)
- _ControlBanner(
- watching: session?.watching ?? false,
- busy: !blocked,
- takeoverNotice: takeoverNotice,
- holderName: holderName,
- onTakeControl: _takeControl,
+ ),
+ ),
+ // The line above the mic: what is going on, in a few words — see [_statusLine].
+ if (!_ownsInput)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: _statusBottom - _StatusLine.below,
+ child: IgnorePointer(
+ child: ListenableBuilder(
+ listenable: Listenable.merge([
+ widget.voice,
+ _barMessage,
+ ]),
+ builder: (context, _) =>
+ _statusLine() ?? const SizedBox.shrink(),
+ ),
+ ),
+ ),
+ // How loud the take is: a glow behind the mic that swells with the voice.
+ if (!_ownsInput)
+ ListenableBuilder(
+ listenable: widget.voice,
+ builder: (context, _) =>
+ widget.voice.status == VoiceInputStatus.listening
+ ? Positioned(
+ left: 0,
+ right: 0,
+ bottom: _micCenter - VoiceLevelHalo.extent / 2,
+ child: IgnorePointer(
+ child: Center(
+ child: VoiceLevelHalo(voice: widget.voice),
+ ),
),
- ],
+ )
+ : const Positioned(
+ left: 0,
+ bottom: 0,
+ child: SizedBox.shrink(),
+ ),
+ ),
+ // The mic: Siri's orb, low at the foot and centred, floating
+ // over the terminal — which stays full screen under it, the
+ // way the home screen stays whole under Siri. Laid over the
+ // whole page so its capsule, rising as it talks, still takes
+ // taps.
+ if (!_ownsInput)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: _micCenter - VoiceMicButton.extent / 2,
+ // Centred at its own size — the mic's slot must not
+ // stretch to the page's width.
+ child: Align(
+ alignment: Alignment.bottomCenter,
+ heightFactor: 1,
+ // Always there, reading or not: what is read is what gets answered.
+ child: TerminalActionColumn(
+ voice: widget.voice,
+ session: session,
+ onSearch: _openSearch,
+ unread: widget.notifier.agentNotices.unread,
+ working: _agentWorking,
),
),
),
- ),
+ // An agent's question: its first and last answers, `1 yes` and `3 no`, as keys
+ // either side of the mic — which never moves. The rest are a tap on their line.
+ if (_answersBesideMic case (final first, final last)?) ...[
+ Positioned(
+ right:
+ MediaQuery.sizeOf(context).width / 2 +
+ VoiceMicButton.extent / 2 +
+ 20 -
+ _Keycap.slop,
+ bottom: _micCenter - _Keycap.touch / 2,
+ child: _AnswerKeycap(
+ answer: first,
+ onTap: () => _answer(_questionWatcher!.view!, first),
+ ),
+ ),
+ if (last != null)
+ Positioned(
+ left:
+ MediaQuery.sizeOf(context).width / 2 +
+ VoiceMicButton.extent / 2 +
+ 20 -
+ _Keycap.slop,
+ bottom: _micCenter - _Keycap.touch / 2,
+ child: _AnswerKeycap(
+ answer: last,
+ onTap: () => _answer(_questionWatcher!.view!, last),
+ ),
+ ),
+ ],
+ // The sample, done: what it was, and the way to the real thing. Once.
+ if (_showEndCard)
+ Positioned.fill(
+ child: _SampleEndCard(
+ started: agent?.displayName ?? 'your harness',
+ onSetUp: () =>
+ SampleMode.maybeOf(context)
+ ?.leave(SampleExit.setUp),
+ onKeepPlaying: () =>
+ setState(() => _showEndCard = false),
+ ),
+ ),
+ // The first time a terminal is up: what the swipes and the mic do. Once.
+ // Not in the sample: its guide line teaches the same by having them done, and the
+ // hints stay unseen for the real first terminal.
+ if (session != null &&
+ widget.isActive &&
+ !_keyBarUp &&
+ SampleMode.maybeOf(context) == null)
+ Positioned.fill(
+ child: FocusHints(
+ onDone: () => unawaited(
+ widget.notifier.agentNotices.system
+ .requestPermission(),
+ ),
+ micBottom: _micCenter,
+ ),
+ ),
],
),
),
@@ -1782,6 +2285,7 @@ class _TerminalPageState extends State<TerminalPage>
animation: _searchCurve,
bottomInset: _windowBottomInset,
onClose: _closeSearch,
+ voice: widget.voice,
),
),
],
@@ -1844,7 +2348,12 @@ class _TerminalPageState extends State<TerminalPage>
final agentName = agent.displayName;
showPhoneSheet(
context,
- title: '$agentName · $machineName',
+ // Where it runs, written as everywhere else: `hn` over `M2:autonomous-harness ⑂ main`.
+ title: [
+ '$agentName · $machineName',
+ if (agent.project?.label case final folder?) ':$folder',
+ ].join(),
+ titleBranch: agent.project?.shownBranch,
// The agent, then where it runs — the machine, then the folder with its parent beside the
// branch — each behind its icon. The header has no room for the path.
titleParts: [agentName],
@@ -1877,31 +2386,17 @@ class _TerminalPageState extends State<TerminalPage>
// chevron is what tells a door from an action.
sections: [
PhoneSheetSection(actions: _agentActions(agent)),
+ // Harnesses and Machines went: Find (a swipe right) is every agent on every computer, and
+ // the computers are a row in Settings.
PhoneSheetSection(
- caption: 'App',
actions: [
- // Every agent on the account, not just this machine's: the sheet is opened from inside
- // one agent, and the thing somebody wants from here is another agent — which is as
- // often on the other laptop as on this one.
- //
- // [AgentsListPage] draws them, with the magnifier in its header for when the list is
- // longer than a screenful.
- PhoneSheetAction(
- icon: LucideIcons.squareTerminal300,
- label: 'Harnesses',
- chevron: true,
- onTap: () => unawaited(_openAgentList()),
- ),
- PhoneSheetAction(
- icon: LucideIcons.laptopMinimal300,
- label: 'Machines',
- chevron: true,
- onTap: () => Navigator.of(context).push(
- phoneRoute(
- (_) => MachinesTab(notifier: widget.notifier, large: false),
- ),
+ // In the sample: the way back out, where a person looks for "what else can I do".
+ if (SampleMode.maybeOf(context) case final sample?)
+ PhoneSheetAction(
+ icon: LucideIcons.logOut300,
+ label: 'Leave the sample',
+ onTap: () => sample.leave(),
),
- ),
PhoneSheetAction(
icon: LucideIcons.settings300,
label: 'Settings',
@@ -1920,7 +2415,47 @@ class _TerminalPageState extends State<TerminalPage>
}
/// What acts on this agent and can be taken back — the first card of its sheet.
+ /// Pastes the phone's clipboard into the terminal, the way a desktop's ⌘V does — the pane's raw
+ /// paste where the computer takes one, bracketed paste where it does not.
+ Future<void> _pasteClipboard() async {
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ if (session == null || !session.acceptsInput) return;
+ final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
+ if (!mounted) return;
+ if (text == null || text.isEmpty) {
+ _flash('the clipboard has no text', error: true);
+ return;
+ }
+ final machine = widget.notifier.stateOf(widget.machineId);
+ if (machine != null && machine.terminalPasteRawAvailable) {
+ await session.pasteText(text);
+ } else {
+ session.terminal.paste(text);
+ }
+ }
+
List<PhoneSheetAction> _agentActions(Agent agent) => [
+ PhoneSheetAction(
+ icon: LucideIcons.clipboardPaste300,
+ label: 'Paste from clipboard',
+ onTap: () => unawaited(_pasteClipboard()),
+ ),
+ // Stop what it is doing — Esc, as in the terminal — only while it is doing something. First,
+ // because when it is wanted it is wanted now.
+ if (_agentWorking)
+ PhoneSheetAction(
+ icon: LucideIcons.octagonPause300,
+ label: 'Interrupt',
+ value: 'esc',
+ onTap: () {
+ final session = widget.notifier
+ .paneOfAgent(widget.machineId, widget.agentId)
+ ?.session;
+ session?.terminal.keyInput(TerminalKey.escape);
+ },
+ ),
// Where this agent runs, above the actions that act ON it: the desktop
// keeps it in the pane header, and this sheet is the phone's pane header.
//
@@ -1983,8 +2518,10 @@ class _TerminalPageState extends State<TerminalPage>
/// share the route.
PhoneSheetAction _stopAction(Agent agent) => PhoneSheetAction(
icon: LucideIcons.trash2300,
- label: 'Stop Harness…',
+ // The least used thing here: small and faint at the foot, not a red row (it still confirms).
+ label: 'Stop this harness…',
destructive: true,
+ quiet: true,
onTap: () => unawaited(
confirmDeleteAgent(
context,
@@ -2044,42 +2581,6 @@ class _TerminalPageState extends State<TerminalPage>
}
}
-/// The header's way back into a session this device is not driving.
-///
-/// Re-selecting the agent is what reclaims it — the same call the desktop tile's
-/// status chip makes, so one gesture means one thing on both.
-class _ReclaimButton extends StatelessWidget {
- const _ReclaimButton({required this.action, required this.onPressed});
-
- final PhoneSummary action;
- final VoidCallback onPressed;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final color = phoneToneColor(action.tone);
- return TextButton.icon(
- onPressed: onPressed,
- icon: Icon(
- action.tone == PhoneTone.attention
- ? LucideIcons.lock300
- : LucideIcons.refreshCw300,
- size: 15,
- ),
- label: Text(
- action.label,
- style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
- ),
- style: TextButton.styleFrom(
- foregroundColor: color,
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
- ),
- );
- }
-}
-
/// What the terminal shows when the agent it opened on is not there any more.
///
/// ⚠️ **This is the cost of opening from the cache, and the whole of it.** The
@@ -2147,142 +2648,6 @@ class _AgentGone extends StatelessWidget {
);
}
-/// The band over the output saying this pane cannot be typed into, and offering the way in.
-///
-/// ⚠️ **Over the output, not in the header.** The header's status word is 11pt in a corner beside
-/// the agent's name, and somebody mid-sentence never looks there — the keystrokes simply stop
-/// landing and nothing on screen says why. This sits where the eyes already are. The desktop puts
-/// the same band in the same place for the same reason (`widgets/terminal_panel.dart`); this is
-/// that band at phone width.
-///
-/// Covers both ways a pane goes read-only. A WATCHER never held the terminal — the page attached
-/// to an agent the desktop was already driving, output and all (see [TerminalSession.watching]) —
-/// while `takenOver` is a terminal this phone HAD and lost. One sentence each, because "another
-/// app has it, press this" is the part that matters either way; the lost one names the taker when
-/// the daemon said who.
-class _ControlBanner extends StatelessWidget {
- const _ControlBanner({
- required this.watching,
- required this.busy,
- required this.takeoverNotice,
- required this.holderName,
- required this.onTakeControl,
- });
-
- /// True where the terminal was never this pane's; false where it was taken away.
- final bool watching;
-
- /// The take is in flight — its `terminal_open` is out and this pane is waiting to hear.
- final bool busy;
-
- /// Who took it, as the one sentence [phoneTakeoverNotice] writes. Null for a watcher, which
- /// never lost a terminal, and while a take is in flight.
- final String? takeoverNotice;
-
- /// Who is driving the terminal a watcher is looking at, as [phoneHolderName] names it — the
- /// machine, as the desktop names a taker. Null when the daemon did not say.
- final String? holderName;
-
- final VoidCallback onTakeControl;
-
- String get _title {
- if (busy) return 'Taking control…';
- if (watching) return '${holderName ?? 'Another app'} is using this terminal';
- return takeoverNotice ?? 'Another app took control of this terminal';
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final ink = phoneToneColor(PhoneTone.attention);
- return Semantics(
- key: const ValueKey('phone-takeover-strip'),
- container: true,
- liveRegion: true,
- child: DecoratedBox(
- decoration: BoxDecoration(
- // Composited over the pane's own ground rather than laid on as a wash: the terminal
- // theme behind this band may be any colour, and a bare translucent fill would read
- // differently on each of them.
- color: Color.alphaBlend(
- ink.withValues(alpha: 0.12),
- AppPalette.windowBg,
- ),
- border: Border(
- bottom: BorderSide(color: ink.withValues(alpha: 0.55)),
- ),
- ),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(14, 10, 10, 10),
- child: Row(
- children: [
- if (busy)
- SizedBox(
- width: 15,
- height: 15,
- child: CircularProgressIndicator(strokeWidth: 2, color: ink),
- )
- else
- Icon(LucideIcons.lock300, size: 15, color: ink),
- const SizedBox(width: 10),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- _title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 12,
- fontWeight: FontWeight.w700,
- ),
- ),
- if (!busy) ...[
- const SizedBox(height: 2),
- Text(
- 'Typing is paused. Take control to type here.',
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppPalette.textSecondary,
- fontSize: 11,
- height: 1.3,
- ),
- ),
- ],
- ],
- ),
- ),
- if (!busy) ...[
- const SizedBox(width: 10),
- TextButton(
- onPressed: onTakeControl,
- style: TextButton.styleFrom(
- foregroundColor: ink,
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 8,
- ),
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- child: const Text(
- 'Take control',
- style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
- ),
- ),
- ],
- ],
- ),
- ),
- ),
- );
- }
-}
-
/// The terminal's body while its first keyframe is still crossing the network.
///
/// ⚠️ **A skeleton here, not a spinner, because the shape IS known** — that is
@@ -2850,52 +3215,6 @@ class _SkeletonTurn {
final double? meta;
}
-/// The header sliding up off the top of the page, fading as it goes.
-///
-/// ⚠️ **A translation, and it must stay one.** It used to shrink with
-/// [Align.heightFactor] so the terminal below could grow into the space — which
-/// resized the far machine's shell on every fold. The header is laid over the
-/// terminal now (see the page's build), so moving its paint is all a fold needs
-/// and the terminal's layout never hears about it.
-///
-/// ⚠️ **The same widgets at every value, 0 included.** Returning the bare child
-/// while it was fully shown swapped the widget type in that slot at the start
-/// and end of every fold, which unmounted the header and built it again.
-class _SlideAway extends StatelessWidget {
- const _SlideAway({required this.progress, required this.child});
-
- /// 0 fully shown, 1 fully gone.
- final Animation<double> progress;
-
- final Widget child;
-
- @override
- Widget build(BuildContext context) => AnimatedBuilder(
- animation: progress,
- // ⚠️ Built ONCE and passed through. The child is a whole header, and
- // rebuilding it on every frame of a scroll is work for nothing — what
- // changes is where it is painted, not anything in it.
- child: child,
- builder: (context, child) {
- final value = progress.value;
- return IgnorePointer(
- // Part-way out it is no longer the bar it looks like — the floating
- // buttons are taking over — and fully out it is off the page.
- ignoring: value > 0,
- child: FractionalTranslation(
- translation: Offset(0, -value),
- child: Opacity(
- // Spent by the two-thirds mark, which is where the floating buttons
- // are arriving. Anything still visible after that competes with them.
- opacity: (1 - value / 0.66).clamp(0.0, 1.0),
- child: child,
- ),
- ),
- );
- },
- );
-}
-
/// The longest agent name the header will print before it cuts.
///
/// An agent's name is usually a filename, and the header row has to hold three
@@ -2940,3 +3259,548 @@ String _clipTitle(String name) {
/// dead space either side and the three stay 24px each — under the 44 iOS asks
/// for. Fixing that belongs in the shared button, where every screen's header
/// would get it, not in a wrapper one page defines.
+
+/// tmux's copy-mode position — `[42/1380]` on tmux's yellow, top right — while the reader is up in
+/// the history: 42 lines above the end, of 1380. The view holds still as output arrives, and the
+/// first number counts it. One tap is back at the end, following the stream.
+class _CopyModePosition extends StatelessWidget {
+ const _CopyModePosition({
+ required this.above,
+ required this.total,
+ required this.onTap,
+ });
+
+ final int above;
+ final int total;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: '$above lines above the end. Back to the latest output',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ // A full touch target around a one-line tag.
+ padding: const EdgeInsets.all(8),
+ child: ColoredBox(
+ color: tty.yellow,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: TtyText('[$above/$total]', color: tty.theme.black),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Slides the title off the top as [progress] runs 0 → 1, fading it as it goes.
+class _SlideAway extends StatelessWidget {
+ const _SlideAway({required this.progress, required this.child});
+
+ /// 0 fully shown, 1 fully gone.
+ final Animation<double> progress;
+
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => AnimatedBuilder(
+ animation: progress,
+ // ⚠️ Built ONCE and passed through. What changes on a frame of a scroll is where the title is
+ // painted, not anything in it.
+ child: child,
+ builder: (context, child) {
+ final value = progress.value;
+ return IgnorePointer(
+ ignoring: value > 0,
+ child: FractionalTranslation(
+ translation: Offset(0, -value),
+ child: Opacity(
+ opacity: (1 - value / 0.66).clamp(0.0, 1.0),
+ child: child,
+ ),
+ ),
+ );
+ },
+ );
+}
+
+/// One of a question's answers beside the mic: `1 yes`, its digit in the asking yellow.
+class _AnswerKeycap extends StatelessWidget {
+ const _AnswerKeycap({required this.answer, required this.onTap});
+
+ final QuestionKey answer;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return _Keycap(
+ semanticsLabel: 'Answer ${answer.number} ${answer.label}',
+ minWidth: 88,
+ haptic: HapticFeedback.selectionClick,
+ onTap: onTap,
+ child: ConstrainedBox(
+ // Room for `2 always`; a longer answer ends in an ellipsis — its line says it in full.
+ constraints: const BoxConstraints(maxWidth: 120),
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '${answer.number} ',
+ style: tty.style(
+ size: TtySize.row,
+ color: tty.yellow,
+ weight: FontWeight.w600,
+ ),
+ ),
+ TextSpan(
+ text: answer.label,
+ style: tty.style(size: TtySize.row),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ );
+ }
+}
+
+/// A key on the raised plane: 6pt corners, no outline, darker under the finger on the way down.
+/// Drawn [height] tall inside a 44pt touch that reaches [slop] past it on every side.
+class _Keycap extends StatefulWidget {
+ const _Keycap({
+ required this.semanticsLabel,
+ required this.onTap,
+ required this.child,
+ required this.haptic,
+ this.minWidth = 48,
+ });
+
+ final String semanticsLabel;
+ final VoidCallback onTap;
+ final Widget child;
+ final Future<void> Function() haptic;
+ final double minWidth;
+
+ static const double height = 36;
+ static const double touch = 52;
+ static const double slop = (touch - height) / 2;
+
+ @override
+ State<_Keycap> createState() => _KeycapState();
+}
+
+class _KeycapState extends State<_Keycap> {
+ bool _down = false;
+
+ void _set(bool down) {
+ if (_down != down) setState(() => _down = down);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final raised = ttyRaised(tty);
+ return Semantics(
+ button: true,
+ label: widget.semanticsLabel,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapDown: (_) => _set(true),
+ onTapCancel: () => _set(false),
+ onTapUp: (_) => _set(false),
+ onTap: () {
+ unawaited(widget.haptic());
+ widget.onTap();
+ },
+ child: Padding(
+ padding: const EdgeInsets.all(_Keycap.slop),
+ child: Container(
+ height: _Keycap.height,
+ constraints: BoxConstraints(minWidth: widget.minWidth),
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: _down ? Color.lerp(raised, tty.ground, 0.5) : raised,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: widget.child,
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Holds the agent's last line at the foot of the screen while the output is followed at its end,
+/// by moving the terminal rather than resizing it.
+///
+/// A terminal fills from the top, so output shorter than the screen left a band of empty rows at
+/// the bottom while its first lines sat under the title. Moved, it fills the screen from the
+/// bottom up, the empty rows above it, under the title — the screen is always full. The pty
+/// keeps the whole screen, so reading back through the history uses every row: while it is read
+/// ([enabled] off) the terminal eases back to where it is drawn. Nothing moves on the alternate
+/// screen, where a full-screen program owns its own layout.
+class _AnchoredTerminal extends StatefulWidget {
+ const _AnchoredTerminal({
+ required this.terminal,
+ required this.enabled,
+ required this.reading,
+ required this.clearBottom,
+ required this.child,
+ });
+
+ final Terminal? terminal;
+ final bool enabled;
+
+ /// Non-null while the history is read back: the terminal is where it is drawn, then.
+ final ValueListenable<Object?> reading;
+
+ /// How far above the terminal's foot its last line is held.
+ final double clearBottom;
+ final Widget child;
+
+ @override
+ State<_AnchoredTerminal> createState() => _AnchoredTerminalState();
+}
+
+class _AnchoredTerminalState extends State<_AnchoredTerminal> {
+ /// Eases only when the reading starts or stops; output moves it at once, as output moves.
+ DateTime _easeUntil = DateTime.fromMillisecondsSinceEpoch(0);
+
+ late bool _on = _wantsOn;
+
+ bool get _wantsOn => widget.enabled && widget.reading.value == null;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.terminal?.addListener(_changed);
+ widget.reading.addListener(_toggled);
+ }
+
+ @override
+ void didUpdateWidget(_AnchoredTerminal old) {
+ super.didUpdateWidget(old);
+ if (!identical(old.terminal, widget.terminal)) {
+ old.terminal?.removeListener(_changed);
+ widget.terminal?.addListener(_changed);
+ }
+ if (!identical(old.reading, widget.reading)) {
+ old.reading.removeListener(_toggled);
+ widget.reading.addListener(_toggled);
+ }
+ // The keyboard coming or going moves everything at once; the terminal goes with it.
+ _settle(ease: false);
+ }
+
+ @override
+ void dispose() {
+ widget.terminal?.removeListener(_changed);
+ widget.reading.removeListener(_toggled);
+ super.dispose();
+ }
+
+ /// Reading started or stopped (eased — it moves the way the scroll does), or the keyboard
+ /// came or went (at once).
+ void _settle({required bool ease}) {
+ if (_on == _wantsOn) return;
+ _on = _wantsOn;
+ _easeUntil = ease
+ ? DateTime.now().add(const Duration(milliseconds: 240))
+ : DateTime.fromMillisecondsSinceEpoch(0);
+ }
+
+ void _toggled() {
+ _settle(ease: true);
+ _changed();
+ }
+
+ void _changed() {
+ if (!mounted) return;
+ // Output can land mid-frame (a resize answered during layout): rebuild after it, then.
+ if (SchedulerBinding.instance.schedulerPhase ==
+ SchedulerPhase.persistentCallbacks) {
+ SchedulerBinding.instance.addPostFrameCallback((_) {
+ if (mounted) setState(() {});
+ });
+ } else {
+ setState(() {});
+ }
+ }
+
+ /// The rendered height of one row, measured as xterm measures it.
+ static final _cells = Expando<double>();
+ static double _cellHeight(TerminalStyle style) => _cells[style] ??= () {
+ final text = style.toTextStyle();
+ final builder = ui.ParagraphBuilder(text.getParagraphStyle())
+ ..pushStyle(text.getTextStyle())
+ ..addText('mmmmmmmmmm');
+ final paragraph = builder.build()
+ ..layout(const ui.ParagraphConstraints(width: double.infinity));
+ final height = paragraph.height;
+ paragraph.dispose();
+ return height;
+ }();
+
+ double _shift(double viewport) {
+ final terminal = widget.terminal;
+ if (!_on || terminal == null || terminal.isUsingAltBuffer) {
+ return 0;
+ }
+ final buffer = terminal.buffer;
+ final height = buffer.height;
+ if (height == 0) return 0;
+ final cell = _cellHeight(terminalFontStore.value);
+ // The last line with anything on it — the cursor's, or below it where a TUI parked the
+ // cursor higher up.
+ var last = buffer.absoluteCursorY.clamp(0, height - 1);
+ for (var y = height - 1; y > last; y--) {
+ if (buffer.lines[y].getText().trim().isNotEmpty) {
+ last = y;
+ break;
+ }
+ }
+ // Rows are laid from the top until there is history to scroll, and from the foot after.
+ final bottom = height * cell <= viewport
+ ? (last + 1) * cell
+ : viewport - (height - 1 - last) * cell;
+ return viewport - widget.clearBottom - bottom;
+ }
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, box) {
+ final ease = DateTime.now().isBefore(_easeUntil);
+ return TweenAnimationBuilder<double>(
+ tween: Tween(end: _shift(box.maxHeight)),
+ duration: ease ? const Duration(milliseconds: 240) : Duration.zero,
+ curve: const Cubic(0.2, 0, 0, 1),
+ builder: (context, dy, child) =>
+ Transform.translate(offset: Offset(0, dy), child: child),
+ child: widget.child,
+ );
+ },
+ );
+}
+
+/// The line above the mic: a few words on what is going on, centred, over a band that fades the
+/// output out above it. The sample's guide wears a 6pt green [dot] that glides 24pt the way the
+/// swipe goes ([glide] 1 right, -1 left) every 2.4s; 0 holds it still.
+class _StatusLine extends StatefulWidget {
+ const _StatusLine({
+ required this.text,
+ this.color,
+ this.glide = 0,
+ this.dot = false,
+ });
+
+ final String text;
+
+ /// The words' colour; faint when null.
+ final Color? color;
+ final int glide;
+ final bool dot;
+
+ /// How far the band reaches below its words' foot.
+ static const double below = 6;
+
+ @override
+ State<_StatusLine> createState() => _StatusLineState();
+}
+
+class _StatusLineState extends State<_StatusLine>
+ with SingleTickerProviderStateMixin {
+ late final _clock = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 2400),
+ );
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _sync();
+ }
+
+ @override
+ void didUpdateWidget(_StatusLine old) {
+ super.didUpdateWidget(old);
+ if (old.glide != widget.glide) _sync();
+ }
+
+ void _sync() {
+ if (widget.glide == 0 ||
+ MediaQuery.maybeDisableAnimationsOf(context) == true) {
+ _clock
+ ..stop()
+ ..value = 0;
+ } else if (!_clock.isAnimating) {
+ unawaited(_clock.repeat());
+ }
+ }
+
+ @override
+ void dispose() {
+ _clock.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final dot = Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(color: tty.green, shape: BoxShape.circle),
+ );
+ // A band the width of the screen, the output fading out above it as it does under the title —
+ // a pill only as wide as its words cut the rows behind it in half.
+ return DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [tty.ground.withValues(alpha: 0), tty.ground, tty.ground],
+ stops: const [0, 0.4, 1],
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 14,
+ Tty.origin,
+ _StatusLine.below,
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ if (widget.dot) ...[
+ SizedBox(
+ width: 30,
+ height: 6,
+ child: AnimatedBuilder(
+ animation: _clock,
+ builder: (context, child) {
+ // A glide over the first 60% of each beat, easing in and out, then a rest.
+ final t = Curves.easeInOut.transform(
+ (_clock.value / 0.6).clamp(0.0, 1.0),
+ );
+ final from = widget.glide < 0 ? 24.0 : 0.0;
+ final x = widget.glide == 0
+ ? 12.0
+ : from + widget.glide * 24 * t;
+ final fade = widget.glide == 0 ? 1.0 : 1 - (t * t);
+ return Stack(
+ children: [
+ Positioned(
+ left: x,
+ top: 0,
+ child: Opacity(opacity: fade, child: child),
+ ),
+ ],
+ );
+ },
+ child: dot,
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ Flexible(
+ child: Text(
+ widget.text,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ size: TtySize.meta,
+ color: widget.color ?? tty.faint,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// The sample's last word: what it was, and the way to the real thing.
+class _SampleEndCard extends StatelessWidget {
+ const _SampleEndCard({
+ required this.started,
+ required this.onSetUp,
+ required this.onKeepPlaying,
+ });
+
+ /// The harness the person started — the last line of the tally.
+ final String started;
+ final VoidCallback onSetUp;
+ final VoidCallback onKeepPlaying;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ Widget tick(String text) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '✓ ',
+ style: tty.style(color: tty.green, size: TtySize.row),
+ ),
+ TextSpan(
+ text: text,
+ style: tty.style(size: TtySize.row),
+ ),
+ ],
+ ),
+ ),
+ );
+ return Material(
+ color: tty.ground,
+ child: SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Spacer(),
+ TtyText('That’s Harness.', size: 26, weight: FontWeight.w600),
+ const SizedBox(height: 20),
+ tick('watched a harness work'),
+ tick('answered its question'),
+ tick('started $started'),
+ const SizedBox(height: 6),
+ TtyText('3 passed', size: TtySize.meta, color: tty.green),
+ const SizedBox(height: 24),
+ Text(
+ 'Now do it on your own code. The real ones run on your '
+ 'computer; this phone is the remote.',
+ style: tty.style(size: TtySize.row),
+ ),
+ const Spacer(),
+ TtyPrimaryButton(label: 'Set up my computer', onPressed: onSetUp),
+ const SizedBox(height: 4),
+ Center(
+ child: TtyTextButton(
+ label: 'Keep playing',
+ onPressed: onKeepPlaying,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dart
index 1c43bb50b..178d48ba6 100644
--- a/mobile/lib/phone/terminal_search.dart
+++ b/mobile/lib/phone/terminal_search.dart
@@ -1,7 +1,9 @@
+import 'dart:async';
import 'dart:math' as math;
import 'dart:ui' show ImageFilter;
import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -9,62 +11,54 @@ import 'package:harness_mobile/shared/widgets/app_dialog.dart'
show kDialogVeilBlur, kSheetVeilOpacity;
import 'package:harness_mobile/state/app_state.dart';
-import 'agent_index.dart';
-import 'desk_groups.dart';
-import 'desk_tabs_panel.dart';
+import 'agents_page.dart' show openNewAgent;
+import 'find_models.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+import 'voice_input_controller.dart';
import 'phone_search_actions.dart';
import 'phone_search_controller.dart';
-import 'phone_search_field.dart';
import 'phone_search_results.dart';
-import 'sheet_list.dart';
-/// The terminal's way to another agent: a sheet up from the bottom, over the
-/// terminal, holding the account's tabs with a search field across its top.
+/// Find: the one way to another agent. A full-screen page in from the left edge over Focus —
+/// Snapchat's way to its chats — pulled by a swipe right on the terminal, or a tap on the agent's
+/// name. The agents you were last in come first; a field runs across the top. A swipe left sends it
+/// back.
///
/// ```
-/// ╭──────────────────────────────────╮
-/// │ ━━━ │
-/// │ ┌────────────────────┐ │
-/// │ │ ⌕ Search harnesses │ Cancel │ ← focused, it grows a Cancel
-/// │ └────────────────────┘ │
-/// │ (▓Desktop▓) ( Docker ) (+) │ ← until then, the tabs —
-/// │ DESKTOP 2 │ [DeskTabsPanel]
-/// │ ╭────────────────────────────╮ │
-/// │ │ ▣ api-3 ◌ › │ │
+/// ╭─────────────────────────────╮
+/// │ ┌──────────────────┐ │░░░
+/// │ │ ⌕ Find an agent │ + │░░░ ← focused, the + gives way to Cancel
+/// │ └──────────────────┘ │░░░
+/// │ ╭───────────────────────╮ │░░░
+/// │ │ ▣ fix login test ✓ │ │░░░ ← the one on screen
+/// │ │ ▣ docs rewrite │ │░░░
/// ```
///
-/// Drawn the way iOS draws its own sheets — a filled search bar, pills, an
-/// inset-grouped list — and the same way in both states: the results are the
-/// rows the tabs are ([SheetRow]), so the field taking focus changes what is
-/// listed and nothing about how.
+/// ⚠️ **One list, and it is the same list focused or not.** The sheet used to open on the account's
+/// desk tabs and trade them for results on focus; a phone has no tabs now (see
+/// `docs/plans/2026-09-26-001-mobile-zero-questions.md`). The rows are the account's harnesses by
+/// when their conversation last moved ([Agent.updatedAt], the same moment on every app) — so
+/// the two or three you work with on the go are the top rows; typing filters them, and return
+/// opens the first. The desktop's modes work here too: `>` commands, `#` projects, `@` machines,
+/// `?` help.
///
-/// ⚠️ **Two ways to the same place, one sheet.** An agent is found by where it
-/// is — its tab — or by what it is called, and those were two doors: a grid
-/// mark in the header for the tabs, and the floating Search button for a search
-/// that covered the screen. The button opens both now. The sheet reads the tabs
-/// until the field is focused; then the results take their place, and Cancel
-/// puts the tabs back.
+/// ⚠️ **Full height, and a keyboard lifts only its foot.** It runs up under the status bar; a
+/// keyboard, when it comes, takes the drawer's foot onto its own top rather than covering the rows.
///
-/// ⚠️ **Full height from the moment it opens.** Its top edge stands just under
-/// the status bar and stays there; the results take the tabs' place, and a
-/// keyboard, when it comes, takes the sheet's foot onto its own top rather
-/// than covering the rows — pinned to the window's foot, the sheet let the
-/// keys cover all but two rows of results.
+/// ⚠️ **The field is not focused on the way in.** The recent agents are what the sheet is opened to
+/// read, and a keyboard would cover half of them.
///
-/// ⚠️ **The field is not focused on the way in.** The tabs are what the sheet
-/// is opened to read, and focus is what trades them for the results.
+/// ⚠️ **Not a route.** Pushed, the sheet would sit in a navigator above the shell, and an agent
+/// opened from it would be pushed over the shell rather than take the home screen (see
+/// [openAgent]). Worse, the terminal beneath would still be the current route of ITS navigator: it
+/// would read the field's keyboard as its own and claim the input back, and the query would be typed
+/// into the shell. In place, the page holds its terminal still for as long as this is up — see
+/// `_heldForSearch` in `terminal_page.dart`.
///
-/// ⚠️ **Not a route.** Pushed, the sheet would sit in a navigator above the
-/// shell, and an agent opened from it would be pushed over the shell rather
-/// than take the home screen (see [openAgent]). Worse, the terminal beneath
-/// would still be the current route of ITS navigator: it would read the
-/// field's keyboard as its own and claim the input back, and the query would
-/// be typed into the shell. In place, the page holds its terminal still for as
-/// long as this is up — see `_heldForSearch` in `terminal_page.dart`.
-///
-/// ⚠️ **It must stay mounted only while it is up.** The field inside keeps the
-/// keyboard once tapped, so a copy left built behind the terminal would keep it
-/// and eat every keystroke the terminal is owed.
+/// ⚠️ **It must stay mounted only while it is up.** The field inside keeps the keyboard once tapped,
+/// so a copy left built behind the terminal would keep it and eat every keystroke the terminal is
+/// owed.
class TerminalSearchOverlay extends StatefulWidget {
const TerminalSearchOverlay({
super.key,
@@ -73,8 +67,12 @@ class TerminalSearchOverlay extends StatefulWidget {
required this.onClose,
this.showing,
this.bottomInset = 0,
+ this.voice,
});
+ /// The field's mic: what is said becomes the query. Null leaves the mic out.
+ final VoiceInputController? voice;
+
final AppNotifier notifier;
/// The open/close animation the terminal page drives — 0 gone, 1 up.
@@ -87,8 +85,7 @@ class TerminalSearchOverlay extends StatefulWidget {
final VoidCallback onClose;
- /// The agent on screen: the tab the sheet opens on, and the row wearing the
- /// check — in the tabs and in the results. See [DeskTabsPanel.showing].
+ /// The agent on screen: the row wearing the check.
final AgentRef? showing;
/// The strip at the foot of the window the sheet runs down over — the home
@@ -100,21 +97,20 @@ class TerminalSearchOverlay extends StatefulWidget {
/// `terminal_page.dart`.
final double bottomInset;
+ /// How wide Find stands over a window [width] wide: all of it. Find is a page of its own, the way
+ /// Snapchat's chats are — a strip of terminal left showing beside it read as a layer, and cost the
+ /// list width for long names. A swipe left takes it back.
+ ///
+ /// Public because the page's swipe right drives the slide under the finger, and a finger that
+ /// moves one drawer-width has opened it all the way.
+ static double drawerWidth(double width) => width;
+
@override
State<TerminalSearchOverlay> createState() => _TerminalSearchOverlayState();
}
class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
with TickerProviderStateMixin {
- /// The corner iOS gives a sheet — rounder than a card, far less round than
- /// [BottomSheet]'s 28, whose curve made a sheet drawn like the system's
- /// own read as Material wearing its clothes.
- static const double _radius = 14;
-
- /// What the field says while it reads the tabs. The modes it also takes
- /// (`>`, `#`, `@`, `?`) are typed — see [_SearchHead].
- static const String _hint = 'Search harnesses';
-
/// How dark the page goes behind the sheet — a step past Material's
/// `black54`, with the page blurred under it as well. The phone sheets stand
/// on the same veil ([kSheetVeilOpacity]), so every sheet over a terminal
@@ -129,21 +125,10 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
/// to set the depth, which is why it can stay this far short of theirs.
static const double _scrim = kSheetVeilOpacity;
- /// A fling down faster than this closes the sheet however little it moved —
- /// [BottomSheet]'s own figure, so this sheet lets go like the others do.
+ /// A fling left faster than this closes Find however little it moved — [BottomSheet]'s own figure,
+ /// so it lets go like the app's sheets do.
static const double _flingSpeed = 700;
- /// How close under the status bar the sheet's top edge stands: a strip of
- /// the dimmed page left showing, which is what says it is a layer over the
- /// terminal rather than a page of its own.
- ///
- /// ⚠️ **The sheet opens full height, up to here, and stays there.** It used
- /// to rest at a share of the screen and climb to this edge only when a
- /// keyboard pushed it; now it opens where the keyboard used to take it, so
- /// the tabs get the whole screen to list in and focusing the field moves
- /// only the sheet's foot, never its top.
- static const double _topGap = 8;
-
final _controller = TextEditingController();
final _focus = FocusNode(debugLabel: 'Terminal search');
late final PhoneSearchController _search = PhoneSearchController(
@@ -152,45 +137,20 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
commands: () => phoneSearchCommands(context, widget.notifier),
);
+ /// The results, for the return key to open the top row of.
+ final _results = GlobalKey<PhoneSearchResultsState>();
+
/// The sheet's own box, measured to turn a drag's pixels into a share of its
/// height.
final _sheetKey = GlobalKey(debugLabel: 'Terminal search sheet');
- /// Whether the sheet is searching: results where the tabs were, Cancel
- /// beside the field.
+ /// Whether the field has been tapped: Cancel beside it instead of `+`.
///
- /// ⚠️ **Entered on focus, left on Cancel — not tied to focus both ways.** The
- /// keyboard goes away for reasons that are not "stop searching" — the return
- /// key puts it away on purpose. The results stay up through that, the way a
- /// search does anywhere on a phone; only Cancel, or Back, ends it. (A drag
- /// on the results keeps it: see [PhoneSearchResults].)
+ /// ⚠️ **Entered on focus, left on Cancel — not tied to focus both ways.** The keyboard goes away
+ /// for reasons that are not "stop searching" — the return key puts it away on purpose. The query
+ /// stays through that, the way a search does anywhere on a phone; only Cancel, or Back, ends it.
bool _searching = false;
- /// Whether the results are BUILT — from the focus that started the search to
- /// the last frame of their fade after Cancel. Not [_searching]: they have to
- /// stay on screen to be seen going.
- bool _resultsUp = false;
-
- /// The tabs and the results trading places, in the same spot.
- late final AnimationController _swap = AnimationController(
- vsync: this,
- duration: const Duration(milliseconds: 250),
- reverseDuration: const Duration(milliseconds: 200),
- )..addStatusListener(_onSwap);
-
- /// The tabs out over the first half of the swap and the results in over the
- /// later part, so the two are never both at full strength — one list printed
- /// over another reads as neither.
- late final CurvedAnimation _tabsGoing = CurvedAnimation(
- parent: _swap,
- curve: const Interval(0, 0.5, curve: Curves.easeIn),
- );
- late final Animation<double> _tabsShown = ReverseAnimation(_tabsGoing);
- late final CurvedAnimation _resultsShown = CurvedAnimation(
- parent: _swap,
- curve: const Interval(0.35, 1, curve: Curves.easeOut),
- );
-
/// How far a finger has pulled the sheet down, as a share of its height.
late final AnimationController _pull = AnimationController(vsync: this);
@@ -240,9 +200,6 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
_controller.dispose();
_focus.dispose();
_search.dispose();
- _tabsGoing.dispose();
- _resultsShown.dispose();
- _swap.dispose();
_pull.dispose();
super.dispose();
}
@@ -250,37 +207,16 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
/// A tap on the field is what starts a search — see [_searching].
void _onFocus() {
if (!_focus.hasFocus || _searching) return;
- // A search cancelled a moment ago can still be fading out with its query
- // in it: see [_cancel]. The empty field is the truth.
- if (_controller.text.isEmpty) _search.reset();
- setState(() {
- _searching = true;
- _resultsUp = true;
- });
- _swap.forward();
+ setState(() => _searching = true);
}
- /// Cancel: the search is over and the sheet goes back to the tabs, leaving
- /// the query behind with it — the next tap on the field starts from an empty
- /// box, as a search cancelled anywhere else does.
- ///
- /// ⚠️ The field is emptied now and the search itself only once the results
- /// have faded ([_onSwap]). Emptied at once, the fading list would swap to
- /// the empty query's rows on its way out — a different list for a blink.
+ /// Cancel: the query goes, and the list is the recent agents again.
void _cancel() {
if (!_searching) return;
_focus.unfocus();
_controller.clear();
- setState(() => _searching = false);
- _swap.reverse();
- }
-
- void _onSwap(AnimationStatus status) {
- if (status != AnimationStatus.dismissed || _searching || !_resultsUp) {
- return;
- }
_search.reset();
- setState(() => _resultsUp = false);
+ setState(() => _searching = false);
}
/// Puts the query in the field when it moved without a keystroke — a chip,
@@ -322,34 +258,59 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
widget.onClose();
}
- /// A row in the tabs: away first, then the agent — see [openDeskAgent].
- void _open(DeskGroup group, AgentEntry entry) {
- final notifier = widget.notifier;
+ /// `+`: away first, then the new-agent form. Null while no machine can take one.
+ /// `+ New Harness` — in the project the query matched when there is one; else on the machine of
+ /// the harness on screen, as a swipe left does; else the command's first ready machine.
+ void Function(({String machineId, String folder, String label})? place)?
+ _newAgent() {
final showing = widget.showing;
- _close();
- // ⚠️ **The agent already on screen, in the tab the phone is already in,
- // opens nothing.** The tap asks to stay where it is. Sent on, it would —
- // on a page reached by a swipe — rebuild the pager around the page it is
- // on (see [AgentHome]) and load that terminal again for nothing.
- if (showing != null &&
- entry.machineId == showing.machineId &&
- entry.agent.id == showing.agentId) {
- final groups = deskGroups(notifier, visibleAgents(agentIndex(notifier)));
- if (activeDeskGroup(notifier, groups, showing).id == group.id) return;
- }
- openDeskAgent(context, notifier, group, entry);
+ final here = showing == null
+ ? null
+ : widget.notifier.stateOf(showing.machineId);
+ final command = phoneSearchCommands(
+ context,
+ widget.notifier,
+ ).where((command) => command.id == 'agent.new').firstOrNull;
+ final ready = here != null && here.nodeOnline != false && !here.needsLink;
+ if (!ready && command == null) return null;
+ return (place) {
+ _close();
+ if (place != null) {
+ unawaited(
+ openNewAgent(
+ context,
+ widget.notifier,
+ place.machineId,
+ folder: place.folder,
+ voice: widget.voice,
+ ),
+ );
+ } else if (ready) {
+ unawaited(
+ openNewAgent(
+ context,
+ widget.notifier,
+ showing!.machineId,
+ voice: widget.voice,
+ ),
+ );
+ } else {
+ command!.run();
+ }
+ };
}
+ /// A drag left, anywhere over the page, pushes Find back the way it came. Measured against the
+ /// drawer's width, so the drawer stays under the finger.
void _onPull(DragUpdateDetails details) {
- final height = _sheetKey.currentContext?.size?.height ?? 0;
- if (height <= 0) return;
- _pull.value += details.primaryDelta! / height;
+ final width = _sheetKey.currentContext?.size?.width ?? 0;
+ if (width <= 0) return;
+ _pull.value -= details.primaryDelta! / width;
}
- /// Let go: closed on a fling down or past half its height — [BottomSheet]'s
- /// own rule — and back up otherwise.
+ /// Let go: closed on a fling left or past half its width, and back otherwise.
void _onRelease(DragEndDetails details) {
- if ((details.primaryVelocity ?? 0) > _flingSpeed || _pull.value > 0.5) {
+ if ((details.primaryVelocity ?? 0) < -_flingSpeed || _pull.value > 0.5) {
_close();
return;
}
@@ -372,23 +333,21 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
// building it again.
final sheet = _sheet(context);
return PopScope(
- // Back steps out of the search and then closes the sheet — never leaves
- // the agent: the terminal is still underneath, and this is what covers
- // it.
+ // Back steps out of the search and then closes Find — never leaves the
+ // agent: the terminal is still underneath, and this is what covers it.
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _back();
},
// The terminal under the dimming is not what a screen reader should be
- // walking while the sheet is up.
+ // walking while Find is up.
child: BlockSemantics(
child: GestureDetector(
- // ⚠️ **A sideways drag anywhere over the page is claimed here and
- // goes nowhere.** The pager under the terminal swipes on exactly
- // that, and it would carry the sheet off with the page it belongs
- // to. The tab pills scroll sideways too, and win it for themselves
- // where they are.
- onHorizontalDragStart: (_) {},
+ // A drag left anywhere — on the drawer or on the strip of terminal
+ // beside it — sends Find back. The list scrolls on the other axis.
+ onHorizontalDragUpdate: _onPull,
+ onHorizontalDragEnd: _onRelease,
+ onHorizontalDragCancel: _settle,
child: LayoutBuilder(
builder: (context, box) => _layOut(context, box.biggest, sheet),
),
@@ -399,43 +358,34 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
Widget _layOut(BuildContext context, Size area, Widget sheet) {
final screen = MediaQuery.sizeOf(context).height;
- final ceiling = MediaQuery.paddingOf(context).top + _topGap;
+ final width = TerminalSearchOverlay.drawerWidth(area.width);
return AnimatedBuilder(
animation: Listenable.merge([widget.animation, _pull, _keyboard]),
child: sheet,
builder: (context, sheet) {
- // ⚠️ **The sheet stands on the keyboard as measured, not on the
+ // ⚠️ **The drawer stands on the keyboard as measured, not on the
// page's foot.** The page does not always end at the keyboard's top:
// where it has been resized for the keys this is zero, and where it
// has not it runs on under them and this is how far — so the foot
// lands on the keys either way. Taken against the window's height,
- // because this overlay starts at the window's top (see where
- // `terminal_page.dart` places it, under the status bar).
- //
- // The sheet runs from the ceiling down to whatever is under it — the
- // foot of the window, or the keyboard's top — so a keyboard shortens
- // it from below and its top edge never moves.
+ // because this overlay starts at the window's top.
//
// ⚠️ **Read from the view HERE, not from the notifier's last value.**
// [_keyboard] is written from metrics ticks and is what makes this
- // rebuild, but the value it holds can be a frame behind the page: a
- // tick that lands while the page has already grown back left the sheet
- // lifted by a keyboard that was no longer there, floating at the top of
- // the screen over a band of empty background — which is what opening
- // search from a keyboard looked like.
+ // rebuild, but the value it holds can be a frame behind the page.
final view = View.of(context);
final keyboard = view.viewInsets.bottom / view.devicePixelRatio;
final covered = math.min(
area.height,
math.max(0.0, area.height - (screen - keyboard)),
);
- final height = math.max(0.0, area.height - covered - ceiling);
+ final height = math.max(0.0, area.height - covered);
final open = widget.animation.value;
final pull = _pull.value;
- // How much of the veil is up: all of it with the sheet, and less of it
- // as a finger pulls the sheet back down — the blur and the tint clear
+ // How much of the veil is up: all of it with the drawer, and less of it
+ // as a finger pushes the drawer back — the blur and the tint clear
// together, so a pull shows the terminal coming back into focus.
- final veil = open * (1 - pull);
+ final veil = math.max(0.0, open * (1 - pull));
final blur = kDialogVeilBlur * veil;
return Stack(
children: [
@@ -453,7 +403,7 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
child: ClipRect(
child: BackdropFilter(
// Off while there is nothing to blur: the first frame of
- // the way up, the last of the way down.
+ // the way in, the last of the way out.
enabled: blur > 0,
filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
child: ColoredBox(
@@ -466,11 +416,11 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
),
Positioned(
left: 0,
- right: 0,
- bottom: covered,
+ top: 0,
+ width: width,
height: height,
child: Transform.translate(
- offset: Offset(0, (1 - open + pull) * height),
+ offset: Offset(-(1 - open + pull) * width, 0),
child: sheet,
),
),
@@ -482,244 +432,158 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
Widget _sheet(BuildContext context) {
final media = MediaQuery.of(context);
- return GestureDetector(
+ final tty = Tty.of(context);
+ return Container(
key: _sheetKey,
- // The whole sheet can be pulled down, as a route's sheet can. The lists
- // in it scroll on the same drag and win it where they are.
- onVerticalDragUpdate: _onPull,
- onVerticalDragEnd: _onRelease,
- onVerticalDragCancel: _settle,
- child: CustomPaint(
- foregroundPainter: _TopRim(color: AppGlass.hair),
+ color: tty.ground,
+ child: MediaQuery(
+ data: media.copyWith(
+ padding: media.padding.copyWith(top: 0, bottom: 0),
+ ),
child: Material(
- // A step above the terminal it covers — see [sheetFill].
- color: sheetFill,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(_radius)),
- ),
- clipBehavior: Clip.antiAlias,
- child: MediaQuery(
- // The lists run down under the strip at the foot of the window and
- // pad their own last row clear of it. The top is the sheet's edge,
- // nowhere near the status bar.
- data: media.copyWith(
- padding: media.padding.copyWith(
- top: 0,
- bottom: widget.bottomInset,
- ),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- const _Grip(),
- ListenableBuilder(
- listenable: _search,
- builder: (context, _) => SheetSearchField(
- controller: _controller,
- focus: _focus,
- // Inside a project or a machine the box says which — the
- // one thing on the sheet that does, other than the caption.
- hintText: _search.canGoBack ? _search.hint : _hint,
- onChanged: _search.setQuery,
- onClear: () {
- _controller.clear();
- _search.setQuery('');
- // Clearing is a step back into browsing, not out of the
- // search — the caret stays where the next query will go.
- _focus.requestFocus();
+ type: MaterialType.transparency,
+ child: ListenableBuilder(
+ listenable: _search,
+ builder: (context, _) {
+ final newAgent = _newAgent();
+ final hasText = _controller.text.isNotEmpty;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(height: media.padding.top + 8),
+ // The field at the top, like ⌘P: the list grows down from it. The keyboard stays
+ // down until the field is tapped — the list is usually the answer.
+ // No Cancel: a swipe left is the way out, as it was the way in.
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyField(
+ controller: _controller,
+ focus: _focus,
+ hint: _search.canGoBack
+ ? 'Search in ${_search.scopeName}'
+ : _search.hint.replaceAll('…', ''),
+ onChanged: _search.setQuery,
+ onSubmitted: () =>
+ _results.currentState?.openFirst(),
+ action: TextInputAction.search,
+ trailing: [
+ if (hasText)
+ _FieldClear(onTap: _clearField)
+ else if (widget.voice case final voice?)
+ ListenableBuilder(
+ listenable: voice,
+ builder: (context, _) => TtyFieldMic(
+ live:
+ voice.status ==
+ VoiceInputStatus.listening ||
+ voice.status ==
+ VoiceInputStatus.starting,
+ onTap: () => _talk(voice),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 4),
+ Expanded(
+ child: switch ((_search.isModelMode, widget.showing)) {
+ // `:` — the models the harness on screen can run on.
+ (true, final showing?) => FindModels(
+ notifier: widget.notifier,
+ machineId: showing.machineId,
+ agentId: showing.agentId,
+ query: _search.matchQuery,
+ onPicked: _close,
+ ),
+ _ => PhoneSearchResults(
+ key: _results,
+ notifier: widget.notifier,
+ controller: _search,
+ fzf: true,
+ showing: widget.showing,
+ onOpen: _close,
+ onNewHarness: newAgent == null
+ ? null
+ : (place) => newAgent(place),
+ ),
},
- onCancel: _searching ? _cancel : null,
),
- ),
- Expanded(child: _content()),
- ],
- ),
+ // Over the home indicator while the keyboard is down; on the keys once it is up.
+ SizedBox(height: widget.bottomInset),
+ ],
+ );
+ },
),
),
),
);
}
- Widget _content() => Stack(
- fit: StackFit.expand,
- children: [
- // ⚠️ **The tabs stay built under the results**, faded out and deaf to
- // touch, rather than coming down with the search. The tab being read is
- // their own state, and Cancel has to land back on it — not on the tab
- // the sheet happened to open on.
- IgnorePointer(
- ignoring: _searching,
- child: ExcludeSemantics(
- excluding: _searching,
- child: FadeTransition(
- opacity: _tabsShown,
- child: DeskTabsPanel(
- notifier: widget.notifier,
- showing: widget.showing,
- onOpen: _open,
- onClose: _close,
- ),
- ),
- ),
- ),
- if (_resultsUp)
- IgnorePointer(
- ignoring: !_searching,
- child: FadeTransition(
- opacity: _resultsShown,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _SearchHead(search: _search, onBack: _back),
- // ⚠️ Handed the query and nothing else. Ranking lives inside
- // it, so this sheet and [PhoneSearchPage] cannot drift into
- // returning different rows for the same words.
- Expanded(
- child: PhoneSearchResults(
- notifier: widget.notifier,
- controller: _search,
- // The rows the tabs under them are drawn with.
- grouped: true,
- showing: widget.showing,
- // ⚠️ Nothing pops this sheet — opening an agent swaps the
- // terminal underneath it instead — so tapping a row has to
- // close it by hand. Without this the keyboard would still
- // be up over an agent nobody asked to type into.
- onOpen: _close,
- ),
- ),
- ],
- ),
- ),
- ),
- ],
- );
-}
-
-/// Calls [onChange] whenever the window's metrics move — a keyboard rising or
-/// falling among them. Its own object, so the sheet's state does not have to
-/// be a [WidgetsBindingObserver] for the one callback it needs.
-class _MetricsWatch extends WidgetsBindingObserver {
- _MetricsWatch(this.onChange);
-
- final VoidCallback onChange;
-
- @override
- void didChangeMetrics() => onChange();
-}
-
-/// What sits over the results once there is a query: a caption naming what is
-/// listed and how much of it. Nothing while the field is empty.
-///
-/// ```
-/// HARNESSES 4/14 ← a query
-/// ‹ MACBOOK PRO 9 ← inside a machine
-/// ```
-///
-/// ⚠️ **No row of mode chips over an empty field.** `> Commands`, `# Projects`,
-/// `@ Machines` and `? Help` stood here while nothing was typed, and cost the
-/// results a row on a sheet the keyboard already shortens. The modes are still
-/// one character away — `?` lists all four.
-///
-/// ⚠️ **No caption over an untouched list.** "Recent" over the rows the
-/// search opens on would cost a row of a sheet the keyboard has already
-/// halved, and say nothing the order of the rows does not.
-class _SearchHead extends StatelessWidget {
- const _SearchHead({required this.search, required this.onBack});
-
- final PhoneSearchController search;
-
- /// The caption's chevron, inside a project or a machine.
- final VoidCallback onBack;
+ void _clearField() {
+ _controller.clear();
+ _search.setQuery('');
+ }
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: search,
- builder: (context, _) {
- AppTheme.watch(context);
- final scoped = search.canGoBack;
- if (!scoped && search.query.trim().isEmpty) {
- return const SizedBox.shrink();
- }
- return SheetCaption(
- label: scoped
- ? search.scopeName ?? ''
- : search.isCommandMode || search.isHelpMode || search.isGroupMode
- ? search.title
- : 'Harnesses',
- // Only once the query has actually excluded something: `14/14` over
- // an untouched list is noise dressed as information.
- count: search.matchCount == search.total
- ? '${search.total}'
- : '${search.matchCount}/${search.total}',
- onBack: scoped ? onBack : null,
+ /// The field's mic: talk, and what was said becomes the query.
+ void _talk(VoiceInputController voice) {
+ if (voice.status == VoiceInputStatus.listening) {
+ unawaited(
+ voice.submit((text) async {
+ if (!mounted) return false;
+ final query = text.trim().replaceAll(RegExp(r'[.!?]+$'), '');
+ _controller.value = TextEditingValue(
+ text: query,
+ selection: TextSelection.collapsed(offset: query.length),
+ );
+ _search.setQuery(query);
+ return true;
+ }),
);
- },
- );
+ return;
+ }
+ if (voice.status == VoiceInputStatus.idle) {
+ unawaited(voice.startListening());
+ }
+ }
}
-/// The sheet's top edge, drawn: a hairline of light round its two corners and
-/// across, where the sheet meets the veil.
-///
-/// ⚠️ **The rim does what the fill cannot.** Two dark surfaces are parted by
-/// very little however their fills are chosen, and a veil darkens the page
-/// towards the sheet as much as away from it — the rim is the one thing on the
-/// edge brighter than both. It is the app's own recipe for anything floating
-/// over dark (see [AppMenu]): the fill lifts, the rim draws the edge.
-///
-/// ⚠️ **The top only.** The sheet runs the full width of the phone and down
-/// under the home indicator; a rim all the way round would be a line down
-/// each side of the screen.
-class _TopRim extends CustomPainter {
- const _TopRim({required this.color});
+/// The field's `✕`: empties it.
+class _FieldClear extends StatelessWidget {
+ const _FieldClear({required this.onTap});
- final Color color;
+ final VoidCallback onTap;
@override
- void paint(Canvas canvas, Size size) {
- const radius = _TerminalSearchOverlayState._radius;
- // Half the stroke in from the edge, so the whole line lies on the sheet
- // rather than half of it out over the veil.
- const inset = 0.5;
- const corner = Radius.circular(radius - inset);
- final rim = Path()
- ..moveTo(inset, radius)
- ..arcToPoint(const Offset(radius, inset), radius: corner)
- ..lineTo(size.width - radius, inset)
- ..arcToPoint(Offset(size.width - inset, radius), radius: corner);
- canvas.drawPath(
- rim,
- Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1
- ..color = color,
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: 'Clear',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: SizedBox(
+ width: 44,
+ height: 44,
+ child: Icon(LucideIcons.x300, size: 18, color: tty.faint),
+ ),
+ ),
);
}
-
- @override
- bool shouldRepaint(_TopRim old) => old.color != color;
}
-/// The bar at the top of the sheet that says it can be pulled down: iOS's
-/// grabber, at its size — drawn by hand because this sheet is not a route's.
-class _Grip extends StatelessWidget {
- const _Grip();
+class _MetricsWatch extends WidgetsBindingObserver {
+ _MetricsWatch(this.onChange);
+
+ final VoidCallback onChange;
@override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return SizedBox(
- height: 16,
- child: Center(
- child: Container(
- width: 36,
- height: 5,
- decoration: BoxDecoration(
- color: AppPalette.textFaint,
- borderRadius: BorderRadius.circular(2.5),
- ),
- ),
- ),
- );
- }
+ void didChangeMetrics() => onChange();
}
diff --git a/mobile/lib/phone/terminal_title.dart b/mobile/lib/phone/terminal_title.dart
new file mode 100644
index 000000000..6f12bcd28
--- /dev/null
+++ b/mobile/lib/phone/terminal_title.dart
@@ -0,0 +1,207 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Focus's title: whose terminal this is, in three lines — the harness, where it runs, its branch.
+///
+/// ```
+/// fix-login api-fix asking
+/// studio:web
+/// ⑂ fix/login-refresh
+/// ```
+///
+/// ⚠️ **The whole title is one button: its menu** (rename, restart, paste…). Nothing else is drawn
+/// to tap — no `…`, no state words: the terminal says when it is loading. Holding it goes back to
+/// the last harness. Find is a swipe right, and `api-fix asking` — a harness elsewhere waiting on
+/// you — is the one word that opens it from here.
+///
+/// It floats over the terminal's top rows only while the output is followed at its end, and slides
+/// away while the history is read back (see `TerminalChromeScroll`) — so it can afford three rows.
+class TerminalTitle extends StatelessWidget {
+ const TerminalTitle({
+ super.key,
+ required this.name,
+ required this.onTap,
+ required this.onFind,
+ this.place,
+ this.branch,
+ this.asking,
+ this.onHold,
+ });
+
+ final String name;
+
+ /// `machine:folder` — where the harness works.
+ final String? place;
+
+ final String? branch;
+
+ /// Harnesses elsewhere asking — `api-fix asking`, or `2 asking` — in yellow; a tap opens Find.
+ final String? asking;
+
+ /// A tap anywhere on the title: the harness's menu.
+ final VoidCallback onTap;
+
+ /// What `asking` opens.
+ final VoidCallback onFind;
+
+ /// Holding the title: back to the last harness (tmux's `prefix L`, vim's `:b#`).
+ final VoidCallback? onHold;
+
+ /// Four terminal rows: three lines of text and half a row of air above and below.
+ static double heightOf(Tty tty) => 4 * tty.row;
+
+ /// A long branch shortened in the middle — `fix/login-refresh-token` → `fix/logi…sh-token` — where
+ /// both ends say which one it is.
+ static String _short(String branch) => branch.length <= 30
+ ? branch
+ : '${branch.substring(0, 14)}…${branch.substring(branch.length - 14)}';
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final height = heightOf(tty);
+ final meta = tty.style(color: tty.faint, size: TtySize.meta);
+ final title = Semantics(
+ button: true,
+ label: '$name — harness menu',
+ child: GestureDetector(
+ key: const ValueKey('terminal-title'),
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ onLongPress: onHold == null
+ ? null
+ : () {
+ HapticFeedback.mediumImpact();
+ onHold!();
+ },
+ child: DecoratedBox(
+ // No rule under it: the output fades out beneath instead — see the gradient below.
+ decoration: BoxDecoration(color: tty.ground),
+ child: SizedBox(
+ height: height,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ if (place case final place? when place.isNotEmpty)
+ Text(
+ place,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: meta,
+ ),
+ if (branch case final branch?
+ when branch.trim().isNotEmpty)
+ Row(
+ children: [
+ Icon(
+ LucideIcons.gitBranch300,
+ size: 12,
+ color: tty.faint,
+ ),
+ const SizedBox(width: 5),
+ Flexible(
+ child: Text(
+ _short(branch),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ color: tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ if (asking case final asking?)
+ Semantics(
+ button: true,
+ label: '$asking — open Find',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onFind();
+ },
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: height,
+ minWidth: 44,
+ maxWidth: 170,
+ ),
+ child: Padding(
+ padding: const EdgeInsets.only(left: 12),
+ child: Align(
+ alignment: Alignment.topRight,
+ widthFactor: 1,
+ child: Padding(
+ padding: EdgeInsets.only(top: tty.row * 0.6),
+ child: Text(
+ asking,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ color: tty.yellow,
+ size: TtySize.meta,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ // The output fades out beneath the title rather than stopping at a rule.
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ title,
+ IgnorePointer(
+ child: Container(
+ height: 12,
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [tty.ground, tty.ground.withValues(alpha: 0)],
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/phone/tty.dart b/mobile/lib/phone/tty.dart
new file mode 100644
index 000000000..9b160dcbe
--- /dev/null
+++ b/mobile/lib/phone/tty.dart
@@ -0,0 +1,208 @@
+import 'package:flutter/material.dart';
+import 'package:xterm/xterm.dart' show TerminalTheme;
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+import 'package:harness_mobile/terminal/terminal_theme.dart';
+import 'package:harness_mobile/terminal/terminal_theme_store.dart';
+
+/// The phone's chrome, drawn as a terminal draws — the pieces every screen is built from.
+///
+/// ⚠️ **The rule: the app should look like the tools it sits beside — zsh, tmux, fzf, vim.** One
+/// monospace face at the terminal's own size, the terminal's own sixteen colours and ground, square
+/// edges, no cards, no shadows, no icons as decoration, reverse video for what is selected. The
+/// agent's terminal is the product; around it, the phone draws what tmux and fzf would.
+///
+/// Colours come from the terminal's resolved theme ([terminalThemeFor]), so the chrome changes with
+/// the terminal when its colours do.
+class Tty {
+ Tty._(this.theme, this.fontFamily, this.fontFallback, this.fontSize);
+
+ /// The terminal theme and font in force, read at build time.
+ factory Tty.of(BuildContext context) {
+ AppTheme.watch(context);
+ final font = terminalFontStore.value;
+ return Tty._(
+ terminalThemeFor(AppTheme.palette.value, terminalThemeStore.value),
+ font.fontFamily,
+ font.fontFamilyFallback,
+ // The terminal's own size, exactly: chrome and output share one cell, so a status line or an
+ // fzf row lands on the same columns as the agent's text beside it.
+ font.fontSize,
+ );
+ }
+
+ final TerminalTheme theme;
+ final String fontFamily;
+ final List<String> fontFallback;
+ final double fontSize;
+
+ Color get ground => theme.background;
+ Color get text => theme.foreground;
+
+ /// Rules, marks and the gutter — brightBlack, as a terminal draws its own furniture.
+ Color get dim => theme.brightBlack;
+
+ /// Secondary TEXT in the chrome: labels, details, hints. brightBlack on the ground is 3.1:1, too
+ /// faint to read at a glance on a phone; this is the agent's own faint text, about 4.9:1.
+ Color get faint =>
+ Color.alphaBlend(theme.foreground.withValues(alpha: 0.52), theme.background);
+ Color get green => theme.green;
+ Color get yellow => theme.yellow;
+ Color get red => theme.red;
+ Color get cyan => theme.cyan;
+ Color get magenta => theme.magenta;
+ Color get blue => theme.blue;
+
+ /// The row under the cursor — fzf's `bg+`: a step up from the ground, the text unchanged.
+ Color get selected => Color.alphaBlend(
+ theme.foreground.withValues(alpha: 0.12),
+ theme.background,
+ );
+
+ /// One terminal row's height — the pane's line height (1.2) at its size. Every height in the
+ /// chrome is a whole number of these.
+ double get row => fontSize * 1.2;
+
+ /// The shortest a tappable row may be drawn: whole rows, at least 44pt.
+ double get tapRow => (44 / row).ceil() * row;
+
+ /// One character cell's width — the grid every column in the chrome sits on.
+ double get cell => _cellWidth(fontFamily, fontFallback, fontSize);
+
+ /// Where the terminal's text starts: the pane's own left padding. Column 0 of the chrome.
+ static const double origin = 12;
+
+ /// The x of column [n].
+ double col(int n) => origin + n * cell;
+
+ static final _cells = <(String, double), double>{};
+ static double _cellWidth(String family, List<String> fallback, double size) =>
+ _cells.putIfAbsent((family, size), () {
+ final painter = TextPainter(
+ text: TextSpan(
+ text: 'MMMMMMMMMM',
+ style: TextStyle(
+ fontFamily: family,
+ fontFamilyFallback: fallback,
+ fontSize: size,
+ ),
+ ),
+ textDirection: TextDirection.ltr,
+ )..layout();
+ final width = painter.width / 10;
+ painter.dispose();
+ return width;
+ });
+
+ TextStyle style({
+ Color? color,
+ Color? background,
+ FontWeight weight = FontWeight.w400,
+ double? size,
+ }) => TextStyle(
+ fontFamily: fontFamily,
+ fontFamilyFallback: fontFallback,
+ fontSize: size ?? fontSize,
+ // The terminal's own line height, so chrome rows and output rows keep one pitch.
+ height: 1.2,
+ color: color ?? text,
+ backgroundColor: background,
+ fontWeight: weight,
+ // Tabular by construction, but ligatures would glue `->` and `!=` in paths and branch names.
+ fontFeatures: const [FontFeature.disable('liga'), FontFeature.disable('calt')],
+ );
+}
+
+/// A run of monospace text, one line, clipped at the edge like a terminal — no ellipsis dots a
+/// terminal would never draw.
+class TtyText extends StatelessWidget {
+ const TtyText(
+ this.text, {
+ super.key,
+ this.color,
+ this.background,
+ this.weight = FontWeight.w400,
+ this.size,
+ });
+
+ final String text;
+ final Color? color;
+ final Color? background;
+ final FontWeight weight;
+ final double? size;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Text(
+ text,
+ maxLines: 1,
+ softWrap: false,
+ overflow: TextOverflow.clip,
+ style: tty.style(
+ color: color,
+ background: background,
+ weight: weight,
+ size: size,
+ ),
+ );
+ }
+}
+
+/// A tappable region with a full touch target and no ink — a terminal has no ripple. Pressed, it
+/// shows fzf's selection ground at once, on the finger's way DOWN, which is what makes a tap feel
+/// instant.
+class TtyTap extends StatefulWidget {
+ const TtyTap({
+ super.key,
+ required this.child,
+ this.onTap,
+ this.semanticsLabel,
+ this.minHeight = 44,
+ });
+
+ final Widget child;
+ final VoidCallback? onTap;
+ final String? semanticsLabel;
+ final double minHeight;
+
+ @override
+ State<TtyTap> createState() => _TtyTapState();
+}
+
+class _TtyTapState extends State<TtyTap> {
+ bool _down = false;
+
+ void _set(bool down) {
+ if (_down != down) setState(() => _down = down);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final enabled = widget.onTap != null;
+ return Semantics(
+ button: enabled,
+ label: widget.semanticsLabel,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapDown: enabled ? (_) => _set(true) : null,
+ onTapCancel: enabled ? () => _set(false) : null,
+ onTapUp: enabled ? (_) => _set(false) : null,
+ onTap: widget.onTap,
+ child: ColoredBox(
+ color: _down ? tty.selected : Colors.transparent,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(minHeight: widget.minHeight),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ widthFactor: 1,
+ child: widget.child,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/tty_controls.dart b/mobile/lib/phone/tty_controls.dart
new file mode 100644
index 000000000..e9f656e3e
--- /dev/null
+++ b/mobile/lib/phone/tty_controls.dart
@@ -0,0 +1,578 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'composing_keyboard.dart';
+import 'tty.dart';
+
+/// The phone's controls, drawn in the terminal's face — the pieces that make a screen read as a
+/// phone app at a glance while still looking like it lives in a terminal.
+///
+/// ⚠️ **Structure from iOS, surface from the terminal.** A search field at the top, rows in groups,
+/// one filled button at the foot: those are what a phone user reads without thinking. SF Mono, the
+/// terminal's own colours, 1px rules and square-ish corners are what keep it at home beside vim
+/// and tmux. Plain words everywhere — never `esc`, `⏎` or a counter — since chrome is not a
+/// keyboard.
+
+/// The type scale: two sizes, one face. 17 for what you decide on or tap — names, values, fields,
+/// the button, titles, Cancel; 13 for everything else, and nothing smaller. The terminal keeps its
+/// own size.
+abstract final class TtySize {
+ /// Page titles.
+ static const double display = 28;
+
+ /// Fields, values, the button, sheet titles.
+ static const double title = 17;
+
+ /// A row's name.
+ static const double row = 15;
+
+ /// Everything secondary — and nothing smaller.
+ static const double meta = 13;
+}
+
+/// A raised ground, one step up from the terminal's: fields, the pressed row.
+Color ttyRaised(Tty tty) =>
+ Color.alphaBlend(tty.text.withValues(alpha: 0.09), tty.ground);
+
+/// The one filled button on a screen — Start, Sign in, Continue: full width, the terminal's green,
+/// a dark bold label. Pressed, it darkens on the finger's way DOWN.
+class TtyPrimaryButton extends StatefulWidget {
+ const TtyPrimaryButton({
+ super.key,
+ required this.label,
+ required this.onPressed,
+ this.busy = false,
+ this.busyLabel,
+ });
+
+ final String label;
+
+ /// Null draws it disabled.
+ final VoidCallback? onPressed;
+
+ /// Working: the label becomes [busyLabel] and the button takes no taps.
+ final bool busy;
+ final String? busyLabel;
+
+ static const double height = 52;
+
+ @override
+ State<TtyPrimaryButton> createState() => _TtyPrimaryButtonState();
+}
+
+class _TtyPrimaryButtonState extends State<TtyPrimaryButton> {
+ bool _down = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final enabled = widget.onPressed != null && !widget.busy;
+ final fill = !enabled && !widget.busy
+ ? tty.selected
+ : _down
+ ? Color.alphaBlend(Colors.black.withValues(alpha: 0.18), tty.green)
+ : tty.green;
+ final ink = !enabled && !widget.busy ? tty.faint : tty.theme.black;
+ return Semantics(
+ button: true,
+ enabled: enabled,
+ label: widget.label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapDown: enabled ? (_) => setState(() => _down = true) : null,
+ onTapCancel: enabled ? () => setState(() => _down = false) : null,
+ onTapUp: enabled ? (_) => setState(() => _down = false) : null,
+ onTap: enabled
+ ? () {
+ HapticFeedback.lightImpact();
+ widget.onPressed!();
+ }
+ : null,
+ child: Container(
+ // At least this tall, and taller when the text is larger — never clipped.
+ constraints: const BoxConstraints(minHeight: TtyPrimaryButton.height),
+ padding: const EdgeInsets.symmetric(
+ horizontal: Tty.origin,
+ vertical: 10,
+ ),
+ decoration: BoxDecoration(
+ color: fill,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ alignment: Alignment.center,
+ child: TtyText(
+ widget.busy ? (widget.busyLabel ?? widget.label) : widget.label,
+ color: ink,
+ weight: FontWeight.w600,
+ size: TtySize.title,
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A plain text button: Try again, Try it first. Text colour: the chrome keeps one accent, green.
+class TtyTextButton extends StatelessWidget {
+ const TtyTextButton({
+ super.key,
+ required this.label,
+ required this.onPressed,
+ this.color,
+ this.weight = FontWeight.w500,
+ });
+
+ final String label;
+ final VoidCallback? onPressed;
+ final Color? color;
+ final FontWeight weight;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onPressed == null
+ ? null
+ : () {
+ HapticFeedback.selectionClick();
+ onPressed!();
+ },
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 44, minWidth: 44),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Center(
+ widthFactor: 1,
+ child: TtyText(
+ label,
+ color: onPressed == null ? tty.dim : (color ?? tty.text),
+ weight: weight,
+ size: TtySize.row,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A branch, the one way it is written everywhere: the branch icon, then its name — never a `·`
+/// before it. The icon because `main` alone reads as a folder; the same glyph as Focus's title and
+/// the desktop's header. [lead] is the gap before it, when it follows something on its line.
+WidgetSpan ttyBranchMark(
+ Tty tty, {
+ Color? color,
+ double size = 12,
+ double lead = 8,
+}) => WidgetSpan(
+ alignment: PlaceholderAlignment.middle,
+ child: Padding(
+ padding: EdgeInsets.only(left: lead, right: 4),
+ child: Icon(
+ LucideIcons.gitBranch300,
+ size: size,
+ color: color ?? tty.faint,
+ ),
+ ),
+);
+
+/// Back, as iOS draws it on a pushed screen: a chevron and no word. A 44pt target whose glyph sits
+/// on the gutter, so it lines up with the title under it.
+class TtyBackButton extends StatelessWidget {
+ const TtyBackButton({super.key, required this.onPressed});
+
+ final VoidCallback? onPressed;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: 'Back',
+ excludeSemantics: true,
+ child: GestureDetector(
+ key: const ValueKey('tty-back'),
+ behavior: HitTestBehavior.opaque,
+ onTap: onPressed == null
+ ? null
+ : () {
+ HapticFeedback.selectionClick();
+ onPressed!();
+ },
+ child: SizedBox(
+ width: 52,
+ height: 44,
+ child: Padding(
+ padding: const EdgeInsets.only(left: Tty.origin - 5),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Icon(
+ LucideIcons.chevronLeft300,
+ size: 26,
+ color: onPressed == null ? tty.dim : tty.text,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A section's header: small, faint, upper case — `NEEDS YOU`, `RECENT`.
+class TtySectionHeader extends StatelessWidget {
+ const TtySectionHeader(this.text, {super.key, this.color, this.trailing});
+
+ final String text;
+ final Color? color;
+ final Widget? trailing;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 20, Tty.origin, 6),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ text.toUpperCase(),
+ maxLines: 1,
+ overflow: TextOverflow.clip,
+ softWrap: false,
+ style: tty
+ .style(
+ color: color ?? tty.faint,
+ size: TtySize.meta - 1,
+ weight: FontWeight.w600,
+ )
+ .copyWith(letterSpacing: 0.8),
+ ),
+ ),
+ ?trailing,
+ ],
+ ),
+ );
+ }
+}
+
+/// A 1px rule across the screen, inset like a grouped list's separator.
+class TtyRule extends StatelessWidget {
+ const TtyRule({super.key, this.indent = 16});
+
+ final double indent;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Padding(
+ padding: EdgeInsets.only(left: indent),
+ child: SizedBox(
+ height: 1,
+ child: ColoredBox(color: tty.dim.withValues(alpha: 0.6)),
+ ),
+ );
+ }
+}
+
+/// A form row: a faint label, its value, and `›` — tapped to change the value.
+class TtyFormRow extends StatelessWidget {
+ const TtyFormRow({
+ super.key,
+ required this.label,
+ required this.value,
+ this.detail,
+ this.onTap,
+ this.valueColor,
+ this.chevron = true,
+ });
+
+ final String label;
+ final String value;
+
+ /// A second, faint line under the value — a path, a note.
+ final String? detail;
+ final VoidCallback? onTap;
+ final Color? valueColor;
+ final bool chevron;
+
+ static const double labelWidth = 92;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return TtyTap(
+ onTap: onTap,
+ semanticsLabel: '$label, $value',
+ minHeight: 56,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 10, Tty.origin, 10),
+ child: Row(
+ children: [
+ SizedBox(
+ width: labelWidth,
+ child: TtyText(label, color: tty.faint, size: TtySize.meta),
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ value,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(
+ color: valueColor ?? tty.text,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ ),
+ if (detail case final detail? when detail.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ // Two lines, then an ellipsis: a note like approvals' meaning is a sentence.
+ Text(
+ detail,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tty.style(color: tty.faint, size: TtySize.meta),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (chevron && onTap != null)
+ Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: TtyText('›', color: tty.faint, size: TtySize.title),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// A text field in the terminal's face: a raised ground, a green cursor, a faint placeholder, and
+/// room at the end for a mic or a clear button. One line for search, a few for a task.
+class TtyField extends StatefulWidget {
+ const TtyField({
+ super.key,
+ required this.controller,
+ required this.hint,
+ this.focus,
+ this.onChanged,
+ this.onSubmitted,
+ this.lines = 1,
+ this.leading,
+ this.trailing = const [],
+ this.action = TextInputAction.done,
+ this.maxLength,
+ this.autofocus = false,
+ this.keyboardType,
+ this.autofillHints,
+ });
+
+ final TextInputType? keyboardType;
+ final Iterable<String>? autofillHints;
+
+ final TextEditingController controller;
+ final FocusNode? focus;
+ final String hint;
+ final ValueChanged<String>? onChanged;
+ final VoidCallback? onSubmitted;
+
+ /// How many lines tall; more than one wraps and grows up to it.
+ final int lines;
+
+ /// Drawn before the text — the search field's `>`.
+ final Widget? leading;
+
+ /// Drawn after the text: a mic, a clear button.
+ final List<Widget> trailing;
+ final TextInputAction action;
+ final int? maxLength;
+ final bool autofocus;
+
+ @override
+ State<TtyField> createState() => _TtyFieldState();
+}
+
+class _TtyFieldState extends State<TtyField> {
+ late final FocusNode _focus = widget.focus ?? FocusNode();
+
+ @override
+ void initState() {
+ super.initState();
+ _focus.addListener(_onFocus);
+ }
+
+ @override
+ void dispose() {
+ _focus.removeListener(_onFocus);
+ if (widget.focus == null) _focus.dispose();
+ super.dispose();
+ }
+
+ void _onFocus() => setState(() {});
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final multi = widget.lines > 1;
+ final field = TextSelectionTheme(
+ // The terminal's green for the cursor, the handles and the selection — not Material blue.
+ data: TextSelectionThemeData(
+ cursorColor: tty.green,
+ selectionColor: tty.green.withValues(alpha: 0.3),
+ selectionHandleColor: tty.green,
+ ),
+ child: TextField(
+ controller: widget.controller,
+ focusNode: _focus,
+ autofocus: widget.autofocus,
+ onChanged: widget.onChanged,
+ onSubmitted: (_) => widget.onSubmitted?.call(),
+ minLines: multi ? 3 : 1,
+ maxLines: multi ? widget.lines : 1,
+ maxLength: widget.maxLength,
+ maxLengthEnforcement: MaxLengthEnforcement.enforced,
+ keyboardType:
+ widget.keyboardType ?? (multi ? TextInputType.multiline : null),
+ autofillHints: widget.autofillHints,
+ textInputAction: widget.action,
+ // The keyboard's own composing, left on: Vietnamese Telex on iOS rides on
+ // autocorrection. See `ComposingKeyboard`.
+ autocorrect: ComposingKeyboard.autocorrect,
+ enableSuggestions: ComposingKeyboard.enableSuggestions,
+ smartDashesType: SmartDashesType.disabled,
+ smartQuotesType: SmartQuotesType.disabled,
+ textCapitalization: multi
+ ? TextCapitalization.sentences
+ : TextCapitalization.none,
+ cursorColor: tty.green,
+ cursorWidth: 2,
+ style: tty.style(size: multi ? TtySize.row : TtySize.title),
+ decoration: InputDecoration(
+ isCollapsed: true,
+ constraints: const BoxConstraints(),
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ contentPadding: EdgeInsets.zero,
+ counterText: '',
+ hintText: widget.hint,
+ hintMaxLines: multi ? 3 : 1,
+ hintStyle: tty.style(
+ color: tty.faint,
+ size: multi ? TtySize.row : TtySize.title,
+ ),
+ ),
+ ),
+ );
+ return GestureDetector(
+ // A tap anywhere in the box — not only on the text — takes the keyboard.
+ behavior: HitTestBehavior.opaque,
+ onTap: _focus.requestFocus,
+ child: Container(
+ constraints: BoxConstraints(minHeight: multi ? 96 : 44),
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ padding: EdgeInsets.fromLTRB(12, multi ? 10 : 0, 4, multi ? 6 : 0),
+ child: multi
+ // Multi-line: the text starts at the top; what trails it (the mic) sits in the bottom
+ // corner, under the thumb, and the text keeps clear of it.
+ ? Stack(
+ children: [
+ Padding(
+ padding: EdgeInsets.only(
+ right: widget.trailing.isEmpty ? 8 : 44,
+ ),
+ child: field,
+ ),
+ if (widget.trailing.isNotEmpty)
+ Positioned(
+ right: 0,
+ bottom: 0,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: widget.trailing,
+ ),
+ ),
+ ],
+ )
+ : Row(
+ children: [
+ if (widget.leading case final leading?) ...[
+ leading,
+ const SizedBox(width: 8),
+ ],
+ Expanded(child: field),
+ ...widget.trailing,
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// A small round mic for inside a field — tap to talk into it.
+class TtyFieldMic extends StatelessWidget {
+ const TtyFieldMic({super.key, required this.onTap, this.live = false});
+
+ final VoidCallback? onTap;
+
+ /// Recording: drawn red.
+ final bool live;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: live ? 'Stop and use what was said' : 'Say it',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap == null
+ ? null
+ : () {
+ HapticFeedback.lightImpact();
+ onTap!();
+ },
+ child: SizedBox(
+ width: 44,
+ height: 44,
+ child: Center(
+ child: Container(
+ width: 32,
+ height: 32,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: live ? tty.red : Colors.transparent,
+ border: live ? null : Border.all(color: tty.dim),
+ ),
+ child: Icon(
+ live ? LucideIcons.arrowUp300 : LucideIcons.mic300,
+ size: 18,
+ color: live ? tty.theme.brightWhite : tty.text,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/usage_entry.dart b/mobile/lib/phone/usage_entry.dart
index b4ca3abe6..0690fe8bc 100644
--- a/mobile/lib/phone/usage_entry.dart
+++ b/mobile/lib/phone/usage_entry.dart
@@ -19,14 +19,17 @@ import 'usage_page.dart';
/// one worth a glance from a list of rows: the account closest to running out is
/// the one that will stop the work. A dash when nothing has been read yet,
/// never a zero — `0% used` is a measurement, and this has none.
-Widget buildUsageSettingsRow(BuildContext context, AppNotifier notifier) =>
- ValueListenableBuilder<String?>(
- valueListenable: lastUsageSummary,
- builder: (context, summary, _) => SettingsRow(
- title: 'Usage',
- value: summary ?? '—',
- onTap: () => Navigator.of(
- context,
- ).push(phoneRoute((_) => UsagePage(notifier: notifier))),
- ),
- );
+Widget buildUsageSettingsRow(
+ BuildContext context,
+ AppNotifier notifier,
+) => ValueListenableBuilder<String?>(
+ valueListenable: lastUsageSummary,
+ builder: (context, summary, _) => SettingsRow(
+ title: 'Usage',
+ // Nothing until something has been read: a dash was a dead word on the row.
+ value: summary,
+ onTap: () =>
+ Navigator.of(context)
+ .push(phoneRoute((_) => UsagePage(notifier: notifier))),
+ ),
+);
diff --git a/mobile/lib/phone/voice_bar_line.dart b/mobile/lib/phone/voice_bar_line.dart
new file mode 100644
index 000000000..fad995a67
--- /dev/null
+++ b/mobile/lib/phone/voice_bar_line.dart
@@ -0,0 +1,107 @@
+import 'package:flutter/material.dart';
+
+import 'tty.dart';
+import 'voice_mic_face.dart' show VoiceMicCore;
+import 'voice_input_controller.dart';
+
+/// What the mic is doing — shown by the mic itself, not said beside it.
+///
+/// Recording, the mic is green and [VoiceLevelHalo] glows behind it with the voice; opening,
+/// transcribing and sending, its arc spins. Words appear on the line above it only when something
+/// went wrong ([voiceStatus]). The take goes to the harness on screen, which its title names.
+abstract final class VoiceLine {
+ /// Whether the voice has anything to say or show.
+ static bool shows(VoiceInputController voice) =>
+ voice.isSending ||
+ voice.notice != null ||
+ voice.transcript.isNotEmpty ||
+ voice.status == VoiceInputStatus.starting ||
+ voice.status == VoiceInputStatus.listening ||
+ voice.status == VoiceInputStatus.transcribing;
+}
+
+/// The words for the line above the mic — only when something went wrong: the mic could not
+/// start or heard nothing, or a take is kept unsent. Null the rest of the time, the mic's own
+/// face saying the rest.
+({String text, Color color})? voiceStatus(VoiceInputController voice, Tty tty) {
+ if (voice.notice case final notice?) {
+ return (text: notice.toLowerCase(), color: tty.yellow);
+ }
+ final idle =
+ !voice.isSending &&
+ voice.status != VoiceInputStatus.starting &&
+ voice.status != VoiceInputStatus.listening &&
+ voice.status != VoiceInputStatus.transcribing;
+ if (idle && voice.transcript.isNotEmpty) {
+ return (text: 'not sent · tap the mic again', color: tty.red);
+ }
+ return null;
+}
+
+/// How loud the take is, as Siri shows it: a soft green glow behind the mic that swells with the
+/// voice — [VoiceMicCore.diameter] at silence, 28pt wider at full voice.
+class VoiceLevelHalo extends StatefulWidget {
+ const VoiceLevelHalo({super.key, required this.voice});
+
+ final VoiceInputController voice;
+
+ /// The widest it grows: the box it is laid out in.
+ static const double extent = VoiceMicCore.diameter + 28;
+
+ @override
+ State<VoiceLevelHalo> createState() => _VoiceLevelHaloState();
+}
+
+class _VoiceLevelHaloState extends State<VoiceLevelHalo> {
+ double _level = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.voice.level.addListener(_onLevel);
+ }
+
+ @override
+ void didUpdateWidget(VoiceLevelHalo old) {
+ super.didUpdateWidget(old);
+ if (!identical(old.voice, widget.voice)) {
+ old.voice.level.removeListener(_onLevel);
+ widget.voice.level.addListener(_onLevel);
+ }
+ }
+
+ @override
+ void dispose() {
+ widget.voice.level.removeListener(_onLevel);
+ super.dispose();
+ }
+
+ void _onLevel() {
+ if (widget.voice.status != VoiceInputStatus.listening) return;
+ final level = widget.voice.level.value.clamp(0.0, 1.0);
+ if ((level - _level).abs() > 0.02) setState(() => _level = level);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final size =
+ VoiceMicCore.diameter +
+ (VoiceLevelHalo.extent - VoiceMicCore.diameter) * _level;
+ return SizedBox.square(
+ dimension: VoiceLevelHalo.extent,
+ child: Center(
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 120),
+ curve: Curves.easeOut,
+ width: size,
+ height: size,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: tty.green.withValues(alpha: 0.28),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/voice_input_scope.dart b/mobile/lib/phone/voice_input_scope.dart
new file mode 100644
index 000000000..9e11d4dec
--- /dev/null
+++ b/mobile/lib/phone/voice_input_scope.dart
@@ -0,0 +1,26 @@
+import 'package:flutter/widgets.dart';
+
+import 'voice_input_controller.dart';
+
+/// Who makes the voice input for the terminal pages below — where it is not the backend's
+/// speech-to-text over the phone's microphone.
+///
+/// Sample mode (`lib/demo/`) is the one place that has this: it has no account to sign a
+/// transcription with and no reason to open the microphone, so it hands its own controller down
+/// here. Without one, `AgentSwipeHost` builds the ordinary controller, exactly as before.
+class VoiceInputScope extends InheritedWidget {
+ const VoiceInputScope({
+ super.key,
+ required this.create,
+ required super.child,
+ });
+
+ /// A new controller for one pager, which owns and disposes it.
+ final VoiceInputController Function() create;
+
+ static VoiceInputScope? maybeOf(BuildContext context) =>
+ context.getInheritedWidgetOfExactType<VoiceInputScope>();
+
+ @override
+ bool updateShouldNotify(VoiceInputScope oldWidget) => false;
+}
diff --git a/mobile/lib/phone/voice_mic_action.dart b/mobile/lib/phone/voice_mic_action.dart
index 7531e5585..5493de9a7 100644
--- a/mobile/lib/phone/voice_mic_action.dart
+++ b/mobile/lib/phone/voice_mic_action.dart
@@ -29,8 +29,8 @@ VoiceMicAction voiceMicAction(
/// Tap to talk, tap Send — [VoiceMicMode.tapToToggle].
///
/// The second tap ends the take and sends what was heard as a composer turn —
-/// the daemon pastes it into the prompt and presses Return. `×` in the pill
-/// beside the mic is the way out while it listens.
+/// the daemon pastes it into the prompt and presses Return. A swipe down on the
+/// mic is the way out while it listens (see `VoiceMicButton.onSwipeDown`).
///
/// ⚠️ **A composer turn, never keystrokes typed into the pane.** Typing the
/// words and pressing Return from here puts both on the wire in the same
@@ -46,7 +46,7 @@ VoiceMicAction voiceMicAction(
/// the person's back is worse than asking for one more tap.
VoiceMicAction _tapAction(VoiceInputController voice, TerminalSession session) {
final canSend = session.acceptsInput;
- void send() => unawaited(voice.submit(session.sendComposerText));
+ void send() => unawaited(voice.submit(session.voiceDeliver ?? session.sendComposerText));
if (voice.isSending) return _face(VoiceMicFace.sending);
return switch (voice.status) {
VoiceInputStatus.transcribing => _face(VoiceMicFace.busy),
@@ -131,7 +131,7 @@ VoiceMicAction _holdAction(
: VoiceMicFace.talk,
onPressed: live ? _live : null,
onHoldStart: live
- ? () => unawaited(voice.startHold(session.sendComposerText))
+ ? () => unawaited(voice.startHold(session.voiceDeliver ?? session.sendComposerText))
: null,
onHoldFinish: live ? _release(voice, session) : null,
);
@@ -158,7 +158,7 @@ void Function({required bool cancelled}) _release(
voice.cancelHold();
return;
}
- unawaited(voice.finishHold(session.sendComposerText));
+ unawaited(voice.finishHold(session.voiceDeliver ?? session.sendComposerText));
};
/// Marks the button live in hold mode without giving it anything to do on tap.
diff --git a/mobile/lib/phone/voice_mic_button.dart b/mobile/lib/phone/voice_mic_button.dart
index 1571d61d9..8ec1a12cc 100644
--- a/mobile/lib/phone/voice_mic_button.dart
+++ b/mobile/lib/phone/voice_mic_button.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -34,10 +35,22 @@ class VoiceMicButton extends StatefulWidget {
this.onHoldStart,
this.onHoldFinish,
this.onSlipChanged,
+ this.working = false,
+ this.level,
+ this.onSwipeDown,
});
final VoiceMicFace face;
+ /// The microphone's level while it listens — see [VoiceMicCore.level].
+ final ValueListenable<double>? level;
+
+ /// A swipe down on the mic: throws the take away. Null when there is no take to throw.
+ final VoidCallback? onSwipeDown;
+
+ /// The agent is working — see [VoiceMicCore.working].
+ final bool working;
+
/// Null draws the button dimmed and dead.
///
/// In [VoiceMicMode.holdToTalk] this still decides whether the button is live
@@ -71,7 +84,7 @@ class VoiceMicButton extends StatefulWidget {
/// now (see `voice_mic_fab.dart`), so this is simply the box the `Positioned`
/// sizes to — raising it costs the terminal nothing, and the hit area below
/// already reaches well past it either way.
- static const double extent = 60;
+ static const double extent = 80;
/// What the finger may actually land on.
///
@@ -81,7 +94,9 @@ class VoiceMicButton extends StatefulWidget {
/// [OverflowBox] is what allows a child bigger than its parent: the hit area
/// reaches out over the terminal on every side, which has nothing tappable to
/// collide with.
- static const double touchExtent = 84;
+ /// The hit circle: the disc and a little more, never the 96pt it was — a tap on the agent's
+ /// prompt beside the mic must reach the terminal, not start a recording.
+ static const double touchExtent = 80;
/// How far the hit area spills past its slot on each side.
///
@@ -119,6 +134,9 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {
/// A finger is on the live mic, and the circle sinks a little under it.
bool _pressed = false;
+ /// How far down the finger has gone in a swipe on the mic.
+ double _swipe = 0;
+
bool get _live => widget.onPressed != null;
/// What to draw: the face given, unless a hold has been dragged off the
@@ -143,7 +161,9 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {
micHoldsToTalk ? 'Hold to talk to the harness' : 'Talk to the harness',
VoiceMicFace.starting => 'Cancel',
VoiceMicFace.listening =>
- micHoldsToTalk ? 'Release to send' : 'Done talking',
+ micHoldsToTalk
+ ? 'Release to send'
+ : 'Listening. Tap to send, swipe down to cancel',
VoiceMicFace.cancelling => 'Release to cancel',
VoiceMicFace.busy || VoiceMicFace.sending => 'Working',
VoiceMicFace.retry => 'Send again',
@@ -297,7 +317,12 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {
duration: const Duration(milliseconds: 140),
curve: Curves.easeOut,
scale: _pressed && !_slippedOff ? 0.92 : 1,
- child: VoiceMicCore(face: _face, dead: _dead),
+ child: VoiceMicCore(
+ face: _face,
+ dead: _dead,
+ working: widget.working,
+ level: widget.level,
+ ),
),
),
),
@@ -334,6 +359,22 @@ class _VoiceMicButtonState extends State<VoiceMicButton> {
}
: null,
onLongPress: widget.onLongPress,
+ // A swipe down throws the take away — past the slop it is no tap, so nothing is sent.
+ onVerticalDragStart: widget.onSwipeDown == null
+ ? null
+ : (_) => _swipe = 0,
+ onVerticalDragUpdate: widget.onSwipeDown == null
+ ? null
+ : (details) => _swipe += details.delta.dy,
+ onVerticalDragEnd: widget.onSwipeDown == null
+ ? null
+ : (details) {
+ _setPressed(false);
+ if (_swipe > 24 || (details.primaryVelocity ?? 0) > 300) {
+ HapticFeedback.mediumImpact();
+ widget.onSwipeDown!();
+ }
+ },
child: child,
);
}
diff --git a/mobile/lib/phone/voice_mic_fab.dart b/mobile/lib/phone/voice_mic_fab.dart
index ada5ab8b3..04ae6b6d1 100644
--- a/mobile/lib/phone/voice_mic_fab.dart
+++ b/mobile/lib/phone/voice_mic_fab.dart
@@ -31,11 +31,15 @@ class VoiceMicFab extends StatefulWidget {
required this.voice,
required this.session,
this.onSlipChanged,
+ this.working = false,
});
final VoiceInputController voice;
final TerminalSession session;
+ /// The agent is working — see [VoiceMicCore.working].
+ final bool working;
+
/// The thumb crossed in or out of the button mid-hold, in
/// [VoiceMicMode.holdToTalk]. Unused in the tap mode, which has no hold.
final ValueChanged<bool>? onSlipChanged;
@@ -149,6 +153,11 @@ class _VoiceMicFabState extends State<VoiceMicFab>
onHoldStart: action.onHoldStart,
onHoldFinish: action.onHoldFinish,
onSlipChanged: widget.onSlipChanged,
+ working: widget.working,
+ level: voice.level,
+ onSwipeDown: voice.status == VoiceInputStatus.listening
+ ? voice.clear
+ : null,
);
}
}
diff --git a/mobile/lib/phone/voice_mic_face.dart b/mobile/lib/phone/voice_mic_face.dart
index 8ce03ed28..314a21c7f 100644
--- a/mobile/lib/phone/voice_mic_face.dart
+++ b/mobile/lib/phone/voice_mic_face.dart
@@ -1,11 +1,14 @@
+import 'dart:async';
import 'dart:math' as math;
+import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'floating_glass.dart';
+import 'tty.dart';
import 'voice_mic_mode.dart';
/// What the mic says it will do when tapped.
@@ -16,8 +19,9 @@ enum VoiceMicFace {
/// The microphone is opening: tap to call it off.
starting,
- /// Recording: tap, and what was said is sent. The waveform in the capsule
- /// beside it is what shows it listening — see `voice_take_meter.dart`.
+ /// Recording: tap, and what was said is sent. Its bars move with the voice —
+ /// what ChatGPT's dictation and Siri do while they listen — and a swipe down
+ /// throws the take away.
listening,
/// Transcribing: nothing to tap until the words are back.
@@ -69,28 +73,29 @@ enum _Fill {
_Fill _fillFor(VoiceMicFace face, {required bool dead}) {
if (dead) return _Fill.glass;
+ // ⚠️ **Flat at rest; filled only while it records.** Over a terminal the mic is a quiet outline
+ // in the terminal's own colours — a lit circle sitting on the agent's prompt all day was the
+ // loudest thing on the screen. It fills (the terminal's red, a recording light) while a take is
+ // live, and that is the one moment it should be loud.
return switch (face) {
VoiceMicFace.cancelling => _Fill.warn,
- VoiceMicFace.busy || VoiceMicFace.off => _Fill.glass,
+ VoiceMicFace.listening || VoiceMicFace.starting => _Fill.accent,
+ VoiceMicFace.busy ||
+ VoiceMicFace.off ||
VoiceMicFace.talk ||
- VoiceMicFace.starting ||
- VoiceMicFace.listening ||
VoiceMicFace.sending ||
VoiceMicFace.sent ||
- VoiceMicFace.retry => _Fill.accent,
+ VoiceMicFace.retry => _Fill.glass,
};
}
/// The glyph for what a press will do.
-enum _Glyph { mic, micOff, send, cancel, check, dots }
+enum _Glyph { mic, micOff, send, cancel, check, dots, bars }
_Glyph _glyphFor(VoiceMicFace face) => switch (face) {
VoiceMicFace.talk || VoiceMicFace.starting => _Glyph.mic,
- // ⚠️ The arrow only in the tap mode, where the next tap IS the send — the
- // fill no longer says so, because the mic is filled at rest too. In
- // hold-to-talk the arrow would be a lie: nothing is sent by pressing, it is
- // sent by letting go, and the thumb never leaves the button to press again.
- VoiceMicFace.listening => micHoldsToTalk ? _Glyph.mic : _Glyph.send,
+ // Live bars, not an arrow: a still `↑` read as "send", not as "listening".
+ VoiceMicFace.listening => _Glyph.bars,
VoiceMicFace.busy => _Glyph.dots,
VoiceMicFace.sending || VoiceMicFace.retry => _Glyph.send,
VoiceMicFace.sent => _Glyph.check,
@@ -108,24 +113,39 @@ bool _spins(VoiceMicFace face) =>
/// The round, filled part of the mic: its colour, its glow, and the glyph for
/// what a press will do.
class VoiceMicCore extends StatelessWidget {
- const VoiceMicCore({super.key, required this.face, required this.dead});
-
- /// The visible circle's diameter — and the voice capsule's height, so the
- /// circle closes the capsule's right end. See `voice_status_pill.dart`.
- static const double diameter = 52;
+ const VoiceMicCore({
+ super.key,
+ required this.face,
+ required this.dead,
+ this.working = false,
+ this.level,
+ });
+
+ /// The microphone's level, 0–1, which the bars follow while it listens. Null draws them idling.
+ final ValueListenable<double>? level;
+
+ /// The visible circle's diameter: Siri's orb, near enough. Centred at the foot of Focus it is
+ /// the one control on the screen, the way a camera's shutter is — and it is held through a
+ /// whole sentence, so it is sized for a thumb, not a fingertip.
+ static const double diameter = 72;
final VoiceMicFace face;
/// Drawn as a button that cannot be pressed: frosted, not filled.
final bool dead;
+ /// The agent is working: the rim is a 2pt ring in the text's faint ink rather than a hairline —
+ /// at the thumb, whose turn it is.
+ final bool working;
+
static const Duration _morph = Duration(milliseconds: 300);
@override
Widget build(BuildContext context) {
final motion = !MediaQuery.disableAnimationsOf(context);
final fill = _fillFor(face, dead: dead);
- final ink = _inkFor(fill);
+ final tty = Tty.of(context);
+ final ink = _inkFor(fill, tty);
final glyph = _glyphFor(face);
return FloatingGlass(
child: AnimatedContainer(
@@ -133,7 +153,7 @@ class VoiceMicCore extends StatelessWidget {
curve: Curves.easeOutCubic,
width: diameter,
height: diameter,
- decoration: _decoration(fill),
+ decoration: _decoration(fill, tty),
child: Stack(
alignment: Alignment.center,
clipBehavior: Clip.none,
@@ -142,9 +162,7 @@ class VoiceMicCore extends StatelessWidget {
duration: const Duration(milliseconds: 200),
opacity: _spins(face) ? 1 : 0,
child: _BusyArc(
- color: fill == _Fill.accent
- ? Colors.white.withValues(alpha: 0.9)
- : AppPalette.accentOnSurface,
+ color: fill == _Fill.accent ? tty.theme.brightWhite : tty.text,
spin: motion && _spins(face),
),
),
@@ -160,6 +178,7 @@ class VoiceMicCore extends StatelessWidget {
ink,
bob: motion && face == VoiceMicFace.sending,
motion: motion,
+ level: level,
),
),
),
@@ -175,17 +194,10 @@ class VoiceMicCore extends StatelessWidget {
);
}
- Color _inkFor(_Fill fill) => switch (fill) {
- _Fill.accent => Colors.white,
- // White on the dark theme's bright amber is 2:1; dark ink there, white on
- // the light theme's deep one.
- _Fill.warn => AppTheme.pick(Colors.white, const Color(0xFF241800)),
- _Fill.glass =>
- face == VoiceMicFace.off
- ? AppPalette.textFaint
- : face == VoiceMicFace.busy
- ? AppPalette.accentOnSurface
- : AppPalette.textPrimary,
+ Color _inkFor(_Fill fill, Tty tty) => switch (fill) {
+ _Fill.accent => tty.theme.black,
+ _Fill.warn => tty.theme.black,
+ _Fill.glass => face == VoiceMicFace.off ? tty.dim : tty.text,
};
/// ⚠️ **Two different shadows for two different jobs, and the frosted one
@@ -193,37 +205,23 @@ class VoiceMicCore extends StatelessWidget {
/// casts a plain drop shadow instead: it floats over streaming output rather
/// than over a surface, and without one its edge disappears against every
/// dark line it happens to sit on.
- BoxDecoration _decoration(_Fill fill) {
+ /// Flat, the terminal's way: no gradient, no glow, no shadow — see [_fillFor].
+ BoxDecoration _decoration(_Fill fill, Tty tty) {
if (fill == _Fill.glass) {
return BoxDecoration(
shape: BoxShape.circle,
- color: floatingButtonFill,
- border: Border.all(color: floatingButtonRim),
- // ⚠️ Kept light: a box shadow paints under the WHOLE circle, and the
- // fill is not opaque — a heavy one showed through as a dark disc.
- boxShadow: floatingButtonShadow,
+ // The terminal's own ground, near-opaque, so the glyph reads over any line of output.
+ color: tty.ground,
+ border: working
+ ? Border.all(color: tty.faint, width: 2)
+ : Border.all(color: tty.dim, width: 1.5),
);
}
- final tint = fill == _Fill.warn ? AppPalette.warn : AppPalette.accent;
+ // Recording, the face is the send button: green, the colour of go. Red stays on the bar's
+ // `●` and its clock, where it means "recording" and nothing else.
return BoxDecoration(
shape: BoxShape.circle,
- gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [Color.lerp(tint, Colors.white, 0.18)!, tint],
- ),
- border: Border.all(color: Colors.white.withValues(alpha: 0.28)),
- boxShadow: [
- BoxShadow(color: tint.withValues(alpha: 0.4), blurRadius: 12),
- // The lift, under the glow. The glow does not separate the circle from
- // the text behind it: it is the same brightness as the accent the
- // terminal itself uses.
- BoxShadow(
- color: Colors.black.withValues(alpha: 0.35),
- blurRadius: 10,
- offset: const Offset(0, 3),
- ),
- ],
+ color: fill == _Fill.warn ? tty.yellow : tty.green,
);
}
@@ -232,8 +230,9 @@ class VoiceMicCore extends StatelessWidget {
Color ink, {
required bool bob,
required bool motion,
+ ValueListenable<double>? level,
}) {
- Icon icon(IconData data) => Icon(data, size: 25, color: ink);
+ Icon icon(IconData data) => Icon(data, size: 30, color: ink);
return switch (glyph) {
_Glyph.mic => icon(LucideIcons.mic300),
_Glyph.micOff => icon(LucideIcons.micOff300),
@@ -241,6 +240,7 @@ class VoiceMicCore extends StatelessWidget {
_Glyph.cancel => icon(LucideIcons.x300),
_Glyph.check => icon(LucideIcons.check300),
_Glyph.dots => _Dots(color: ink, animate: motion),
+ _Glyph.bars => _LiveBars(color: ink, level: level, animate: motion),
};
}
@@ -323,7 +323,7 @@ class _BusyArcState extends State<_BusyArc>
child: RotationTransition(
turns: _turn,
child: CustomPaint(
- size: const Size.square(44),
+ size: const Size.square(VoiceMicCore.diameter - 14),
painter: _ArcPainter(widget.color),
),
),
@@ -441,6 +441,99 @@ class _DotsState extends State<_Dots> with SingleTickerProviderStateMixin {
);
}
+/// Five bars that move with the voice while the mic listens: short at silence, tall when loud,
+/// each on its own phase so they never move as one block. They idle gently when there is no
+/// level to follow, so the mic never looks frozen while it is recording.
+class _LiveBars extends StatefulWidget {
+ const _LiveBars({
+ required this.color,
+ required this.level,
+ required this.animate,
+ });
+
+ final Color color;
+ final ValueListenable<double>? level;
+ final bool animate;
+
+ @override
+ State<_LiveBars> createState() => _LiveBarsState();
+}
+
+class _LiveBarsState extends State<_LiveBars>
+ with SingleTickerProviderStateMixin {
+ late final AnimationController _wave = AnimationController(
+ vsync: this,
+ duration: const Duration(milliseconds: 1000),
+ );
+
+ /// The level, eased toward what the microphone reports, so the bars glide.
+ double _shown = 0;
+
+ static const _weights = [0.55, 0.85, 1.0, 0.8, 0.5];
+ static const double _bar = 4;
+ static const double _gap = 4;
+ static const double _low = 5;
+ static const double _high = 30;
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.animate) unawaited(_wave.repeat());
+ }
+
+ @override
+ void didUpdateWidget(_LiveBars old) {
+ super.didUpdateWidget(old);
+ if (widget.animate && !_wave.isAnimating) unawaited(_wave.repeat());
+ if (!widget.animate) _wave.stop();
+ }
+
+ @override
+ void dispose() {
+ _wave.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => RepaintBoundary(
+ child: AnimatedBuilder(
+ animation: _wave,
+ builder: (context, _) {
+ final target = (widget.level?.value ?? 0.15).clamp(0.0, 1.0);
+ _shown += (target - _shown) * 0.35;
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ for (var i = 0; i < _weights.length; i++) ...[
+ if (i > 0) const SizedBox(width: _gap),
+ Container(
+ width: _bar,
+ height: _heightOf(i),
+ decoration: BoxDecoration(
+ color: widget.color,
+ borderRadius: BorderRadius.circular(_bar / 2),
+ ),
+ ),
+ ],
+ ],
+ );
+ },
+ ),
+ );
+
+ double _heightOf(int i) {
+ // A breath of motion always, more of it the louder the voice.
+ final phase = math.sin(2 * math.pi * (_wave.value + i * 0.18));
+ final swing = 0.18 + 0.82 * _shown;
+ final amount = (_weights[i] * swing * (0.75 + 0.25 * phase)).clamp(
+ 0.0,
+ 1.0,
+ );
+ return _low + (_high - _low) * amount;
+ }
+}
+
/// The send arrow, nudging upward while the words are on their way.
class _Bob extends StatefulWidget {
const _Bob({required this.active, required this.child});
diff --git a/mobile/lib/phone/voice_status_pill.dart b/mobile/lib/phone/voice_status_pill.dart
index 3564d0615..6134503dd 100644
--- a/mobile/lib/phone/voice_status_pill.dart
+++ b/mobile/lib/phone/voice_status_pill.dart
@@ -10,7 +10,6 @@ import 'package:harness_mobile/shared/widgets/pulse.dart';
import 'voice_input_controller.dart';
import 'voice_mic_action.dart';
-import 'voice_mic_face.dart';
import 'voice_mic_mode.dart';
import 'voice_take_meter.dart';
@@ -62,8 +61,9 @@ class VoiceStatusPill extends StatefulWidget {
/// stands on its own.
final double micClearance;
- /// The body's least height: the mic's circle, so the circle closes its end.
- static const double height = VoiceMicCore.diameter;
+ /// The body's least height. It stood beside the mic once and took the circle's height to close
+ /// round it; it stands over the mic now, on its own.
+ static const double height = 52;
@override
State<VoiceStatusPill> createState() => _VoiceStatusPillState();
diff --git a/mobile/lib/phone/welcome/connect_code.dart b/mobile/lib/phone/welcome/connect_code.dart
new file mode 100644
index 000000000..dd0b5379b
--- /dev/null
+++ b/mobile/lib/phone/welcome/connect_code.dart
@@ -0,0 +1,78 @@
+/// What the desktop app's **Add phone** QR says — the contract between the two apps:
+///
+/// ```
+/// https://harness.autonomous.ai/pair#e=<email>&m=<machineId>&c=<one-time pairing code>&h=<sign-in code>
+/// ```
+///
+/// A link, so the Camera app lands somewhere sensible: `/pair` on the website says to scan it from
+/// the Harness app (`/connect` there is an older, unrelated page). **Everything is in the
+/// fragment**, which a browser never sends to the server: the pairing code is the out-of-band
+/// secret end-to-end encryption rests on, and it must not reach our backend even when the link is
+/// opened in Safari. `m`, `c` and `h` are optional: a QR with only `e`
+/// still signs the phone in to the right account, by an emailed code.
+class ConnectCode {
+ const ConnectCode({
+ required this.email,
+ this.machineId,
+ this.pairCode,
+ this.signIn,
+ });
+
+ final String email;
+ final String? machineId;
+
+ /// The one-time code the computer's daemon pairs with (its live-code CPace pairing), so no remote
+ /// password is typed. Held until the phone is signed in.
+ final String? pairCode;
+
+ /// The one-time code that signs the phone in with no emailed code — minted
+ /// for this QR by the computer's own sign-in, good for about a minute, and
+ /// spent by the first phone to redeem it (`AppNotifier.signInWithScan`).
+ final String? signIn;
+
+ static const host = 'harness.autonomous.ai';
+ static const path = '/pair';
+
+ /// The code a scanned string holds, or null when it is not one of ours.
+ static ConnectCode? parse(String raw) {
+ final uri = Uri.tryParse(raw.trim());
+ if (uri == null ||
+ uri.scheme != 'https' ||
+ uri.host != host ||
+ uri.path != path) {
+ return null;
+ }
+ final fields = Uri.splitQueryString(uri.fragment);
+ final email = fields['e']?.trim() ?? '';
+ if (!email.contains('@')) return null;
+ String? present(String key) {
+ final value = fields[key]?.trim();
+ return value == null || value.isEmpty ? null : value;
+ }
+
+ return ConnectCode(
+ email: email,
+ machineId: present('m'),
+ pairCode: present('c'),
+ signIn: present('h'),
+ );
+ }
+
+ /// The link for [email] — what the desktop app encodes, and what tests scan.
+ static String link(
+ String email, {
+ String? machineId,
+ String? pairCode,
+ String? signIn,
+ }) => Uri(
+ scheme: 'https',
+ host: host,
+ path: path,
+ fragment: [
+ 'e=${Uri.encodeQueryComponent(email)}',
+ if (machineId != null) 'm=${Uri.encodeQueryComponent(machineId)}',
+ if (pairCode != null) 'c=${Uri.encodeQueryComponent(pairCode)}',
+ if (signIn != null) 'h=${Uri.encodeQueryComponent(signIn)}',
+ ].join('&'),
+ ).toString();
+}
diff --git a/mobile/lib/phone/welcome/connect_computer.dart b/mobile/lib/phone/welcome/connect_computer.dart
new file mode 100644
index 000000000..07fc58a71
--- /dev/null
+++ b/mobile/lib/phone/welcome/connect_computer.dart
@@ -0,0 +1,494 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+import 'how_it_works.dart';
+
+/// The commands that put Harness on a computer, in order — the README's "Get started".
+const kSetUpCommands = [
+ 'curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash',
+ 'harness login',
+ 'harness remote-password set',
+ 'harness start',
+];
+
+/// Where the desktop app is downloaded.
+const kDesktopAppUrl = 'https://harness.autonomous.ai/desktop';
+
+/// How to put Harness on a computer, for someone who has not — the one idea a phone app for agents
+/// has to get across first: **the agents run on your computer, and the phone connects to it.**
+///
+/// Two ways, the app or a terminal, each with its steps to copy. Signed in, the page also watches
+/// for the computer to appear (every few seconds, since nothing tells the phone), and the app moves
+/// on by itself the moment it does. Signed out, it is the "New here?" page behind the welcome.
+class ConnectComputerPage extends StatefulWidget {
+ const ConnectComputerPage({
+ super.key,
+ required this.notifier,
+ this.signedIn = true,
+ this.onBack,
+ this.onTrySample,
+ });
+
+ final AppNotifier notifier;
+
+ /// Watch for the computer and say whose account it must be signed in to.
+ final bool signedIn;
+
+ /// Shown as `‹ Back` when set.
+ final VoidCallback? onBack;
+
+ /// Opens the sample; see `PhoneWelcome.onTrySample`.
+ final Future<Object?> Function(BuildContext context)? onTrySample;
+
+ @override
+ State<ConnectComputerPage> createState() => _ConnectComputerPageState();
+}
+
+class _ConnectComputerPageState extends State<ConnectComputerPage> {
+ Timer? _watch;
+ String? _copied;
+ Timer? _copiedTimer;
+
+ /// Which way the steps are shown: the terminal first — who this is for lives in one — or the
+ /// Mac app.
+ bool _terminal = true;
+
+ /// The steps, sent to [email] through the phone's own Mail — there is no server doing it, and a
+ /// message in your own inbox is where the computer will find it.
+ Future<void> _emailSteps(String? email) async {
+ final body = [
+ 'Set up Harness on your computer:',
+ '',
+ 'Mac app: $kDesktopAppUrl',
+ ' Sign in${email == null ? '' : ' with $email'}, then Machines → this computer → Set password.',
+ '',
+ 'Or, in a terminal:',
+ for (final line in kSetUpCommands) ' $line',
+ '',
+ 'Then open Harness on your phone — it finds the computer by itself.',
+ ].join('\n');
+ final uri = Uri(
+ scheme: 'mailto',
+ path: email ?? '',
+ query: _mailQuery({
+ 'subject': 'Set up Harness on your computer',
+ 'body': body,
+ }),
+ );
+ try {
+ final opened = await launchUrl(uri);
+ if (!opened && mounted) _copy('commands', body);
+ } on Exception {
+ if (mounted) _copy('commands', body);
+ }
+ }
+
+ /// `mailto:` wants `%20`, not `+`, between words.
+ static String _mailQuery(Map<String, String> fields) => fields.entries
+ .map((e) => '${e.key}=${Uri.encodeComponent(e.value)}')
+ .join('&');
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.signedIn) {
+ // Nothing pushes a new machine to the phone: ask again every few seconds while this is up.
+ _watch = Timer.periodic(const Duration(seconds: 5), (_) {
+ if (mounted) unawaited(widget.notifier.refreshMachines());
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ _watch?.cancel();
+ _copiedTimer?.cancel();
+ super.dispose();
+ }
+
+ void _copy(String what, String text) {
+ unawaited(Clipboard.setData(ClipboardData(text: text)));
+ HapticFeedback.lightImpact();
+ _copiedTimer?.cancel();
+ setState(() => _copied = what);
+ _copiedTimer = Timer(const Duration(seconds: 2), () {
+ if (mounted) setState(() => _copied = null);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final email = widget.notifier.currentUser?.email;
+ final account = email == null ? 'the same account' : email;
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (widget.onBack != null)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(onPressed: widget.onBack),
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 16,
+ Tty.origin,
+ 24,
+ ),
+ children: [
+ TtyText(
+ 'Set up your computer',
+ size: 24,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'Your agents run on your computer — this phone is the '
+ 'remote. It takes about two minutes, once.',
+ style: tty.style(size: TtySize.row, color: tty.faint),
+ ),
+ const SizedBox(height: 24),
+ // Signed in: say so — and that the page is watching — where it is read first.
+ if (widget.signedIn) ...[
+ _Watching(account: email),
+ const SizedBox(height: 16),
+ ],
+ // Most people meet this page on the phone, away from the computer: the one thing
+ // to do from here is send the steps to where they will be read.
+ TtyPrimaryButton(
+ label: 'Email me the setup link',
+ onPressed: () => unawaited(_emailSteps(email)),
+ ),
+ const SizedBox(height: 6),
+ Center(
+ child: TtyText(
+ 'Open it on your Mac or Linux computer.',
+ size: TtySize.meta,
+ color: tty.faint,
+ ),
+ ),
+ const SizedBox(height: 32),
+ TtyText(
+ 'Already at your computer?',
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 12),
+ _Choice(
+ options: const ['Terminal', 'Mac app'],
+ selected: _terminal ? 0 : 1,
+ onSelected: (index) =>
+ setState(() => _terminal = index == 0),
+ ),
+ const SizedBox(height: 14),
+ if (!_terminal) ...[
+ _CopyLine(
+ text: 'harness.autonomous.ai/desktop',
+ copied: _copied == 'link',
+ onCopy: () => _copy('link', kDesktopAppUrl),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'Download it, sign in with $account, then open Machines '
+ '(your computers) → this Mac → Set password. That is '
+ 'the phone password you type here next.',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ ] else ...[
+ _CommandBlock(
+ lines: kSetUpCommands,
+ copied: _copied == 'commands',
+ onCopy: () =>
+ _copy('commands', kSetUpCommands.join('\n')),
+ ),
+ const SizedBox(height: 10),
+ Text.rich(
+ TextSpan(
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ children: [
+ TextSpan(
+ text: 'harness login',
+ style: tty.style(
+ size: TtySize.meta,
+ color: tty.green,
+ ),
+ ),
+ TextSpan(
+ text: ' signs the computer in to $account. ',
+ ),
+ TextSpan(
+ text: 'remote-password',
+ style: tty.style(
+ size: TtySize.meta,
+ color: tty.green,
+ ),
+ ),
+ const TextSpan(
+ text:
+ ' sets your phone password — what this '
+ 'phone unlocks it with. It never leaves your '
+ 'devices.',
+ ),
+ ],
+ ),
+ ),
+ ],
+ const SizedBox(height: 32),
+ Center(
+ child: TtyTextButton(
+ label: 'How Harness works',
+ onPressed: () => unawaited(openHowItWorks(context)),
+ ),
+ ),
+ if (widget.onTrySample != null) ...[
+ const SizedBox(height: 16),
+ Center(
+ child: TtyTextButton(
+ label: widget.signedIn
+ ? 'Try the sample while you wait'
+ : 'Try the sample',
+ onPressed: () =>
+ unawaited(widget.onTrySample!(context)),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// Two or three ways to do one thing, one chosen — iOS's segmented control, drawn flat.
+class _Choice extends StatelessWidget {
+ const _Choice({
+ required this.options,
+ required this.selected,
+ required this.onSelected,
+ });
+
+ final List<String> options;
+ final int selected;
+ final ValueChanged<int> onSelected;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ height: 40,
+ padding: const EdgeInsets.all(3),
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Row(
+ children: [
+ for (var i = 0; i < options.length; i++)
+ Expanded(
+ child: Semantics(
+ button: true,
+ selected: i == selected,
+ label: options[i],
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onSelected(i);
+ },
+ child: Container(
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ // The chosen one lifts off the track, as iOS draws it.
+ color: i == selected
+ ? Color.alphaBlend(
+ tty.text.withValues(alpha: 0.2),
+ tty.ground,
+ )
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: TtyText(
+ options[i],
+ size: TtySize.meta,
+ weight: i == selected ? FontWeight.w600 : FontWeight.w400,
+ color: i == selected ? tty.text : tty.faint,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// One line to copy — a link — with `Copy` at its end.
+class _CopyLine extends StatelessWidget {
+ const _CopyLine({
+ required this.text,
+ required this.copied,
+ required this.onCopy,
+ });
+
+ final String text;
+ final bool copied;
+ final VoidCallback onCopy;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ padding: const EdgeInsets.only(left: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyText(text, size: TtySize.meta, color: tty.text),
+ ),
+ TtyTextButton(
+ label: copied ? 'Copied' : 'Copy',
+ color: copied ? tty.green : null,
+ onPressed: onCopy,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Commands as a terminal would show them, `$ ` in front of each, and `Copy all` under them.
+class _CommandBlock extends StatelessWidget {
+ const _CommandBlock({
+ required this.lines,
+ required this.copied,
+ required this.onCopy,
+ });
+
+ final List<String> lines;
+ final bool copied;
+ final VoidCallback onCopy;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ padding: const EdgeInsets.fromLTRB(12, 10, 0, 0),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final line in lines)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 6, right: 12),
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: r'$ ',
+ style: tty.style(color: tty.green, size: TtySize.meta),
+ ),
+ TextSpan(
+ text: line,
+ style: tty.style(size: TtySize.meta),
+ ),
+ ],
+ ),
+ ),
+ ),
+ Align(
+ alignment: Alignment.centerRight,
+ child: TtyTextButton(
+ label: copied ? 'Copied' : 'Copy all',
+ color: copied ? tty.green : null,
+ onPressed: onCopy,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// `Looking for your computer…` with a terminal spinner — the page is watching.
+class _Watching extends StatefulWidget {
+ const _Watching({this.account});
+
+ /// Whose computer it is waiting for.
+ final String? account;
+
+ @override
+ State<_Watching> createState() => _WatchingState();
+}
+
+class _WatchingState extends State<_Watching> {
+ // The terminal's oldest spinner — every monospace face has these four.
+ static const _frames = ['|', '/', '-', r'\'];
+ int _frame = 0;
+ Timer? _tick;
+
+ @override
+ void initState() {
+ super.initState();
+ _tick = Timer.periodic(const Duration(milliseconds: 150), (_) {
+ if (mounted) setState(() => _frame = (_frame + 1) % _frames.length);
+ });
+ }
+
+ @override
+ void dispose() {
+ _tick?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Row(
+ children: [
+ TtyText(_frames[_frame], color: tty.green, size: TtySize.row),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ widget.account == null
+ ? 'Waiting for your computer…'
+ : 'Signed in as ${widget.account}. Waiting for your '
+ 'computer…',
+ style: tty.style(size: TtySize.meta, color: tty.text),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/focus_hints.dart b/mobile/lib/phone/welcome/focus_hints.dart
new file mode 100644
index 000000000..be492b818
--- /dev/null
+++ b/mobile/lib/phone/welcome/focus_hints.dart
@@ -0,0 +1,219 @@
+import 'dart:async';
+import 'dart:io' show Platform;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/core/harness_file_store.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// Whether Focus's first-time hints have been seen — once per install.
+class FocusHintsSeen {
+ FocusHintsSeen({LocalKeyValueStore? storage})
+ : _storage = storage ?? HarnessFileStore.shared;
+
+ static const _key = 'phone_focus_hints_v1';
+ final LocalKeyValueStore _storage;
+
+ /// Shared by every Focus page, so a second page opened before the first read lands does not
+ /// show the hints twice.
+ static final shared = FocusHintsSeen();
+
+ bool? _seen;
+
+ Future<bool> seen() async {
+ if (_seen case final seen?) return seen;
+ // Under `flutter test` the shared store is the real one in the home directory: never read or
+ // write it there. A test that wants the hints hands [FocusHints] a store of its own.
+ if (identical(this, shared) &&
+ Platform.environment.containsKey('FLUTTER_TEST')) {
+ return _seen = true;
+ }
+ try {
+ _seen = await _storage.read(_key) == 'yes';
+ } on Exception {
+ _seen = true; // No memory: never nag.
+ }
+ return _seen!;
+ }
+
+ /// Show them again, on the next Focus — Settings ▸ Show the tips again.
+ Future<void> forget() async {
+ _seen = false;
+ try {
+ await _storage.delete(_key);
+ } on Exception {
+ // Back for this run at least.
+ }
+ }
+
+ Future<void> markSeen() async {
+ _seen = true;
+ try {
+ await _storage.write(_key, 'yes');
+ } on Exception {
+ // Seen for this run at least.
+ }
+ }
+}
+
+/// Focus's first-time hints: the three things a phone can do here that nothing on screen says —
+/// swipe right for your harnesses, swipe left for a new one, the mic to talk. Laid over the
+/// terminal once, in the terminal's own type; any touch puts them away for good.
+///
+/// ```
+/// tap the title ─ rename, restart, paste…
+///
+/// → swipe right swipe left ←
+/// all your harnesses start a new one
+///
+/// talk to it
+/// ( mic )
+/// ```
+class FocusHints extends StatefulWidget {
+ const FocusHints({
+ super.key,
+ required this.micBottom,
+ this.store,
+ this.onDone,
+ });
+
+ /// Called once, as the hints go — the moment to ask for what the next step needs (the
+ /// notification permission: a harness asking you something is what a notice is for).
+ final VoidCallback? onDone;
+
+ /// Where the mic's centre sits, measured up from the bottom of this box.
+ final double micBottom;
+
+ final FocusHintsSeen? store;
+
+ @override
+ State<FocusHints> createState() => _FocusHintsState();
+}
+
+class _FocusHintsState extends State<FocusHints> {
+ bool _show = false;
+
+ FocusHintsSeen get _store => widget.store ?? FocusHintsSeen.shared;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(
+ _store.seen().then((seen) {
+ if (!mounted || seen) return;
+ setState(() => _show = true);
+ }),
+ );
+ }
+
+ void _dismiss() {
+ if (!_show) return;
+ HapticFeedback.selectionClick();
+ setState(() => _show = false);
+ unawaited(_store.markSeen());
+ widget.onDone?.call();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (!_show) return const SizedBox.shrink();
+ final tty = Tty.of(context);
+ Widget hint(String big, String small, {TextAlign align = TextAlign.left}) =>
+ Column(
+ crossAxisAlignment: align == TextAlign.right
+ ? CrossAxisAlignment.end
+ : align == TextAlign.center
+ ? CrossAxisAlignment.center
+ : CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TtyText(
+ big,
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ color: tty.green,
+ ),
+ const SizedBox(height: 2),
+ TtyText(small, size: TtySize.meta, color: tty.text),
+ ],
+ );
+ // ⚠️ **The touch goes THROUGH.** A hint that swallowed the swipe it teaches ("swipe right")
+ // made the first swipe do nothing. The listener only notices the finger going down — the hints
+ // go — and the terminal under it gets the same touch and does what was taught.
+ return Listener(
+ behavior: HitTestBehavior.translucent,
+ onPointerDown: (_) => _dismiss(),
+ child: IgnorePointer(
+ child: Semantics(
+ label:
+ 'Tips: swipe right for all your harnesses, swipe left to start '
+ 'one, tap the title for its menu, the mic to talk.',
+ child: Material(
+ color: tty.ground.withValues(alpha: 0.95),
+ child: Stack(
+ children: [
+ // Under the title, never on it: the title is three rows tall.
+ Positioned(
+ left: 16,
+ top: 4 * tty.row + 14,
+ child: hint('↑ tap the title', 'rename, restart, paste…'),
+ ),
+ Positioned(
+ left: 16,
+ right: 16,
+ top: 0,
+ bottom: 0,
+ child: Row(
+ children: [
+ Expanded(
+ child: hint('→ swipe right', 'all your harnesses'),
+ ),
+ Expanded(
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: hint(
+ 'swipe left ←',
+ 'start a new one',
+ align: TextAlign.right,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: widget.micBottom + 44,
+ child: Center(
+ child: hint(
+ 'talk to it ↓',
+ 'tap the mic, speak, tap again to send',
+ align: TextAlign.center,
+ ),
+ ),
+ ),
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 12,
+ child: Center(
+ child: TtyText(
+ 'touch anywhere to start',
+ size: TtySize.meta,
+ color: tty.faint,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/how_it_works.dart b/mobile/lib/phone/welcome/how_it_works.dart
new file mode 100644
index 000000000..a5d9c97ee
--- /dev/null
+++ b/mobile/lib/phone/welcome/how_it_works.dart
@@ -0,0 +1,139 @@
+import 'package:flutter/material.dart';
+
+import '../phone_navigation.dart';
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// Opens [HowItWorksPage].
+Future<void> openHowItWorks(BuildContext context) =>
+ Navigator.of(context).push(phoneRoute((_) => const HowItWorksPage()));
+
+/// The five words Harness uses and the gestures nothing on screen spells out — in one page, in
+/// plain language, reachable from Settings, from Find (`help`) and from setting up a computer.
+class HowItWorksPage extends StatelessWidget {
+ const HowItWorksPage({super.key});
+
+ static const _concepts = [
+ (
+ 'Computer',
+ 'Where your agents actually run — a Mac or a Linux machine with Harness '
+ 'on it. This phone connects to it; nothing runs on the phone.',
+ ),
+ ('Agent', 'The AI that does the work: Claude Code, Codex, and others.'),
+ (
+ 'Harness',
+ 'One agent working in one project on one computer — a live terminal you '
+ 'can watch and talk to. Start as many as you like; they keep going '
+ 'when you close the app.',
+ ),
+ (
+ 'Project',
+ 'The folder a harness works in. In a git project it can take its own '
+ 'branch in a new worktree, so two harnesses never trip over each other.',
+ ),
+ (
+ 'Phone password',
+ 'Unlocks one computer from this phone, once. It sets up an end-to-end '
+ 'encrypted link and never leaves your devices.',
+ ),
+ ];
+
+ static const _gestures = [
+ ('swipe right', 'all your harnesses'),
+ ('swipe left', 'start a new harness'),
+ ('tap the title', 'rename, restart, paste'),
+ ('hold the title', 'back to the last harness'),
+ ('esc', 'stop what it is doing'),
+ ('the mic', 'talk to the harness on screen'),
+ ];
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 8,
+ Tty.origin,
+ 32,
+ ),
+ children: [
+ TtyText(
+ 'How Harness works',
+ size: 24,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 20),
+ for (final (word, meaning) in _concepts) ...[
+ TtyText(
+ word,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ color: tty.green,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ meaning,
+ style: tty.style(size: TtySize.meta, color: tty.text),
+ ),
+ const SizedBox(height: 18),
+ ],
+ const SizedBox(height: 8),
+ TtyText(
+ 'On the phone',
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ const SizedBox(height: 10),
+ for (final (gesture, does) in _gestures)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 128,
+ child: TtyText(
+ gesture,
+ size: TtySize.meta,
+ color: tty.green,
+ ),
+ ),
+ Expanded(
+ child: Text(
+ does,
+ style: tty.style(size: TtySize.meta),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'When a harness asks you something, its answers appear as '
+ 'buttons at the bottom of the screen. Tap one, or just say '
+ '"yes", "no" or the number.',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/how_it_works_video.dart b/mobile/lib/phone/welcome/how_it_works_video.dart
new file mode 100644
index 000000000..05cd1956e
--- /dev/null
+++ b/mobile/lib/phone/welcome/how_it_works_video.dart
@@ -0,0 +1,105 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:video_player/video_player.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// The recording of the app — a harness at work, one asking and answered by voice, a new one
+/// started — played from the set-up page ("See how it works"), for someone not at their computer.
+/// In place of an interactive demo: 30 seconds, bundled, so it plays offline.
+const kHowItWorksVideo = 'assets/video/how_it_works.mp4';
+
+class HowItWorksVideoPage extends StatefulWidget {
+ const HowItWorksVideoPage({super.key, this.controller});
+
+ /// Stands in for the player in tests. Null plays [kHowItWorksVideo].
+ final VideoPlayerController? controller;
+
+ @override
+ State<HowItWorksVideoPage> createState() => _HowItWorksVideoPageState();
+}
+
+class _HowItWorksVideoPageState extends State<HowItWorksVideoPage> {
+ late final VideoPlayerController _video =
+ widget.controller ?? VideoPlayerController.asset(kHowItWorksVideo);
+ bool _ready = false;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_start());
+ }
+
+ Future<void> _start() async {
+ try {
+ await _video.initialize();
+ } catch (_) {
+ return;
+ }
+ if (!mounted) return;
+ setState(() => _ready = true);
+ await _video.play();
+ }
+
+ @override
+ void dispose() {
+ if (widget.controller == null) unawaited(_video.dispose());
+ super.dispose();
+ }
+
+ /// A tap pauses, plays, or — at the end — plays it again.
+ void _toggle() {
+ final value = _video.value;
+ if (value.isPlaying) {
+ unawaited(_video.pause());
+ } else {
+ if (value.position >= value.duration) {
+ unawaited(_video.seekTo(Duration.zero));
+ }
+ unawaited(_video.play());
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ ),
+ Expanded(
+ child: Center(
+ child: !_ready
+ ? const SizedBox.shrink()
+ : GestureDetector(
+ onTap: _toggle,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(14),
+ child: AspectRatio(
+ aspectRatio: _video.value.aspectRatio,
+ child: VideoPlayer(_video),
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/pairing_with_code.dart b/mobile/lib/phone/welcome/pairing_with_code.dart
new file mode 100644
index 000000000..36c8d888e
--- /dev/null
+++ b/mobile/lib/phone/welcome/pairing_with_code.dart
@@ -0,0 +1,104 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// The moment after signing in from a scanned "Add phone" QR: the phone pairs with the computer by
+/// the QR's one-time code ([AppNotifier.connectWithCode]) — no password — while this says so.
+///
+/// ```
+/// Connecting to MacBook Pro…
+/// Keep “Add phone” open on your Mac.
+/// ```
+///
+/// On success the computer unlocks and the home screen moves on by itself. On failure the code is
+/// spent: the reason is shown, with the computer's password as the way on.
+class PairingWithCode extends StatefulWidget {
+ const PairingWithCode({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ required this.code,
+ });
+
+ final AppNotifier notifier;
+ final String machineId;
+ final String code;
+
+ @override
+ State<PairingWithCode> createState() => _PairingWithCodeState();
+}
+
+class _PairingWithCodeState extends State<PairingWithCode> {
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_pair());
+ }
+
+ Future<void> _pair() async {
+ final error = await widget.notifier.connectWithCode(
+ widget.machineId,
+ widget.code,
+ );
+ if (!mounted) return;
+ if (error == null) {
+ HapticFeedback.mediumImpact();
+ widget.notifier.pendingPairing = null;
+ return;
+ }
+ setState(() => _error = error);
+ }
+
+ /// The code is spent either way: the computer's password form is what is left.
+ void _usePassword() => widget.notifier.dropPendingPairing();
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final name =
+ widget.notifier.machineStates[widget.machineId]?.machine.displayName ??
+ 'your computer';
+ final error = _error;
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 48, Tty.origin, 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ error == null ? 'Connecting to\n$name…' : 'Couldn’t connect',
+ style: tty
+ .style(size: TtySize.display, weight: FontWeight.w600)
+ .copyWith(height: 34 / 28, letterSpacing: -0.6),
+ ),
+ const SizedBox(height: 12),
+ TtyText(
+ error ?? 'Keep “Add phone” open on your Mac.',
+ color: error == null ? tty.faint : tty.red,
+ size: TtySize.row,
+ ),
+ const Spacer(),
+ if (error != null)
+ TtyPrimaryButton(
+ label: 'Use its password instead',
+ onPressed: _usePassword,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/phone_boot.dart b/mobile/lib/phone/welcome/phone_boot.dart
new file mode 100644
index 000000000..0f584eb8a
--- /dev/null
+++ b/mobile/lib/phone/welcome/phone_boot.dart
@@ -0,0 +1,33 @@
+import 'package:flutter/material.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// The phone while the app starts: the terminal's ground and the mark, nothing to read — a second
+/// at most, and the welcome or the last harness follows. No spinner: nothing moves while nothing is
+/// asked of the person.
+class PhoneBoot extends StatelessWidget {
+ const PhoneBoot({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return ColoredBox(
+ color: tty.ground,
+ child: Center(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TtyText('harness', size: TtySize.title, weight: FontWeight.w600),
+ Container(
+ width: 9,
+ height: 18,
+ margin: const EdgeInsets.only(left: 2),
+ color: tty.green,
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/phone_welcome.dart b/mobile/lib/phone/welcome/phone_welcome.dart
new file mode 100644
index 000000000..a74ef18fd
--- /dev/null
+++ b/mobile/lib/phone/welcome/phone_welcome.dart
@@ -0,0 +1,546 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+import 'connect_code.dart';
+import 'scan_to_connect.dart';
+import 'set_up_computer.dart';
+
+/// The phone's first screen, signed out: what Harness is in one breath, and one question anyone
+/// can answer — is Harness on your computer?
+///
+/// ```
+/// harness▌
+///
+/// Claude Code and Codex
+/// run on your computer.
+/// Drive them from here.
+///
+/// Is Harness on your computer?
+/// ┌──────────────────────────────┐
+/// │ Yes — scan to connect › │
+/// └──────────────────────────────┘
+/// ┌──────────────────────────────┐
+/// │ Not yet — set it up › │
+/// └──────────────────────────────┘
+/// ```
+///
+/// **Yes** scans the code the desktop app shows ([ScanToConnectPage]), and the scan signs the phone
+/// in: the QR carries a one-time code the computer's own sign-in minted
+/// ([AppNotifier.signInWithScan]). A QR without one — an older computer — or one that has expired
+/// names the account instead: the email is filled in and its code sent, so signing in is the four
+/// digits (`viewer/email_code_api.dart`, no browser). **Not yet** gets Harness onto the computer ([SetUpComputerPage]). Both
+/// buttons weigh the same: the question decides, not us. Nothing else is on the screen — no
+/// pretend agents, no diagram — for someone who has never seen Harness.
+class PhoneWelcome extends StatefulWidget {
+ const PhoneWelcome({
+ super.key,
+ required this.notifier,
+ this.onTrySample,
+ this.sendCode,
+ this.signIn,
+ this.signInWithScan,
+ this.scanCamera,
+ this.loadDownloads,
+ });
+
+ /// Stands in for the desktop release manifest on the set-up page, in tests and renders.
+ final DesktopDownloadsLoader? loadDownloads;
+
+ /// Stands in for the camera on the scan page, in tests and renders. Null opens the real one.
+ final Widget? scanCamera;
+
+ final AppNotifier notifier;
+
+ /// Stand-ins for the account service, for tests and renders. Null uses [notifier]'s.
+ final Future<void> Function(String email)? sendCode;
+ final Future<void> Function(String email, String code)? signIn;
+ final Future<void> Function(String code)? signInWithScan;
+
+ /// Opens the offline sample; completes when it is left, with `'set-up'` when it was left to set
+ /// up a real computer. Null leaves the way out.
+ final Future<Object?> Function(BuildContext context)? onTrySample;
+
+ @override
+ State<PhoneWelcome> createState() => _PhoneWelcomeState();
+}
+
+enum _Step { hello, setUp, scan, email, code }
+
+class _PhoneWelcomeState extends State<PhoneWelcome> {
+ _Step _step = _Step.hello;
+ final _email = TextEditingController();
+ final _code = TextEditingController();
+ final _emailFocus = FocusNode();
+ final _codeFocus = FocusNode();
+ String? _sentTo;
+ bool _busy = false;
+
+ /// Between a scan and the session it signs in: the scan page says so.
+ bool _signingInWithScan = false;
+ String? _error;
+ int _resendIn = 0;
+ Timer? _resendTimer;
+
+ static const _codeLength = 4;
+ static const _resendAfter = 30;
+
+ @override
+ void dispose() {
+ _resendTimer?.cancel();
+ _email.dispose();
+ _code.dispose();
+ _emailFocus.dispose();
+ _codeFocus.dispose();
+ super.dispose();
+ }
+
+ /// The offline sample — no longer offered on this screen (a video shows the app instead), but
+ /// kept behind a long press on the wordmark for the simulator's screenshots. Left from its end
+ /// card to set up a computer, it lands on the set-up page.
+ Future<void> _trySample() async {
+ final result = await widget.onTrySample!(context);
+ if (!mounted || result != 'set-up') return;
+ _go(_Step.setUp);
+ }
+
+ /// A code the desktop app showed. Its pairing code is held until its computer shows up, when the
+ /// phone pairs with it instead of asking for a password (`AppNotifier.pendingPairing`). Its
+ /// sign-in code signs the phone in there and then; without one, or when it has expired, the
+ /// account's email is filled in and a code sent, so signing in is the four digits.
+ Future<void> _onScanned(ConnectCode code) async {
+ final machineId = code.machineId, pairCode = code.pairCode;
+ if (machineId != null && pairCode != null) {
+ widget.notifier.pendingPairing = (machineId: machineId, code: pairCode);
+ }
+ _email.text = code.email;
+ final signIn = code.signIn;
+ if (signIn != null) {
+ setState(() => _signingInWithScan = true);
+ try {
+ await (widget.signInWithScan ?? widget.notifier.signInWithScan)(signIn);
+ return;
+ } catch (_) {
+ // Expired, spent, or a backend that predates it: the email is the way on.
+ } finally {
+ if (mounted) setState(() => _signingInWithScan = false);
+ }
+ if (!mounted) return;
+ }
+ unawaited(_sendCode());
+ }
+
+ void _go(_Step step) {
+ setState(() {
+ _step = step;
+ _error = null;
+ });
+ if (step == _Step.email) _emailFocus.requestFocus();
+ if (step == _Step.code) _codeFocus.requestFocus();
+ if (step == _Step.hello) FocusManager.instance.primaryFocus?.unfocus();
+ }
+
+ Future<void> _sendCode() async {
+ final email = _email.text.trim();
+ if (!email.contains('@') || !email.contains('.')) {
+ setState(() => _error = 'That doesn’t look like an email address.');
+ return;
+ }
+ final ok = await _run(
+ () => (widget.sendCode ?? widget.notifier.sendLoginCode)(email),
+ );
+ if (!ok || !mounted) return;
+ _sentTo = email;
+ _code.clear();
+ _startResend();
+ _go(_Step.code);
+ }
+
+ Future<void> _signIn() async {
+ final email = _sentTo, code = _code.text.trim();
+ if (email == null) return;
+ if (code.length < _codeLength) {
+ setState(() => _error = 'Enter the $_codeLength digits from the email.');
+ return;
+ }
+ await _run(
+ () => widget.signIn != null
+ ? widget.signIn!(email, code)
+ : widget.notifier.signInWithCode(email: email, code: code),
+ );
+ }
+
+ Future<bool> _run(Future<void> Function() request) async {
+ if (_busy) return false;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ String? error;
+ try {
+ await request();
+ } catch (e) {
+ error = _plain(e.toString());
+ }
+ if (!mounted) return false;
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ return error == null;
+ }
+
+ /// A service's reason, without the exception's type in front of it.
+ static String _plain(String raw) =>
+ raw.replaceFirst(RegExp(r'^(Exception|StateError|Bad state):\s*'), '');
+
+ void _startResend() {
+ _resendTimer?.cancel();
+ _resendIn = _resendAfter;
+ _resendTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
+ if (!mounted) return timer.cancel();
+ setState(() => _resendIn--);
+ if (_resendIn <= 0) timer.cancel();
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final signingIn = widget.notifier.signingIn;
+ return PopScope(
+ canPop: _step == _Step.hello,
+ onPopInvokedWithResult: (didPop, _) {
+ if (didPop) return;
+ _go(_step == _Step.code ? _Step.email : _Step.hello);
+ },
+ child: Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: switch (_step) {
+ _Step.hello => _Hello(
+ onScan: () => _go(_Step.scan),
+ onSetUp: () => _go(_Step.setUp),
+ onSample: widget.onTrySample == null
+ ? null
+ : () => unawaited(_trySample()),
+ ),
+ _Step.setUp => SetUpComputerPage(
+ onScan: () => _go(_Step.scan),
+ onBack: () => _go(_Step.hello),
+ loadDownloads: widget.loadDownloads,
+ ),
+ _Step.scan => ScanToConnectPage(
+ camera: widget.scanCamera,
+ onCode: (code) => unawaited(_onScanned(code)),
+ signingIn: _signingInWithScan,
+ onUseEmail: () => _go(_Step.email),
+ onBack: () => _go(_Step.hello),
+ ),
+ _Step.email => _Form(
+ onBack: () => _go(_Step.hello),
+ title: 'Your email',
+ lines: const [
+ 'The one Harness on your computer is signed in with. We’ll send you a 4-digit code.',
+ ],
+ field: TtyField(
+ key: const Key('welcome-email'),
+ controller: _email,
+ focus: _emailFocus,
+ action: TextInputAction.go,
+ onSubmitted: _sendCode,
+ keyboardType: TextInputType.emailAddress,
+ autofillHints: const [AutofillHints.email],
+ ),
+ error: _error,
+ button: TtyPrimaryButton(
+ label: 'Send code',
+ busy: _busy,
+ busyLabel: 'Sending…',
+ onPressed: _sendCode,
+ ),
+ ),
+ _Step.code => _Form(
+ onBack: () => _go(_Step.email),
+ title: 'Check your email',
+ lines: [
+ 'We sent a $_codeLength-digit code to ${_sentTo ?? 'your email'}.',
+ ],
+ field: _CodeField(
+ controller: _code,
+ focus: _codeFocus,
+ length: _codeLength,
+ onFilled: _signIn,
+ ),
+ error: _error,
+ button: TtyPrimaryButton(
+ label: 'Sign in',
+ busy: _busy || signingIn,
+ busyLabel: 'Signing in…',
+ onPressed: _signIn,
+ ),
+ footer: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(
+ child: TtyTextButton(
+ label: _resendIn > 0
+ ? 'Resend in ${_resendIn}s'
+ : 'Resend code',
+ onPressed: _resendIn > 0 || _busy ? null : _sendCode,
+ ),
+ ),
+ Flexible(
+ child: TtyTextButton(
+ label: 'Change email',
+ onPressed: _busy ? null : () => _go(_Step.email),
+ ),
+ ),
+ ],
+ ),
+ ),
+ },
+ ),
+ ),
+ );
+ }
+}
+
+/// The first thing anyone sees: the headline, the question and its two answers.
+class _Hello extends StatelessWidget {
+ const _Hello({required this.onScan, required this.onSetUp, this.onSample});
+
+ final VoidCallback onScan;
+ final VoidCallback onSetUp;
+
+ /// Behind a long press on the wordmark — see `_PhoneWelcomeState._trySample`.
+ final VoidCallback? onSample;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final hero = tty
+ .style(size: TtySize.display, weight: FontWeight.w600)
+ .copyWith(height: 34 / 28, letterSpacing: -0.6);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 24, Tty.origin, 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ GestureDetector(
+ key: const ValueKey('welcome-wordmark'),
+ behavior: HitTestBehavior.opaque,
+ onLongPress: onSample,
+ child: Row(
+ children: [
+ TtyText(
+ 'harness',
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ Container(
+ width: 9,
+ height: 18,
+ margin: const EdgeInsets.only(left: 2),
+ color: tty.green,
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 48),
+ Text(
+ 'Claude Code and Codex\nrun on your computer.\nDrive them from here.',
+ style: hero,
+ ),
+ const Spacer(),
+ TtyText(
+ 'Is Harness on your computer?',
+ color: tty.faint,
+ size: TtySize.row,
+ ),
+ const SizedBox(height: 12),
+ _Answer(label: 'Yes — scan to connect', onTap: onScan),
+ const SizedBox(height: 10),
+ _Answer(label: 'Not yet — set it up', onTap: onSetUp),
+ ],
+ ),
+ );
+ }
+}
+
+/// One of the question's two answers: a raised row the width of the screen, its words and a `›`.
+/// Equal weight — neither is the "primary" — because which one is right depends on the person.
+class _Answer extends StatelessWidget {
+ const _Answer({required this.label, required this.onTap});
+
+ final String label;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ child: Container(
+ height: 56,
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyText(
+ label,
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ ),
+ Icon(LucideIcons.chevronRight300, size: 18, color: tty.faint),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// One step of signing in: back, a title, a line or two, a field, the button.
+class _Form extends StatelessWidget {
+ const _Form({
+ required this.onBack,
+ required this.title,
+ required this.lines,
+ required this.field,
+ required this.button,
+ this.error,
+ this.footer,
+ });
+
+ final VoidCallback onBack;
+ final String title;
+ final List<String> lines;
+ final Widget field;
+ final Widget button;
+ final String? error;
+ final Widget? footer;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(onPressed: onBack),
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 16),
+ children: [
+ TtyText(title, size: 24, weight: FontWeight.w600),
+ const SizedBox(height: 12),
+ for (final line in lines)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Text(
+ line,
+ style: tty.style(size: TtySize.row, color: tty.faint),
+ ),
+ ),
+ const SizedBox(height: 18),
+ AutofillGroup(child: field),
+ if (error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: 10),
+ child: Text(
+ '✗ $error',
+ style: tty.style(size: TtySize.meta, color: tty.red),
+ ),
+ ),
+ const SizedBox(height: 16),
+ button,
+ ?footer,
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// The code, typed into one wide field in big mono digits — it submits itself on the last one.
+class _CodeField extends StatelessWidget {
+ const _CodeField({
+ required this.controller,
+ required this.focus,
+ required this.length,
+ required this.onFilled,
+ });
+
+ final TextEditingController controller;
+ final FocusNode focus;
+ final int length;
+ final VoidCallback onFilled;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ height: 64,
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ alignment: Alignment.center,
+ child: TextField(
+ key: const Key('welcome-code'),
+ controller: controller,
+ focusNode: focus,
+ keyboardType: TextInputType.number,
+ autofillHints: const [AutofillHints.oneTimeCode],
+ textAlign: TextAlign.center,
+ maxLength: length,
+ inputFormatters: [FilteringTextInputFormatter.digitsOnly],
+ cursorColor: tty.green,
+ style: tty
+ .style(size: 30, weight: FontWeight.w600)
+ .copyWith(letterSpacing: 18),
+ onChanged: (value) {
+ if (value.length == length) onFilled();
+ },
+ decoration: InputDecoration(
+ isCollapsed: true,
+ counterText: '',
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ hintText: '•' * length,
+ hintStyle: tty
+ .style(size: 30, color: tty.dim)
+ .copyWith(letterSpacing: 18),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/pick_up_page.dart b/mobile/lib/phone/welcome/pick_up_page.dart
new file mode 100644
index 000000000..ebf4a2336
--- /dev/null
+++ b/mobile/lib/phone/welcome/pick_up_page.dart
@@ -0,0 +1,132 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../agent_index.dart';
+import '../agents_page.dart' show openNewAgent;
+import '../phone_status.dart';
+import '../phone_search_controller.dart';
+import '../phone_search_results.dart';
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// The first screen once a computer is there: **Pick up where you left off**, every session on
+/// your computers with the ones that moved last on top, each a tap from its terminal.
+///
+/// What the phone opens on when it has nothing to remember (a new phone, or a computer just linked)
+/// in place of guessing one session and dropping you into it cold. The owner: "the welcome screen
+/// should display a list of sessions so users can just click and start right away, rather than a
+/// blank cold screen."
+///
+/// ⚠️ **The list is Find's own** ([PhoneSearchResults]): the same rows, state words, resume for a
+/// paused session, and `+ New Harness` at the end. The first screen teaches the one a swipe right
+/// brings back, and a tap opens through the same path Find uses (`openAgent` → the home screen).
+class PickUpPage extends StatefulWidget {
+ const PickUpPage({super.key, required this.notifier});
+
+ final AppNotifier notifier;
+
+ @override
+ State<PickUpPage> createState() => _PickUpPageState();
+}
+
+class _PickUpPageState extends State<PickUpPage> {
+ late final _search = PhoneSearchController(
+ notifier: widget.notifier,
+ history: widget.notifier.searchHistory,
+ modes: false,
+ );
+
+ @override
+ void dispose() {
+ _search.dispose();
+ super.dispose();
+ }
+
+ /// `12 sessions on MacBook Pro`, or `on 2 computers`.
+ String _where() {
+ final entries = visibleAgents(agentIndex(widget.notifier));
+ final computers = {for (final entry in entries) entry.machineName};
+ final sessions =
+ '${entries.length} ${entries.length == 1 ? 'session' : 'sessions'}';
+ return computers.length == 1
+ ? '$sessions on ${computers.single}'
+ : '$sessions on ${computers.length} computers';
+ }
+
+ /// `+ New Harness`: in the project a row names, else on the first computer that can take one.
+ void _newHarness(({String machineId, String folder, String label})? place) {
+ if (place != null) {
+ openNewAgent(
+ context,
+ widget.notifier,
+ place.machineId,
+ folder: place.folder,
+ );
+ return;
+ }
+ final ready = filterableMachines(widget.notifier)
+ .where(
+ (machine) =>
+ phoneMachineStatusOf(machine) == PhoneMachineStatus.ready,
+ )
+ .firstOrNull;
+ if (ready != null) {
+ openNewAgent(context, widget.notifier, ready.machine.machineId);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: widget.notifier,
+ builder: (context, _) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 20,
+ Tty.origin,
+ 0,
+ ),
+ child: Text(
+ // Broken by hand: at 28pt it wraps with "off" alone on the second line.
+ 'Pick up where\nyou left off',
+ key: const ValueKey('pick-up-title'),
+ style: tty
+ .style(size: TtySize.display, weight: FontWeight.w600)
+ .copyWith(height: 34 / 28, letterSpacing: -0.6),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Tty.origin,
+ 6,
+ Tty.origin,
+ 8,
+ ),
+ child: TtyText(_where(), color: tty.faint, size: TtySize.meta),
+ ),
+ Expanded(
+ child: PhoneSearchResults(
+ notifier: widget.notifier,
+ controller: _search,
+ fzf: true,
+ onNewHarness: _newHarness,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/mobile/lib/phone/welcome/scan_to_connect.dart b/mobile/lib/phone/welcome/scan_to_connect.dart
new file mode 100644
index 000000000..a72062110
--- /dev/null
+++ b/mobile/lib/phone/welcome/scan_to_connect.dart
@@ -0,0 +1,142 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:mobile_scanner/mobile_scanner.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+import 'connect_code.dart';
+
+/// **Yes — scan to connect**: the camera, reading the code the desktop app shows under
+/// Harness ▸ Add Phone… ([ConnectCode]). The scan signs the phone in; [signingIn] says so while it
+/// does.
+///
+/// ```
+/// ‹
+/// ┌──────────────────────┐
+/// │ [ camera view ] │
+/// └──────────────────────┘
+/// Scan the code on your computer
+/// On your Mac: Harness ▸ Add Phone…
+///
+/// Use email instead
+/// ```
+///
+/// The camera runs only while this page is up. A code that is not ours is ignored, so a stray QR
+/// in frame does nothing; no camera (refused, or none) says so and leaves email as the way in.
+class ScanToConnectPage extends StatefulWidget {
+ const ScanToConnectPage({
+ super.key,
+ required this.onCode,
+ required this.onUseEmail,
+ required this.onBack,
+ this.signingIn = false,
+ this.camera,
+ });
+
+ final ValueChanged<ConnectCode> onCode;
+ final VoidCallback onUseEmail;
+ final VoidCallback onBack;
+
+ /// A code was read and the phone is signing in with it.
+ final bool signingIn;
+
+ /// Stands in for the camera in tests and renders. Null opens the real one.
+ final Widget? camera;
+
+ @override
+ State<ScanToConnectPage> createState() => _ScanToConnectPageState();
+}
+
+class _ScanToConnectPageState extends State<ScanToConnectPage> {
+ /// Set once a code of ours is read: the camera keeps reporting it every frame.
+ bool _done = false;
+
+ void _onDetect(BarcodeCapture capture) {
+ if (_done) return;
+ for (final barcode in capture.barcodes) {
+ final code = ConnectCode.parse(barcode.rawValue ?? '');
+ if (code == null) continue;
+ _done = true;
+ HapticFeedback.mediumImpact();
+ widget.onCode(code);
+ return;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(onPressed: widget.onBack),
+ ),
+ const SizedBox(height: 12),
+ // As big a square as fits: the full width on a phone, less on a short screen.
+ Expanded(
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(14),
+ child: ColoredBox(
+ color: ttyRaised(tty),
+ child:
+ widget.camera ??
+ MobileScanner(
+ onDetect: _onDetect,
+ errorBuilder: (context, error) => Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: TtyText(
+ 'No camera. Allow it in Settings, or use your email.',
+ color: tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 24),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: TtyText(
+ widget.signingIn ? 'Signing in…' : 'Scan the code on your computer',
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 6),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ child: TtyText(
+ 'On your Mac: Harness ▸ Add Phone…',
+ color: tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Center(
+ child: TtyTextButton(
+ label: 'Use email instead',
+ color: tty.faint,
+ onPressed: widget.onUseEmail,
+ ),
+ ),
+ const SizedBox(height: 12),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/set_up_computer.dart b/mobile/lib/phone/welcome/set_up_computer.dart
new file mode 100644
index 000000000..dfd7e91fb
--- /dev/null
+++ b/mobile/lib/phone/welcome/set_up_computer.dart
@@ -0,0 +1,353 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:dio/dio.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:share_plus/share_plus.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+import 'how_it_works_video.dart';
+
+/// Where the desktop app is downloaded, for someone typing it on the computer — and every row's
+/// link when the release manifest cannot be read.
+const kDesktopDownloadUrl = 'https://harness.autonomous.ai/desktop';
+
+/// The desktop release manifest: the one the website's download menu and the desktop app's own
+/// updater read, so each row below sends the current build of its file.
+const kDesktopManifestUrl =
+ 'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/desktop/metadata.json';
+
+/// The `harness` command alone, for a computer with no desktop — the website menu's CLI row.
+const kCliInstall =
+ 'curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash';
+
+/// One row of the website's download menu: its manifest key, what it says, and its icon.
+typedef DesktopPlatform = ({
+ String key,
+ String label,
+ String note,
+ IconData icon,
+});
+
+/// The website's download menu (autonomous.ai/harness-app), row for row.
+const kDesktopPlatforms = <DesktopPlatform>[
+ (
+ key: 'desktop-macos-arm64-dmg',
+ label: 'macOS',
+ note: 'Apple Silicon',
+ icon: Icons.apple,
+ ),
+ (key: 'desktop-macos-dmg', label: 'macOS', note: 'Intel', icon: Icons.apple),
+ (
+ key: 'desktop-linux-x64',
+ label: 'Linux',
+ note: 'Intel/AMD · Ubuntu, Omarchy and more',
+ icon: LucideIcons.monitor300,
+ ),
+ (
+ key: 'desktop-linux-arm64',
+ label: 'Linux',
+ note: 'ARM · Raspberry Pi, ARM servers',
+ icon: LucideIcons.monitor300,
+ ),
+];
+
+/// Manifest key → the file's URL. Empty when the manifest cannot be read.
+typedef DesktopDownloadsLoader = Future<Map<String, String>> Function();
+
+Future<Map<String, String>> loadDesktopDownloads({Dio? dio}) async {
+ try {
+ final res =
+ await (dio ??
+ Dio(
+ BaseOptions(
+ connectTimeout: const Duration(seconds: 10),
+ receiveTimeout: const Duration(seconds: 10),
+ ),
+ ))
+ .get<Object?>(kDesktopManifestUrl);
+ final raw = res.data;
+ final data = raw is String ? jsonDecode(raw) : raw;
+ if (data is! Map) return const {};
+ return {
+ for (final MapEntry(:key, :value) in data.entries)
+ if (key is String && value is Map && value['url'] is String)
+ key: value['url'] as String,
+ };
+ } catch (_) {
+ return const {};
+ }
+}
+
+/// **Not yet — set it up**: getting Harness onto the computer, from the phone — the website's
+/// download menu, where a row SENDS its file (AirDrop to the Mac beside you, or Messages or email
+/// to yourself) because a phone cannot install it.
+///
+/// ```
+/// ‹
+/// Get Harness for
+/// your computer
+///
+/// Send it to your computer:
+/// ┌──────────────────────────────────────┐
+/// │ macOS ⇪ │
+/// │ Apple Silicon │
+/// │ macOS ⇪ │
+/// │ Intel │
+/// │ Linux ⇪ │
+/// │ Intel/AMD · Ubuntu, Omarchy and more│
+/// │ Linux ⇪ │
+/// │ ARM · Raspberry Pi, ARM servers │
+/// │ CLI ⧉ │
+/// │ curl -fsSL …/install.sh | bash │
+/// └──────────────────────────────────────┘
+/// or open harness.autonomous.ai/desktop there.
+///
+/// Then open it, and scan the code it shows.
+/// Scan to connect ›
+/// ```
+class SetUpComputerPage extends StatefulWidget {
+ const SetUpComputerPage({
+ super.key,
+ required this.onScan,
+ required this.onBack,
+ this.loadDownloads,
+ });
+
+ /// Back to the first screen's other answer, once the app is on the computer.
+ final VoidCallback onScan;
+ final VoidCallback onBack;
+
+ /// Stands in for the manifest in tests. Null reads [kDesktopManifestUrl].
+ final DesktopDownloadsLoader? loadDownloads;
+
+ @override
+ State<SetUpComputerPage> createState() => _SetUpComputerPageState();
+}
+
+class _SetUpComputerPageState extends State<SetUpComputerPage> {
+ bool _copied = false;
+ Timer? _copiedTimer;
+
+ /// Read as the page opens, so a tap shares at once; a tap before it lands waits for it.
+ late final Future<Map<String, String>> _downloads =
+ (widget.loadDownloads ?? loadDesktopDownloads)();
+
+ @override
+ void dispose() {
+ _copiedTimer?.cancel();
+ super.dispose();
+ }
+
+ /// The share sheet with [platform]'s file: AirDrop straight to the computer beside you, or
+ /// Messages or email to yourself. Anchored to the row for iPad, where the sheet is a popover.
+ Future<void> _send(BuildContext row, DesktopPlatform platform) async {
+ final box = row.findRenderObject() as RenderBox?;
+ final origin = box == null
+ ? null
+ : box.localToGlobal(Offset.zero) & box.size;
+ final url = (await _downloads)[platform.key] ?? kDesktopDownloadUrl;
+ await SharePlus.instance.share(
+ ShareParams(
+ uri: Uri.parse(url),
+ subject: 'Harness for ${platform.label} (${platform.note})',
+ sharePositionOrigin: origin,
+ ),
+ );
+ }
+
+ void _copy() {
+ unawaited(Clipboard.setData(const ClipboardData(text: kCliInstall)));
+ HapticFeedback.selectionClick();
+ _copiedTimer?.cancel();
+ setState(() => _copied = true);
+ _copiedTimer = Timer(const Duration(seconds: 2), () {
+ if (mounted) setState(() => _copied = false);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ final faint = tty.style(color: tty.faint, size: TtySize.meta);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(onPressed: widget.onBack),
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, Tty.origin, 24),
+ children: [
+ Text(
+ 'Get Harness for\nyour computer',
+ style: tty
+ .style(size: TtySize.display, weight: FontWeight.w600)
+ .copyWith(height: 34 / 28, letterSpacing: -0.6),
+ ),
+ const SizedBox(height: 28),
+ Text('Send it to your computer:', style: faint),
+ const SizedBox(height: 8),
+ DecoratedBox(
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Column(
+ children: [
+ for (final platform in kDesktopPlatforms)
+ Builder(
+ builder: (row) => _DownloadRow(
+ icon: platform.icon,
+ label: platform.label,
+ note: platform.note,
+ action: LucideIcons.share300,
+ actionLabel: 'Send',
+ onTap: () => unawaited(_send(row, platform)),
+ ),
+ ),
+ _DownloadRow(
+ icon: LucideIcons.squareTerminal300,
+ label: 'CLI',
+ note: _copied
+ ? 'copied'
+ : 'curl -fsSL …/install.sh | bash',
+ noteColor: _copied ? tty.green : null,
+ action: LucideIcons.copy300,
+ actionLabel: 'Copy',
+ onTap: _copy,
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 10),
+ Text.rich(
+ TextSpan(
+ children: [
+ const TextSpan(text: 'or open '),
+ TextSpan(
+ text: kDesktopDownloadUrl.replaceFirst('https://', ''),
+ style: tty.style(size: TtySize.meta),
+ ),
+ const TextSpan(text: ' there.'),
+ ],
+ ),
+ style: faint,
+ ),
+ const SizedBox(height: 28),
+ Text('Then open it, and scan the code it shows.', style: faint),
+ const SizedBox(height: 4),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Transform.translate(
+ // The button's own inset, so its words sit on the gutter.
+ offset: const Offset(-12, 0),
+ child: TtyTextButton(
+ label: 'Scan to connect ›',
+ onPressed: widget.onScan,
+ ),
+ ),
+ ),
+ const SizedBox(height: 32),
+ // Not at the computer: what it is like, in 30 seconds.
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Transform.translate(
+ offset: const Offset(-12, 0),
+ child: TtyTextButton(
+ label: 'See how it works ▶',
+ color: tty.faint,
+ onPressed: () => Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (_) => const HowItWorksVideoPage(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// One row of the menu: its icon, what it is and for which computer, and what a tap does.
+class _DownloadRow extends StatelessWidget {
+ const _DownloadRow({
+ required this.icon,
+ required this.label,
+ required this.note,
+ required this.action,
+ required this.actionLabel,
+ required this.onTap,
+ this.noteColor,
+ });
+
+ final IconData icon;
+ final String label;
+ final String note;
+ final Color? noteColor;
+ final IconData action;
+ final String actionLabel;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: '$actionLabel $label, $note',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 10, 14, 10),
+ child: Row(
+ children: [
+ Icon(icon, size: 22, color: tty.faint),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ label,
+ style: tty.style(
+ size: TtySize.row,
+ weight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ note,
+ style: tty.style(
+ color: noteColor ?? tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 12),
+ Icon(action, size: 18, color: tty.faint),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/welcome/unlock_computer.dart b/mobile/lib/phone/welcome/unlock_computer.dart
new file mode 100644
index 000000000..77eb1fb50
--- /dev/null
+++ b/mobile/lib/phone/welcome/unlock_computer.dart
@@ -0,0 +1,275 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// Unlocking a computer from this phone: its phone password, once — the page behind a locked
+/// computer's row.
+///
+/// ```
+/// Unlock M2
+/// Enter the phone password you set on M2.
+/// [ •••••••• Show ]
+/// [ Unlock ]
+///
+/// Forgot it, or never set one? On M2, run
+/// $ harness remote-password set Copy
+/// ```
+///
+/// What the link is doing while it works is said in words ("Checking the password…"), never as the
+/// CLI's stage names.
+class UnlockComputer extends StatefulWidget {
+ const UnlockComputer({
+ super.key,
+ required this.notifier,
+ required this.machineState,
+ this.onUnlocked,
+ });
+
+ final AppNotifier notifier;
+ final MachineState machineState;
+
+ /// Called once the computer is unlocked.
+ final VoidCallback? onUnlocked;
+
+ @override
+ State<UnlockComputer> createState() => _UnlockComputerState();
+}
+
+class _UnlockComputerState extends State<UnlockComputer> {
+ final _password = TextEditingController();
+ final _focus = FocusNode();
+ bool _obscure = true;
+ bool _busy = false;
+ String? _error;
+ String? _stage;
+ bool _copied = false;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _password.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ static String _say(String stage) => switch (stage) {
+ 'connecting' => 'Reaching the computer…',
+ 'deriving_key' => 'Checking the password…',
+ 'exchanging' => 'Making a secure link…',
+ 'verifying' => 'Almost there…',
+ _ => 'Unlocking…',
+ };
+
+ Future<void> _unlock() async {
+ if (_busy) return;
+ if (_password.text.isEmpty) {
+ setState(() => _error = 'Enter the password first.');
+ return;
+ }
+ setState(() {
+ _busy = true;
+ _error = null;
+ _stage = null;
+ });
+ final error = await widget.notifier.connectWithPassword(
+ widget.machineState.machine.machineId,
+ _password.text,
+ onProgress: (stage) {
+ if (mounted) setState(() => _stage = stage);
+ },
+ );
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ _stage = null;
+ });
+ if (error == null) {
+ _password.clear();
+ HapticFeedback.mediumImpact();
+ widget.onUnlocked?.call();
+ } else {
+ HapticFeedback.heavyImpact();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final name = widget.machineState.machine.displayName;
+ return ListView(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 24),
+ children: [
+ TtyText('Unlock $name', size: 24, weight: FontWeight.w600),
+ const SizedBox(height: 12),
+ Text(
+ 'Enter the phone password you set on $name.',
+ style: tty.style(size: TtySize.row, color: tty.faint),
+ ),
+ const SizedBox(height: 18),
+ _PasswordField(
+ controller: _password,
+ focus: _focus,
+ obscure: _obscure,
+ onToggle: () => setState(() => _obscure = !_obscure),
+ onSubmitted: _unlock,
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: 10),
+ child: Text(
+ '✗ $error',
+ style: tty.style(size: TtySize.meta, color: tty.red),
+ ),
+ ),
+ const SizedBox(height: 16),
+ TtyPrimaryButton(
+ label: 'Unlock',
+ busy: _busy,
+ busyLabel: _stage == null ? 'Unlocking…' : _say(_stage!),
+ onPressed: _unlock,
+ ),
+ const SizedBox(height: 32),
+ Text(
+ 'Forgot it, or never set one? On $name, run',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ const SizedBox(height: 8),
+ Container(
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ padding: const EdgeInsets.only(left: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: r'$ ',
+ style: tty.style(color: tty.green, size: TtySize.meta),
+ ),
+ TextSpan(
+ text: 'harness remote-password set',
+ style: tty.style(size: TtySize.meta),
+ ),
+ ],
+ ),
+ ),
+ ),
+ TtyTextButton(
+ label: _copied ? 'Copied' : 'Copy',
+ color: _copied ? tty.green : null,
+ onPressed: () {
+ unawaited(
+ Clipboard.setData(
+ const ClipboardData(text: 'harness remote-password set'),
+ ),
+ );
+ setState(() => _copied = true);
+ },
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'or, in the Harness app on $name: Machines → $name → Set password.',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ const SizedBox(height: 28),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Icon(LucideIcons.lock300, size: 13, color: tty.faint),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ 'The password makes an end-to-end encrypted link between this '
+ 'phone and $name. It never leaves your devices.',
+ style: tty.style(size: TtySize.meta, color: tty.faint),
+ ),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+}
+
+class _PasswordField extends StatelessWidget {
+ const _PasswordField({
+ required this.controller,
+ required this.focus,
+ required this.obscure,
+ required this.onToggle,
+ required this.onSubmitted,
+ });
+
+ final TextEditingController controller;
+ final FocusNode focus;
+ final bool obscure;
+ final VoidCallback onToggle;
+ final VoidCallback onSubmitted;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ return Container(
+ height: 48,
+ decoration: BoxDecoration(
+ color: ttyRaised(tty),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ padding: const EdgeInsets.only(left: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const Key('remote-password-connect-field'),
+ controller: controller,
+ focusNode: focus,
+ obscureText: obscure,
+ autocorrect: false,
+ enableSuggestions: false,
+ autofillHints: const [AutofillHints.password],
+ textInputAction: TextInputAction.go,
+ onSubmitted: (_) => onSubmitted(),
+ cursorColor: tty.green,
+ style: tty.style(size: TtySize.title),
+ decoration: InputDecoration(
+ isCollapsed: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ hintText: 'Phone password',
+ hintStyle: tty.style(size: TtySize.title, color: tty.faint),
+ ),
+ ),
+ ),
+ TtyTextButton(label: obscure ? 'Show' : 'Hide', onPressed: onToggle),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/shared/widgets/app_dialog.dart b/mobile/lib/shared/widgets/app_dialog.dart
index 00a42abbc..eabe47c80 100644
--- a/mobile/lib/shared/widgets/app_dialog.dart
+++ b/mobile/lib/shared/widgets/app_dialog.dart
@@ -27,7 +27,13 @@ import '../theme/app_theme.dart' show AppFont;
/// become a grey haze that looks like a rendering fault rather than depth. 7
/// is where a line behind the panel is unmistakably gone while the window
/// still reads as the window.
-const double kDialogVeilBlur = 7;
+///
+/// ⚠️ **Zero on the phone: no blur at all.** A blur re-reads and filters the
+/// whole screen behind it on every frame that screen changes — behind a sheet
+/// that is a streaming terminal, so every frame. The phone is meant to feel
+/// instant; the tint alone sets the depth. Every veil that multiplies by this
+/// (dialogs, sheets, Find) turns its filter off at zero.
+const double kDialogVeilBlur = 0;
/// Shared dark backdrop for dialogs and centered pickers. Terminal output
/// stays in the background while the active surface has the user's attention.
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 20b338519..44c5a6170 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -3,6 +3,7 @@ import 'dart:io' show exit, pid;
import 'dart:math' show Random;
import 'package:dio/dio.dart';
+import 'package:xterm/xterm.dart' show Terminal;
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -60,6 +61,8 @@ import '../ws/ws_pool.dart';
import 'pane_preset.dart';
import 'pane_arrangement.dart';
import 'pending_question.dart';
+import 'search_when.dart';
+import 'session_content_search.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
import '../phone/phone_name_store.dart';
@@ -1324,6 +1327,11 @@ class AppNotifier extends ChangeNotifier {
ApiClient _newApiClient() =>
ApiClient(config: config, session: session, auth: viewer?.auth);
+ /// Where the harnesses this notifier sees are counted — the app's own [harnessStats], kept on
+ /// disk. Sample mode (`lib/demo/`) counts into one of its own: its harnesses are not the
+ /// person's, and must not land in their figures.
+ HarnessStats get stats => harnessStats;
+
String? get lastError => _lastError;
bool get lastErrorRetryable => _lastErrorRetryable;
String? get bootStatusMessage => _bootStatusMessage;
@@ -2797,6 +2805,37 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Sign in with the one-time code a signed-in computer's Add Phone QR
+ /// carries — no email, no digits — and go in. Thrown and kept like
+ /// [signInWithCode]: the welcome screen falls back to an emailed code.
+ Future<void> signInWithScan(String code) async {
+ final login = viewer?.emailLogin;
+ if (_disposed || signingIn || login == null) return;
+ final revision = _invalidateAuthWork();
+ _closedHistory.clear();
+ _lastError = null;
+ signingIn = true;
+ notifyListeners();
+ try {
+ await login.signInWithScan(code, label: phoneClientDescriptor().name);
+ if (!_authWorkCurrent(revision)) return;
+ status = AppStatus.bootstrapping;
+ notifyListeners();
+ await _enterSignedIn(revision);
+ } catch (_) {
+ if (_authWorkCurrent(revision)) {
+ status = AppStatus.unauthenticated;
+ analytics.signInFailed('failed');
+ }
+ rethrow;
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ signingIn = false;
+ notifyListeners();
+ }
+ }
+ }
+
void _resetLoginBrowser() {
++_loginBrowserRevision;
openingLoginBrowser = false;
@@ -3362,6 +3401,7 @@ class AppNotifier extends ChangeNotifier {
// the phone sorting and searching by the list it had an hour ago.
prev.title != agent.title ||
prev.updatedAt != agent.updatedAt ||
+ prev.lastOpenedAt != agent.lastOpenedAt ||
prev.gridModel != agent.gridModel ||
prev.selectedModel != agent.selectedModel ||
prev.dshName != agent.dshName ||
@@ -3419,6 +3459,40 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ /// A code scanned from a desktop app's "Add phone" QR, held across sign-in: once its machine shows
+ /// up locked, the phone pairs with the code ([connectWithCode]) instead of asking for a password.
+ /// See `phone/welcome/connect_code.dart`. Null the rest of the time.
+ ({String machineId, String code})? pendingPairing;
+
+ /// The scanned code is spent (it failed, or the person chose the password): the computer's
+ /// password form is what the home screen shows next.
+ void dropPendingPairing() {
+ if (pendingPairing == null) return;
+ pendingPairing = null;
+ notifyListeners();
+ }
+
+ /// Pairs with [machineId] by the one-time code its desktop app showed, then reconnects it — the
+ /// QR's way in, where [connectWithPassword] is the password's. Null on success, or what to show.
+ Future<String?> connectWithCode(String machineId, String code) async {
+ final result = await peerLinks.connectWithCode(
+ machineId,
+ code,
+ label: phoneClientDescriptor().name,
+ displayName: machineStates[machineId]?.machine.displayName,
+ );
+ if (result.error != null) return result.error;
+ final state = machineStates[result.linkedMachineId ?? machineId];
+ if (state != null) {
+ state.needsLink = false;
+ state.agentLoadStatus = AgentLoadStatus.idle;
+ notifyListeners();
+ await _pool?.closeMachine(state.machine.machineId);
+ _connectMachine(state);
+ }
+ return null;
+ }
+
List<LinkedMachine> linkedMachines = [];
bool linkedMachinesLoading = false;
String? linkedMachinesError;
@@ -4557,7 +4631,7 @@ class AppNotifier extends ChangeNotifier {
// Closed even when the machine has been replaced under us: this path is
// the only end a stalled turn ever gets, and a stats turn left open would
// sit there until quit and then bank every hour since as work.
- harnessStats.onTurnEnded(key);
+ stats.onTurnEnded(key);
final current = machineStates[machine.machine.machineId];
if (!identical(current, machine)) return;
if (machine.processingAgentIds.remove(agentId)) notifyListeners();
@@ -4594,7 +4668,7 @@ class AppNotifier extends ChangeNotifier {
// disconnect, a deleted agent — so this is where the clock stops. An end for
// a turn this process never saw start contributes nothing (see
// `HarnessStats.onTurnEnded`), which is what makes the disconnect sweep safe.
- harnessStats.onTurnEnded(key);
+ stats.onTurnEnded(key);
final machine = machineStates[machineId];
machine?.processingAgentIds.remove(agentId);
// A question cannot outlive its own turn — the daemon's watcher says the
@@ -4831,6 +4905,47 @@ class AppNotifier extends ChangeNotifier {
/// A short timeout on purpose: this runs while somebody is looking at a form
/// they have already half filled in, and a machine that cannot answer in six
/// seconds should leave the rest of the form working.
+ /// Machines whose daemon can be asked what was said in their sessions now — connected, never
+ /// dialled for it: a search must not be what wakes a relay socket.
+ Iterable<String> get searchableMachineIds => [
+ for (final machine in machineStates.values)
+ if (machine.connectionStatus == ConnectionStatus.connected &&
+ !machine.needsLink &&
+ machine.nodeOnline != false)
+ machine.machine.machineId,
+ ];
+
+ /// Every turn of every session on [machineId], searched by its daemon (`session_search`,
+ /// cli/src/lib/sessionSearch/) — the desktop's `searchSessions`, unchanged. Null when the machine
+ /// cannot answer: offline, or a CLI that predates the request, which goes silent rather than
+ /// refusing it — hence the short timeout.
+ Future<List<SessionContentHit>?> searchSessions(
+ String machineId,
+ String query, {
+ SearchWhen? when,
+ int limit = 30,
+ }) async {
+ if (!searchableMachineIds.contains(machineId)) return null;
+ try {
+ final reply = await _conn(machineId).request(
+ 'session_search',
+ payload: {
+ 'query': query,
+ 'limit': limit,
+ if (when != null) ...{
+ 'from': when.from.millisecondsSinceEpoch,
+ 'to': when.to.millisecondsSinceEpoch,
+ },
+ },
+ timeout: const Duration(seconds: 4),
+ );
+ if (reply['error'] != null) return null;
+ return SessionContentHit.listFromReply(machineId, reply);
+ } catch (_) {
+ return null;
+ }
+ }
+
Future<Map<String, dynamic>> readGitProject(
String machineId,
String path,
@@ -4907,10 +5022,15 @@ class AppNotifier extends ChangeNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ String? prompt,
}) {
final creation = attempt ?? AgentCreationAttempt();
+ final task = prompt?.trim();
final choices = <String, dynamic>{
'engine': engine,
+ // The harness's first task — the machine types it into the agent once it is up. Only
+ // claude, codex and opencode take one (see `kFirstTaskEngines`); an empty one is left out.
+ if (task != null && task.isNotEmpty) 'prompt': task,
if (projectFolder == null) 'cwd': folder,
...?projectFolder?.payload,
'permissionMode': ?permissionMode,
@@ -4925,6 +5045,43 @@ class AppNotifier extends ChangeNotifier {
: permissionModeApproves(permissionMode),
'codexHome': ?codexHome,
};
+ return _create(
+ machineId,
+ choices,
+ swarmId: swarmId,
+ split: split,
+ attempt: creation,
+ );
+ }
+
+ /// A Claude Code or Codex conversation Harness did not start, opened as a harness that resumes
+ /// it, in its own folder (Find's "not in Harness" rows, `ExternalSessionRef`) — the desktop's
+ /// `resumeConversation`. The machine refuses one open elsewhere, already a harness, or whose
+ /// folder is gone, and says why. Null when it started; otherwise what to tell the person. The
+ /// new harness's id is on [attempt] once it has.
+ Future<String?> resumeConversation(
+ String machineId, {
+ required String engine,
+ required String folder,
+ required String sessionId,
+ String? name,
+ AgentCreationAttempt? attempt,
+ }) => _create(machineId, {
+ 'engine': engine,
+ 'cwd': folder,
+ 'bypassPermission': true,
+ 'name': ?name,
+ 'resumeSessionId': sessionId,
+ }, attempt: attempt);
+
+ Future<String?> _create(
+ String machineId,
+ Map<String, dynamic> choices, {
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ }) {
+ final creation = attempt ?? AgentCreationAttempt();
if (creation._choices != null &&
(creation._machineId != machineId ||
!mapEquals(creation._choices, choices))) {
@@ -4967,6 +5124,14 @@ class AppNotifier extends ChangeNotifier {
'Install tmux there, then try again.',
'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
'Update the harness CLI on this machine to create a harness',
+ // Opening a conversation Harness did not start (`resumeSessionId`). The machine says what
+ // stopped it: open elsewhere, already a harness, gone.
+ 'SESSION_OPEN_ELSEWHERE' ||
+ 'SESSION_IN_HARNESS' ||
+ 'SESSION_NOT_FOUND' ||
+ 'SESSION_FOLDER_GONE' ||
+ 'INVALID_SESSION' =>
+ detail ?? 'Could not open that conversation on $machine.',
_ => 'Create harness failed: ${detail ?? code}',
};
@@ -5039,6 +5204,12 @@ class AppNotifier extends ChangeNotifier {
'GRID_CONFIG_FAILED',
'UNSUPPORTED_ON_REMOTE',
'UNSUPPORTED',
+ // A conversation Harness did not start, refused before its pane opens.
+ 'SESSION_OPEN_ELSEWHERE',
+ 'SESSION_IN_HARNESS',
+ 'SESSION_NOT_FOUND',
+ 'SESSION_FOLDER_GONE',
+ 'INVALID_SESSION',
};
if (refusedBeforeLaunch.contains(failure.code)) {
return creation._complete(
@@ -5111,7 +5282,7 @@ class AppNotifier extends ChangeNotifier {
unawaited(projectHistory.select(machineId, projectPath));
}
// Apply each creation receipt once, even if its transport result is replayed.
- harnessStats.onAgentSpawned();
+ stats.onAgentSpawned();
notifyListeners();
if (_creationPlacementError(targetId, split) != null) {
_lastError =
@@ -5212,6 +5383,36 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ /// Tells the machine that owns an agent it was just opened here, so it can stamp
+ /// `lastOpenedAt` and every app — this phone, each desktop — sorts by the same
+ /// last use. Fire and forget: a daemon too old to keep the stamp answers
+ /// `MISSING_UPDATE`, and nothing here depends on the answer.
+ ///
+ /// Coalesced per agent: opening the same one again within [_touchEvery] says
+ /// nothing new.
+ void touchAgent(String machineId, String agentId) {
+ final machine = machineStates[machineId];
+ if (machine == null || machine.needsLink) return;
+ final key = '$machineId/$agentId';
+ final now = DateTime.now();
+ final last = _touchedAt[key];
+ if (last != null && now.difference(last) < _touchEvery) return;
+ _touchedAt[key] = now;
+ unawaited(() async {
+ try {
+ await _conn(machineId).request(
+ 'agent_update',
+ payload: {'agentId': agentId, 'opened': true},
+ );
+ } catch (_) {
+ // Recency is a nicety: a machine that cannot hear it keeps its order.
+ }
+ }());
+ }
+
+ static const _touchEvery = Duration(seconds: 3);
+ final _touchedAt = <String, DateTime>{};
+
/// Deletes an agent via `agent_delete`. Returns null on success, or an error message to show
/// inline in the caller's dialog.
Future<String?> deleteAgent(String machineId, String agentId) async {
@@ -5797,6 +5998,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> selectAgent(
String machineId,
String agentId, {
+
/// [AttachIntent.automatic] shows the agent without claiming its
/// terminal — the road `_showAgentFromDevice` and recovery take.
AttachIntent intent = AttachIntent.person,
@@ -6170,6 +6372,9 @@ class AppNotifier extends ChangeNotifier {
takeover: takeControl,
);
pane.session = terminal;
+ // Back to an agent read a moment ago: its last screen, at once, until the stream's arrives.
+ final kept = _keptScreens.remove('${pane.machineId}/${agent.id}');
+ if (kept != null) terminal.seedScreen(kept);
terminal.addListener(notifyListeners);
notifyListeners();
// Wait for the pane's actual measured viewport before asking the daemon to open anything.
@@ -6190,6 +6395,16 @@ class AppNotifier extends ChangeNotifier {
pane.session = null;
if (terminal == null) return;
terminal.removeListener(notifyListeners);
+ // The screen as the reader left it, for the next time this agent opens — see [_keptScreens].
+ final agentId = pane.agentId;
+ if (agentId != null && terminal.hasRenderedFrame) {
+ final key = '${pane.machineId}/$agentId';
+ _keptScreens.remove(key);
+ _keptScreens[key] = terminal.terminal;
+ while (_keptScreens.length > _keptScreenLimit) {
+ _keptScreens.remove(_keptScreens.keys.first);
+ }
+ }
if (sendClose) await terminal.close();
terminal.dispose();
}
@@ -6557,7 +6772,15 @@ class AppNotifier extends ChangeNotifier {
if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
}
+ /// The last screens of agents this phone closed, oldest first — shown the instant one is opened
+ /// again, while its live stream attaches ([TerminalSession.seedScreen]). A few, not all: each holds
+ /// its scrollback, up to 10,000 lines.
+ final _keptScreens = <String, Terminal>{};
+ static const _keptScreenLimit = 3;
+
Future<void> _closeAllPanes({bool persist = true}) async {
+ // Everything closing at once is a sign-out or a reset: nothing of it is kept.
+ _keptScreens.clear();
final open = allPanes.toList();
for (final swarm in swarms) {
swarm.panes.clear();
@@ -7131,7 +7354,7 @@ class AppNotifier extends ChangeNotifier {
// is a turn already under way, and counting one would report an agent
// this app merely reconnected to as work somebody just asked for.
if (type == 'turn_started') {
- harnessStats.onTurnStarted(
+ stats.onTurnStarted(
_turnActivityKey(machine.machine.machineId, agentId),
);
}
diff --git a/mobile/lib/state/external_session.dart b/mobile/lib/state/external_session.dart
new file mode 100644
index 000000000..afa5f4d73
--- /dev/null
+++ b/mobile/lib/state/external_session.dart
@@ -0,0 +1,49 @@
+import 'package:flutter/foundation.dart' show immutable;
+
+/// A Claude Code or Codex conversation Harness did not start, on one machine: run in a terminal or
+/// in the engine's own app, found on disk by that machine's daemon
+/// (cli/src/lib/sessionSearch/external.ts). Find shows one when a search matches it, and opens it
+/// as a new harness resuming it — the desktop Cmd-P's `ExternalSessionRef`, unchanged.
+@immutable
+class ExternalSessionRef {
+ const ExternalSessionRef({
+ required this.sessionId,
+ required this.engine,
+ required this.cwd,
+ required this.origin,
+ this.title = '',
+ this.open = false,
+ });
+
+ final String sessionId, engine, cwd, title;
+
+ /// `terminal`, `claude-app`, `codex-app` or `editor`.
+ final String origin;
+
+ /// Open in a running process elsewhere: opening it here too would have two processes writing one
+ /// conversation.
+ final bool open;
+
+ /// Where it ran, as a person says it.
+ String get originLabel => switch (origin) {
+ 'claude-app' => 'Claude app',
+ 'codex-app' => 'Codex app',
+ 'editor' => 'editor',
+ _ => 'terminal',
+ };
+
+ /// The engine as a person says it.
+ String get engineLabel => switch (engine) {
+ 'claude' => 'Claude Code',
+ 'codex' => 'Codex',
+ final other => other,
+ };
+
+ /// The folder it ran in, by its own name.
+ String get folderName =>
+ cwd.split('/').where((part) => part.isNotEmpty).lastOrNull ?? cwd;
+}
+
+/// A row id for a conversation Harness did not start — the desktop's `externalDestinationId`.
+String externalDestinationId(String machineId, String sessionId) =>
+ 'external:$machineId:$sessionId';
diff --git a/mobile/lib/state/search_when.dart b/mobile/lib/state/search_when.dart
new file mode 100644
index 000000000..70b06f68b
--- /dev/null
+++ b/mobile/lib/state/search_when.dart
@@ -0,0 +1,99 @@
+/// When a search is about, read from its words: "dial last week", "yesterday",
+/// "3 days ago", "on monday". People remember a session by roughly when as
+/// often as by what; the phrase narrows the search to sessions worked on then
+/// and is taken out of the words matched against names and conversations.
+///
+/// Parsed here rather than by each machine so every machine searches the same
+/// window, in this computer's time zone.
+typedef SearchWhen = ({DateTime from, DateTime to, String phrase});
+
+const _numbers = {
+ 'a': 1,
+ 'an': 1,
+ 'one': 1,
+ 'two': 2,
+ 'three': 3,
+ 'four': 4,
+ 'five': 5,
+ 'six': 6,
+ 'seven': 7,
+ 'eight': 8,
+ 'nine': 9,
+ 'ten': 10,
+};
+
+const _weekdays = {
+ 'monday': DateTime.monday,
+ 'tuesday': DateTime.tuesday,
+ 'wednesday': DateTime.wednesday,
+ 'thursday': DateTime.thursday,
+ 'friday': DateTime.friday,
+ 'saturday': DateTime.saturday,
+ 'sunday': DateTime.sunday,
+};
+
+final _phrases = RegExp(
+ r'(?<![\p{L}\p{N}])(?:'
+ r'(?<today>today)'
+ r'|(?<yesterday>yesterday)'
+ r'|(?<thisweek>this week)'
+ r'|(?<lastweek>last week)'
+ r'|(?<thismonth>this month)'
+ r'|(?<lastmonth>last month)'
+ r'|(?<few>(?:a )?few days ago|(?:a )?couple(?: of)? days ago)'
+ r'|(?<count>\d{1,2}|a|an|one|two|three|four|five|six|seven|eight|nine|ten) (?<unit>days?|weeks?) ago'
+ // A weekday only with "on" or "last": "friday deploy" is a harness's name,
+ // "on friday" is a time.
+ r'|(?<last>last|on) (?<weekday>monday|tuesday|wednesday|thursday|friday|saturday|sunday)'
+ r')(?![\p{L}\p{N}])',
+ caseSensitive: false,
+ unicode: true,
+);
+
+/// The words with any time phrase taken out, and the window it names.
+({String words, SearchWhen? when}) parseSearchWhen(String query, DateTime now) {
+ final match = _phrases.firstMatch(query);
+ if (match == null) return (words: query, when: null);
+ final midnight = DateTime(now.year, now.month, now.day);
+ DateTime day(int offset) =>
+ DateTime(midnight.year, midnight.month, midnight.day + offset);
+ late DateTime from, to;
+ if (match.namedGroup('today') != null) {
+ (from, to) = (midnight, now);
+ } else if (match.namedGroup('yesterday') != null) {
+ (from, to) = (day(-1), midnight);
+ } else if (match.namedGroup('thisweek') != null) {
+ (from, to) = (day(1 - now.weekday), now);
+ } else if (match.namedGroup('lastweek') != null) {
+ (from, to) = (day(1 - now.weekday - 7), day(1 - now.weekday));
+ } else if (match.namedGroup('thismonth') != null) {
+ (from, to) = (DateTime(now.year, now.month), now);
+ } else if (match.namedGroup('lastmonth') != null) {
+ (from, to) = (
+ DateTime(now.year, now.month - 1),
+ DateTime(now.year, now.month),
+ );
+ } else if (match.namedGroup('few') != null) {
+ // Two to five days back, loosely.
+ (from, to) = (day(-6), day(-1));
+ } else if (match.namedGroup('count') case final count?) {
+ final n = int.tryParse(count) ?? _numbers[count.toLowerCase()] ?? 1;
+ final weeks = match.namedGroup('unit')!.toLowerCase().startsWith('week');
+ // Memory is loose: a day either side, or half a week either side.
+ final back = weeks ? n * 7 : n;
+ final slack = weeks ? 4 : 1;
+ (from, to) = (day(-back - slack), day(-back + slack + 1));
+ } else {
+ final weekday = _weekdays[match.namedGroup('weekday')!.toLowerCase()]!;
+ final strictlyBefore = match.namedGroup('last')!.toLowerCase() == 'last';
+ var back = (now.weekday - weekday) % 7;
+ if (back == 0 && strictlyBefore) back = 7;
+ (from, to) = (day(-back), day(-back + 1));
+ }
+ if (to.isAfter(now)) to = now;
+ final words = query
+ .replaceRange(match.start, match.end, ' ')
+ .replaceAll(RegExp(r'\s+'), ' ')
+ .trim();
+ return (words: words, when: (from: from, to: to, phrase: match[0]!));
+}
diff --git a/mobile/lib/state/session_content_search.dart b/mobile/lib/state/session_content_search.dart
new file mode 100644
index 000000000..bd6c36e6a
--- /dev/null
+++ b/mobile/lib/state/session_content_search.dart
@@ -0,0 +1,325 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:harness_mobile/phone/phone_search_catalog.dart'
+ show phoneAgentId;
+
+import 'external_session.dart';
+import 'search_when.dart';
+
+/// Where a machine's daemon marks each matched word in a snippet.
+const kSnippetMarkOpen = '\u0002';
+const kSnippetMarkClose = '\u0003';
+
+/// One conversation that matched a search, as its machine's daemon found it
+/// (`session_search`, cli/src/lib/sessionSearch/). The daemon has read every
+/// turn of every session on that machine; the app only ever sees the hits.
+@immutable
+class SessionContentHit {
+ const SessionContentHit({
+ required this.machineId,
+ required this.agentId,
+ required this.sessionId,
+ required this.field,
+ required this.snippet,
+ required this.together,
+ required this.score,
+ this.position = 0,
+ this.turn = 0,
+ this.at,
+ this.lastAt,
+ this.external,
+ });
+
+ final String machineId, agentId, sessionId;
+
+ /// A conversation Harness did not start, whose [agentId] is empty.
+ final ExternalSessionRef? external;
+
+ /// When the session was last worked on.
+ final DateTime? lastAt;
+
+ /// `ask`, `answer`, `tools` or `name`: which part of the turn matched.
+ final String field;
+
+ /// The words around the match, each matched word between
+ /// [kSnippetMarkOpen] and [kSnippetMarkClose].
+ final String snippet;
+
+ /// Every searched word in one turn, rather than spread across the session.
+ final bool together;
+
+ /// 0–1, higher is better: relevance blended with recency by the daemon.
+ /// Relative to that machine's best hit, so not comparable across machines.
+ final double score;
+
+ /// Where the machine ranked it, from 0. Hits from several machines merge
+ /// by this: each machine's first is as good as another's first.
+ final int position;
+ final int turn;
+
+ /// When the matching turn happened, when the transcript says.
+ final DateTime? at;
+
+ String get destinationId => external == null
+ ? phoneAgentId(machineId, agentId)
+ : externalDestinationId(machineId, sessionId);
+
+ /// The snippet as plain text, marks removed.
+ String get plainSnippet => snippet
+ .replaceAll(kSnippetMarkOpen, '')
+ .replaceAll(kSnippetMarkClose, '');
+
+ static SessionContentHit? fromJson(
+ String machineId,
+ Object? raw, {
+ int position = 0,
+ }) {
+ if (raw is! Map) return null;
+ final agentId = raw['agentId'];
+ final sessionId = raw['sessionId'];
+ final snippet = raw['snippet'];
+ final external = _external(raw, sessionId);
+ if (agentId is! String ||
+ (agentId.isEmpty && external == null) ||
+ sessionId is! String) {
+ return null;
+ }
+ final score = raw['score'];
+ final at = raw['at'];
+ final lastAt = raw['lastAt'];
+ final turn = raw['turn'];
+ return SessionContentHit(
+ machineId: machineId,
+ agentId: agentId,
+ sessionId: sessionId,
+ field: raw['field'] is String ? raw['field'] as String : 'ask',
+ snippet: snippet is String
+ ? snippet.length > 600
+ ? snippet.substring(0, 600)
+ : snippet
+ : '',
+ together: raw['together'] == true,
+ score: score is num ? score.toDouble().clamp(0, 1) : 0,
+ position: position,
+ turn: turn is int ? turn : 0,
+ at: at is int ? DateTime.fromMillisecondsSinceEpoch(at) : null,
+ lastAt: lastAt is int
+ ? DateTime.fromMillisecondsSinceEpoch(lastAt)
+ : null,
+ external: agentId.isEmpty ? external : null,
+ );
+ }
+
+ /// A hit on a conversation Harness did not start: the daemon says where it
+ /// resumes and where it ran. Null when the hit is a harness's.
+ static ExternalSessionRef? _external(Map raw, Object? sessionId) {
+ final external = raw['external'];
+ final engine = raw['engine'];
+ if (external is! Map || sessionId is! String || engine is! String) {
+ return null;
+ }
+ final cwd = external['cwd'];
+ if (cwd is! String || !cwd.startsWith('/')) return null;
+ final title = external['title'];
+ final origin = external['origin'];
+ return ExternalSessionRef(
+ sessionId: sessionId,
+ engine: engine,
+ cwd: cwd,
+ origin: origin is String ? origin : 'terminal',
+ title: title is String ? title : '',
+ open: external['open'] == true,
+ );
+ }
+
+ /// A `session_search_result` payload, or an empty list for an error.
+ static List<SessionContentHit> listFromReply(
+ String machineId,
+ Map<String, dynamic> reply,
+ ) {
+ final hits = reply['hits'];
+ if (reply['error'] != null || hits is! List) return const [];
+ return [
+ for (final (position, raw) in hits.take(100).indexed)
+ ?SessionContentHit.fromJson(machineId, raw, position: position),
+ ];
+ }
+}
+
+/// Asks one machine for [words], only in sessions worked on in [when] when
+/// there is one.
+typedef SessionSearchAsk = Future<List<SessionContentHit>?> Function(
+ String machineId,
+ String words,
+ SearchWhen? when,
+);
+
+/// Asks every reachable machine what was said in its sessions, as the person
+/// types in Find (the desktop's Cmd-P, `desktop/lib/state/session_content_search.dart`). Debounced so a burst of keys is one question; an answer to
+/// an older question is dropped. Hits are keyed by the harness row they belong
+/// to, and a machine that cannot answer (offline, or a CLI that predates
+/// `session_search`) simply adds none.
+class SessionContentSearch extends ChangeNotifier {
+ SessionContentSearch({
+ required this.machines,
+ required this.ask,
+ this.debounce = const Duration(milliseconds: 110),
+ DateTime Function()? now,
+ }) : _now = now ?? DateTime.now;
+
+ /// The machines to ask right now.
+ final Iterable<String> Function() machines;
+ final SessionSearchAsk ask;
+ final Duration debounce;
+ final DateTime Function() _now;
+
+ /// What [query] asks for: its words, and when, if it says.
+ ({String words, SearchWhen? when}) read(String query) =>
+ parseSearchWhen(query.trim(), _now());
+
+ Map<String, SessionContentHit> _hits = const {};
+ Map<String, SessionContentHit> get hits => _hits;
+
+ /// The hits that vouch for [query]. While its own answer is on the way, an
+ /// earlier answer's hit counts only if its snippet shows every word of it:
+ /// a hit found for "mob" says nothing about "mob swipe".
+ Map<String, SessionContentHit> hitsFor(String query) {
+ final wanted = query.trim();
+ if (_answered == null || _hits.isEmpty) return const {};
+ if (_answered == wanted) return _hits;
+ // Read on every row's build: worked out once per query and answer.
+ final cached = _vouched;
+ if (cached != null &&
+ cached.query == wanted &&
+ identical(cached.hits, _hits)) {
+ return cached.vouched;
+ }
+ final vouched = _vouch(wanted);
+ _vouched = (query: wanted, hits: _hits, vouched: vouched);
+ return vouched;
+ }
+
+ ({
+ String query,
+ Map<String, SessionContentHit> hits,
+ Map<String, SessionContentHit> vouched,
+ })?
+ _vouched;
+
+ Map<String, SessionContentHit> _vouch(String wanted) {
+ // A hit found for another time says nothing about this one. Compared by
+ // the phrase: "today" ends now, and now moves on every read.
+ final now = read(wanted), then = read(_answered!);
+ if (now.when?.phrase.toLowerCase() != then.when?.phrase.toLowerCase()) {
+ return const {};
+ }
+ final words = now.words
+ .toLowerCase()
+ .split(RegExp(r'\s+'))
+ .where((word) => word.isNotEmpty)
+ .toList();
+ return {
+ for (final entry in _hits.entries)
+ if (_shows(entry.value.plainSnippet.toLowerCase(), words))
+ entry.key: entry.value,
+ };
+ }
+
+ static final _wordStart = RegExp(r'[^\p{L}\p{N}]', unicode: true);
+
+ static bool _shows(String text, List<String> words) => words.every((word) {
+ for (
+ var at = text.indexOf(word);
+ at >= 0;
+ at = text.indexOf(word, at + 1)
+ ) {
+ if (at == 0 || _wordStart.hasMatch(text[at - 1])) return true;
+ }
+ return false;
+ });
+
+ /// The query the current [hits] answer, or null while none have arrived.
+ String? get answered => _answered;
+ String? _answered;
+
+ String _query = '';
+ int _generation = 0;
+ Timer? _timer;
+ bool _disposed = false;
+
+ /// Two letters at least: one matches too much of everything to mean anything.
+ /// A time on its own ("yesterday") is a search too: what was worked on then.
+ bool searchable(String query) {
+ final read = this.read(query);
+ return read.when != null || read.words.runes.length >= 2;
+ }
+
+ void search(String query) {
+ final next = query.trim();
+ if (next == _query) return;
+ final previous = _query;
+ _query = next;
+ _timer?.cancel();
+ final generation = ++_generation;
+ // Typing more of the same words keeps the last answer on screen until the
+ // new one lands; anything else would show rows for words no longer typed.
+ if (!next.toLowerCase().startsWith(previous.toLowerCase()) ||
+ !searchable(next)) {
+ if (_hits.isNotEmpty || _answered != null) {
+ _hits = const {};
+ _answered = null;
+ notifyListeners();
+ }
+ }
+ // Nothing to ask while every machine is offline: no timer, no work.
+ if (!searchable(next) || machines().isEmpty) return;
+ final read = this.read(next);
+ _timer = Timer(
+ debounce,
+ () => _run(next, read.words, read.when, generation),
+ );
+ }
+
+ Future<void> _run(
+ String query,
+ String words,
+ SearchWhen? when,
+ int generation,
+ ) async {
+ final found = <String, SessionContentHit>{};
+ var first = true;
+ await Future.wait([
+ for (final machineId in machines())
+ ask(machineId, words, when).then((hits) {
+ if (_disposed || generation != _generation) return;
+ if (first) {
+ // The first answer replaces what an earlier question found.
+ first = false;
+ _hits = const {};
+ }
+ for (final hit in hits ?? const <SessionContentHit>[]) {
+ final id = hit.destinationId;
+ final known = found[id];
+ // One row per harness: its best conversation, earlier ones included.
+ if (known == null ||
+ (hit.together && !known.together) ||
+ (hit.together == known.together &&
+ hit.position < known.position)) {
+ found[id] = hit;
+ }
+ }
+ _hits = Map.unmodifiable(found);
+ _answered = query;
+ notifyListeners();
+ }, onError: (_) {}),
+ ]);
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/terminal/key_hints.dart b/mobile/lib/terminal/key_hints.dart
index bef802c20..ab075404c 100644
--- a/mobile/lib/terminal/key_hints.dart
+++ b/mobile/lib/terminal/key_hints.dart
@@ -111,12 +111,13 @@ bool _isProcessControl(KeyChord chord) =>
/// question` — move through an open one, or leave it;
/// - `shift+← edit last queued message` — take back a queued message;
/// - `ctrl+o copy` — the warnings view;
-/// - `ctrl+t to view transcript`.
+/// - `ctrl+t to view transcript`;
+/// - `shift+tab to cycle` — Claude Code's modes (plan, accept edits), one tap instead of two.
///
/// Matched on the WORDS, never the key: the key is the person's to remap, and
/// the one printed beside the words is the one pressed.
final RegExp _offered = RegExp(
- r'^(answer|skip|main prompt|next question|prev(ious)? question|edit last queued|copy|view transcript)\b',
+ r'^(answer|skip|main prompt|next question|prev(ious)? question|edit last queued|copy|view transcript|cycle)\b',
caseSensitive: false,
);
diff --git a/mobile/lib/terminal/question_pane_watcher.dart b/mobile/lib/terminal/question_pane_watcher.dart
index 224d14652..3ae21545b 100644
--- a/mobile/lib/terminal/question_pane_watcher.dart
+++ b/mobile/lib/terminal/question_pane_watcher.dart
@@ -62,6 +62,12 @@ class QuestionPaneWatcher extends ChangeNotifier {
/// nobody could hit.
List<KeyHint> get hints => _hints;
+ /// The pane's own chrome says `esc to interrupt` — Claude Code's and Codex's working line. The
+ /// page offers its `esc` on this as well as on the machine's word that the agent is working,
+ /// which can lag the screen by a beat.
+ bool get interruptible => _interruptible;
+ bool _interruptible = false;
+
/// How long the buffer must be quiet before it is read.
///
/// ⚠️ Long enough to outlast a repaint, short enough that the pad follows the
@@ -118,10 +124,9 @@ class QuestionPaneWatcher extends ChangeNotifier {
? parseQueuedQuestions(lines)
: null,
);
- // Codex only: every hint offered is one of its own (see `parseKeyHints`).
- final keys = _readHints(
- engine == QuestionEngine.codex ? parseKeyHints(lines) : const <KeyHint>[],
- );
+ // Every hint offered is one of the engines' own (see `parseKeyHints`): Codex's, and Claude
+ // Code's `shift+tab to cycle`.
+ final keys = _readHints(parseKeyHints(lines));
if (dialog.again || queue.again || keys.again) {
// ⚠️ **Ask for the next read rather than waiting for one.** Reads are
// driven by terminal output, and the engine may print NOTHING after the
@@ -132,7 +137,24 @@ class QuestionPaneWatcher extends ChangeNotifier {
_debounce?.cancel();
_debounce = Timer(_settle, _read);
}
- _publish(dialog.view, queue.queued, keys.hints);
+ _publish(
+ dialog.view,
+ queue.queued,
+ keys.hints,
+ interruptible: _saysInterrupt(lines),
+ );
+ }
+
+ /// Whether the bottom of the pane offers `esc to interrupt`.
+ static bool _saysInterrupt(List<String> lines) {
+ var seen = 0;
+ for (var i = lines.length - 1; i >= 0 && seen < 10; i--) {
+ final line = lines[i];
+ if (line.trim().isEmpty) continue;
+ seen++;
+ if (line.toLowerCase().contains('esc to interrupt')) return true;
+ }
+ return false;
}
/// What [found] makes of the open dialog: the view to keep, and whether to
@@ -198,16 +220,19 @@ class QuestionPaneWatcher extends ChangeNotifier {
void _publish(
QuestionPaneView? view,
QueuedQuestions? queued,
- List<KeyHint> hints,
- ) {
+ List<KeyHint> hints, {
+ bool interruptible = false,
+ }) {
if (identical(view, _view) &&
queued == _queued &&
- identical(hints, _hints)) {
+ identical(hints, _hints) &&
+ interruptible == _interruptible) {
return;
}
_view = view;
_queued = queued;
_hints = hints;
+ _interruptible = interruptible;
notifyListeners();
}
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index d5eb5e62e..64fe826cd 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -262,6 +262,32 @@ class TerminalSession extends ChangeNotifier {
/// cleared by every reopen (see `_armInitialKeyframeWatchdog`, which treats
/// the same null as "no keyframe arrived").
bool get hasRenderedFrame => _expectedSeq != null;
+
+ /// Whether [terminal] is a screen KEPT from the last time this agent was open on this phone,
+ /// standing in until this attach's first keyframe replaces it. See [seedScreen].
+ bool get showingKeptScreen => _showingKeptScreen;
+ bool _showingKeptScreen = false;
+
+ /// Something to show: this attach's first frame, or a kept screen standing in for it.
+ bool get hasScreen => hasRenderedFrame || _showingKeptScreen;
+
+ /// Shows [kept] — the screen this agent had when the phone last left it — until the live stream's
+ /// first keyframe lands and replaces it.
+ ///
+ /// ⚠️ **What makes switching back to an agent instant.** An attach waits a network round trip for
+ /// its keyframe; until then the page showed a skeleton. The kept screen is what the reader last
+ /// saw of this agent — seconds or minutes stale, which the header's "Attaching…" says — and the
+ /// keyframe that follows replaces it whole.
+ ///
+ /// Rebound to this session: the kept terminal's callbacks still named the session it came from,
+ /// which is gone.
+ void seedScreen(Terminal kept) {
+ if (hasRenderedFrame || _disposed) return;
+ _bindTerminal(kept);
+ terminal = kept;
+ _showingKeptScreen = true;
+ notifyListeners();
+ }
int _lastRenderedSeq = -1;
int _framesSinceAck = 0;
int _renderedSinceAckBytes = 0;
@@ -794,6 +820,7 @@ class TerminalSession extends ChangeNotifier {
..write(decoded.text);
_bindTerminal(replacement);
terminal = replacement;
+ _showingKeptScreen = false;
cols = _clampCols(nextCols);
rows = _clampRows(nextRows);
_utf8Tail = decoded.tail;
@@ -938,7 +965,13 @@ class TerminalSession extends ChangeNotifier {
_applyCursorVisibility();
}
+ /// Bumped once per chunk of output written — what a reader scrolled up in the history watches to
+ /// know there is something newer below. Its own notifier, not this session's: output is the most
+ /// frequent event there is, and nothing else here should rebuild for it.
+ final ValueNotifier<int> outputTicks = ValueNotifier(0);
+
void _writeTerminalText(String text) {
+ outputTicks.value++;
terminal.setCursorVisibleMode(_remoteCursorVisible);
terminal.write(text);
_remoteCursorVisible = terminal.cursorVisibleMode;
@@ -1042,6 +1075,11 @@ class TerminalSession extends ChangeNotifier {
/// the injection from there: it adapts slash commands to the pane's engine and retries the
/// submit Enter. A client typing bytes can do neither — which is exactly how Codex ended up
/// holding a composed line unsent, its Enter arriving in the same read as the text.
+ /// Where a finished voice take goes instead of [sendComposerText], while the page has a reason
+ /// to route it — an agent's question dialog is open, and a paste-and-Return would answer it
+ /// blind. Set and cleared by the page; null the rest of the time.
+ Future<bool> Function(String text)? voiceDeliver;
+
Future<bool> sendComposerText(String text) async {
if (!acceptsInput) return false;
final content = text.trimRight();
@@ -1695,6 +1733,7 @@ class TerminalSession extends ChangeNotifier {
_disposed = true;
_generation++;
_cancelTimers();
+ outputTicks.dispose();
super.dispose();
}
}
diff --git a/mobile/lib/terminal/terminal_theme_store.dart b/mobile/lib/terminal/terminal_theme_store.dart
index 58b590e0a..12d4dc4e6 100644
--- a/mobile/lib/terminal/terminal_theme_store.dart
+++ b/mobile/lib/terminal/terminal_theme_store.dart
@@ -22,7 +22,7 @@ enum TerminalThemeChoice {
/// Today's behaviour, and still the default: ground and cursor follow the
/// palette chosen in Settings ▸ Appearance, ANSI ramp from `darkTerminalTheme`.
matchApp(
- 'Match app appearance',
+ 'Same as the app',
'Ground and cursor follow Settings ▸ Appearance',
),
diff --git a/mobile/lib/terminal/terminal_typography.dart b/mobile/lib/terminal/terminal_typography.dart
index a60e6662f..929b9cdc7 100644
--- a/mobile/lib/terminal/terminal_typography.dart
+++ b/mobile/lib/terminal/terminal_typography.dart
@@ -1,3 +1,5 @@
+import 'package:flutter/foundation.dart';
+
import '../core/apple_fonts.dart';
/// The default terminal face, per platform.
@@ -74,5 +76,12 @@ String get terminalFontFamily =>
List<String> get terminalFontFallback =>
hasAppleFonts ? macTerminalFontFallback : linuxTerminalFontFallback;
-/// The default terminal font size — the same on every platform.
-const terminalFontSize = 13.0;
+/// The default terminal font size: 13 on a desktop, 14 on a phone.
+///
+/// Tried on an iPhone: 13 read as small print, 16 as far too big. Monospace is wider than the
+/// proportional faces reading apps use — X sets posts at about 15 — so 14 here reads about as large
+/// as those, and keeps about 43 columns on a 390pt iPhone.
+double get terminalFontSize => switch (defaultTargetPlatform) {
+ TargetPlatform.iOS || TargetPlatform.android => 14.0,
+ _ => 13.0,
+};
diff --git a/mobile/lib/viewer/code_link.dart b/mobile/lib/viewer/code_link.dart
new file mode 100644
index 000000000..095c41127
--- /dev/null
+++ b/mobile/lib/viewer/code_link.dart
@@ -0,0 +1,228 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+
+import '../e2ee/bytes.dart';
+import '../e2ee/code_pake.dart';
+import '../e2ee/cpace.dart';
+import '../e2ee/envelope.dart';
+import '../e2ee/keys.dart';
+import '../e2ee/primitives.dart';
+import 'password_link.dart'
+ show
+ PasswordLinkFailed,
+ PasswordLinkResult,
+ PasswordLinked,
+ RelaySocketFactory,
+ defaultRelaySocket;
+
+/// Pairs this phone with [machineId] using the one-time code its desktop app showed in the
+/// "Add phone" QR — no remote password.
+///
+/// The daemon's live-code pairing (`manager.ts` `onPairIntent` / `onPake`): this phone says it is
+/// waiting to pair (`e2e_pair_intent`), and the desktop app, which put the code in the QR, hands the
+/// same code to its own daemon (`POST /api/pair`) the moment the intent arrives. The two sides then
+/// run CPace over it and pin each other's identity, as the password link does. A wrong code fails
+/// the MAC; the code is used once and the daemon holds the intent for 60 s.
+///
+/// [timeout] covers the wait for the desktop to answer: it polls every second or two.
+Future<PasswordLinkResult> linkWithCode({
+ required String machineId,
+ required String code,
+ required String label,
+ required E2eeIdentity identity,
+ required String accessToken,
+ required String wsBaseUrl,
+ required String autonomousEnv,
+ RelaySocketFactory socket = defaultRelaySocket,
+ Duration timeout = const Duration(seconds: 50),
+}) async {
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws')
+ .replace(queryParameters: {'autonomousEnv': autonomousEnv});
+ final channel = socket(uri, [accessToken]);
+ final run = CodeLinkRun(
+ machineId: machineId,
+ code: code,
+ label: label,
+ identity: identity,
+ send: (type, payload) =>
+ channel.sink.add(jsonEncode({'type': type, 'payload': payload})),
+ );
+ try {
+ await channel.ready;
+ return await run
+ .drive(
+ channel.stream.map(
+ (raw) => raw is String ? jsonObjectOf(utf8Bytes(raw)) : null,
+ ),
+ )
+ .timeout(timeout, onTimeout: () => const PasswordLinkFailed('TIMEOUT'));
+ } catch (_) {
+ return const PasswordLinkFailed('CONNECTION_ERROR');
+ } finally {
+ unawaited(channel.sink.close());
+ }
+}
+
+/// The joiner ('b') side of the machine's live-code state machine, over any stream of frames —
+/// the socket in [linkWithCode], a simulated machine in tests.
+class CodeLinkRun {
+ CodeLinkRun({
+ required this.machineId,
+ required this.code,
+ required this.label,
+ required this.identity,
+ required this.send,
+ Uint8List? pairId,
+ }) : _pairId = pairId ?? secureRandomBytes(16);
+
+ final String machineId;
+ final String code;
+ final String label;
+ final E2eeIdentity identity;
+ final void Function(String type, Map<String, Object> payload) send;
+
+ final Uint8List _pairId;
+ late final String _pairIdB64 = b64e(_pairId);
+ final String _requestId = b64e(secureRandomBytes(16));
+ late final String _ci = pairContext(machineId);
+ bool _selected = false;
+ Uint8List? _isk;
+ Uint8List? _transcript;
+ Uint8List? _machinePub;
+
+ Future<PasswordLinkResult> drive(Stream<Map<String, dynamic>?> frames) async {
+ send('machine_select', {'machineId': machineId});
+ await for (final frame in frames) {
+ if (frame == null) continue;
+ final PasswordLinkResult? result;
+ try {
+ result = await step(frame);
+ } catch (_) {
+ return const PasswordLinkFailed('PROTOCOL_ERROR');
+ }
+ if (result != null) return result;
+ }
+ return const PasswordLinkFailed('CONNECTION_CLOSED');
+ }
+
+ /// One frame from the machine; a result once the pairing is decided, else null.
+ Future<PasswordLinkResult?> step(Map<String, dynamic> frame) async {
+ final type = frame['type'];
+ final payload = frame['payload'] is Map<String, dynamic>
+ ? frame['payload'] as Map<String, dynamic>
+ : const <String, dynamic>{};
+ if (!_selected) {
+ if (payload['machineId'] != machineId) return null;
+ if (type == 'connected') {
+ _selected = true;
+ send('e2e_pair_intent', {
+ 'requestId': _requestId,
+ 'pairId': _pairIdB64,
+ 'label': label,
+ 'role': 'web',
+ });
+ return null;
+ }
+ if (type == 'machine_select_error') {
+ return PasswordLinkFailed(_codeOr(payload['error'], 'SELECT_FAILED'));
+ }
+ return null;
+ }
+ if (type == 'e2e_pair_intent_result' &&
+ payload['requestId'] == _requestId) {
+ return payload['accepted'] == true
+ ? null
+ : PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_REFUSED'));
+ }
+ if (type != 'e2e_pake' || payload['pairId'] != _pairIdB64) return null;
+ final error = payload['error'];
+ if (error != null) return PasswordLinkFailed('$error');
+ return switch (payload['round']) {
+ 1 => _answerShare(payload),
+ 3 => await _answerIdentity(payload),
+ 5 => _finish(payload),
+ _ => null,
+ };
+ }
+
+ /// Round 1 in, round 2 out: our CPace share, and a MAC only the right code could have made.
+ PasswordLinkResult? _answerShare(Map<String, dynamic> payload) {
+ final theirs = b64d(payload['ya'] as String);
+ final ours = cpaceStart(codeCpaceGenerator(code, _pairId, _ci));
+ final isk = _isk = cpaceIsk(
+ _pairId,
+ cpaceShared(theirs, ours.scalar),
+ theirs,
+ ours.share,
+ );
+ final transcript = _transcript = transcriptHash(
+ _pairId,
+ _ci,
+ theirs,
+ ours.share,
+ );
+ send('e2e_pake', {
+ 'pairId': _pairIdB64,
+ 'round': 2,
+ 'yb': b64e(ours.share),
+ 'mac': b64e(macTag(kcKeys(isk, _ci).web, transcript)),
+ });
+ return null;
+ }
+
+ /// Round 3 in, round 4 out: the machine proves the code too and hands over its identity, bound
+ /// to this transcript; ours goes back the same way.
+ Future<PasswordLinkResult?> _answerIdentity(
+ Map<String, dynamic> payload,
+ ) async {
+ final isk = _isk, transcript = _transcript;
+ if (isk == null || transcript == null) {
+ return const PasswordLinkFailed('PROTOCOL_ERROR');
+ }
+ final mac = b64d(payload['mac'] as String);
+ if (!macVerify(kcKeys(isk, _ci).adapter, transcript, mac)) {
+ return const PasswordLinkFailed('CODE_MISMATCH');
+ }
+ final key = pairKey(isk, _ci);
+ final opened = aeadOpen(
+ key,
+ 3,
+ utf8Bytes('e2e-id'),
+ b64d(payload['enc'] as String),
+ );
+ final claim = opened == null ? null : jsonObjectOf(opened);
+ final id = claim?['id'], sig = claim?['sig'];
+ if (id is! String || sig is! String) {
+ return const PasswordLinkFailed('CODE_MISMATCH');
+ }
+ final machinePub = b64d(id);
+ if (!await pairBindVerify(machinePub, transcript, b64d(sig))) {
+ return const PasswordLinkFailed('CODE_MISMATCH');
+ }
+ _machinePub = machinePub;
+ final ours = jsonEncode({
+ 'id': b64e(identity.pub),
+ 'sig': b64e(await pairBindSig(identity, transcript)),
+ });
+ send('e2e_pake', {
+ 'pairId': _pairIdB64,
+ 'round': 4,
+ 'enc': b64e(aeadSeal(key, 4, utf8Bytes('e2e-id'), utf8Bytes(ours))),
+ });
+ return null;
+ }
+
+ /// The fingerprint is computed here from the pinned key, not taken from the clear frame.
+ PasswordLinkResult _finish(Map<String, dynamic> payload) {
+ final machinePub = _machinePub;
+ if (payload['ok'] != true || machinePub == null) {
+ return PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_FAILED'));
+ }
+ return PasswordLinked(machinePub, fingerprint(machinePub));
+ }
+}
+
+String _codeOr(Object? value, String fallback) =>
+ value is String && value.isNotEmpty ? value : fallback;
diff --git a/mobile/lib/viewer/direct_auth.dart b/mobile/lib/viewer/direct_auth.dart
index 49e13afe8..f9571c916 100644
--- a/mobile/lib/viewer/direct_auth.dart
+++ b/mobile/lib/viewer/direct_auth.dart
@@ -36,7 +36,20 @@ class DirectAuth implements AccessTokenSource {
issuer: issuer,
);
- Future<void> signOut() => session.clear();
+ /// A session Harness issued itself is ended at the backend too, so its
+ /// refresh token is dead even if a copy of this phone's storage turns up.
+ /// Only briefly waited on: signing out never hangs on the network.
+ Future<void> signOut() async {
+ if (await session.issuer() == SessionIssuer.harness) {
+ final refreshToken = await session.refreshToken();
+ if (refreshToken != null && refreshToken.isNotEmpty) {
+ try {
+ await api.revoke(refreshToken).timeout(const Duration(seconds: 3));
+ } catch (_) {}
+ }
+ }
+ await session.clear();
+ }
@override
Future<String> accessToken({bool force = false, String? failedToken}) async {
@@ -77,7 +90,7 @@ class DirectAuth implements AccessTokenSource {
// A refresh token only renews where it was issued.
final tokens = switch (await session.issuer()) {
SessionIssuer.emailCode => await emailCodes.refresh(refreshToken),
- SessionIssuer.sso => await api.refresh(
+ SessionIssuer.sso || SessionIssuer.harness => await api.refresh(
refreshToken,
autonomousEnv: autonomousEnv,
),
diff --git a/mobile/lib/viewer/direct_auth_api.dart b/mobile/lib/viewer/direct_auth_api.dart
index 812bc3e4c..de35ef19c 100644
--- a/mobile/lib/viewer/direct_auth_api.dart
+++ b/mobile/lib/viewer/direct_auth_api.dart
@@ -78,13 +78,18 @@ class DirectAuthApi {
final data = unwrapApiResponse(
await _dio.post(
'/api/auth/authorize-native',
- data: {'redirectUri': redirectUri, 'autonomousEnv': config.autonomousEnv},
+ data: {
+ 'redirectUri': redirectUri,
+ 'autonomousEnv': config.autonomousEnv,
+ },
),
);
final url = data is Map ? data['authorizeUrl'] : null;
final tx = data is Map ? data['tx'] : null;
if (url is! String || url.isEmpty || tx is! String || tx.isEmpty) {
- throw const DirectAuthException('The server did not return a sign-in page.');
+ throw const DirectAuthException(
+ 'The server did not return a sign-in page.',
+ );
}
return (authorizeUrl: url, tx: tx);
}
@@ -104,6 +109,46 @@ class DirectAuthApi {
(throw const DirectAuthException('Sign-in returned no access token.'));
}
+ /// Trade the one-time code in a signed-in computer's Add Phone QR for a
+ /// session of this phone's own — scan to sign in, no emailed code. [label]
+ /// is what the phone calls itself, for the account's list of devices.
+ ///
+ /// A spent or expired code is the backend's 401 and its own sentence.
+ Future<IssuedTokens> redeemHandoff(
+ String code, {
+ required String label,
+ }) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(
+ '/api/auth/handoff/redeem',
+ data: {'code': code, 'label': label},
+ );
+ } on DioException {
+ throw const DirectAuthException(
+ 'Could not reach Harness. Check your connection and scan again.',
+ );
+ }
+ final body = res.data is Map ? res.data as Map : const {};
+ final tokens = body['success'] == true
+ ? IssuedTokens.fromData(body['data'])
+ : null;
+ if (tokens != null) return tokens;
+ final error = body['error'] is Map ? body['error'] as Map : const {};
+ final message = error['message'];
+ throw DirectAuthException(
+ message is String && message.isNotEmpty
+ ? message
+ : 'That code didn’t work. Scan the new one.',
+ );
+ }
+
+ /// End a session the backend issued itself ([SessionIssuer.harness]).
+ /// Best effort: the caller clears this phone's copy whatever the answer.
+ Future<void> revoke(String refreshToken) async {
+ await _dio.post('/api/auth/revoke', data: {'refreshToken': refreshToken});
+ }
+
/// authSession.ts `refreshRequest`, down to its one subtle rule: only a 401 or
/// `REFRESH_TOKEN_INVALID` means the session is dead. An unusable refresh token and a real outage
/// both come back as the same 503, and reading that as dead would delete a refresh token nothing
diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dart
index 17d0dc13c..eb52c9042 100644
--- a/mobile/lib/viewer/direct_link.dart
+++ b/mobile/lib/viewer/direct_link.dart
@@ -5,6 +5,7 @@ import '../core/config.dart';
import '../e2ee/keys.dart';
import 'direct_auth.dart';
import 'direct_auth_api.dart';
+import 'code_link.dart';
import 'password_link.dart';
import 'viewer_key_store.dart';
@@ -64,6 +65,54 @@ class DirectLink implements PeerLinkClient {
}
}
+ /// The QR's one-time code in place of the password: the same pin, from [linkWithCode].
+ @override
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ }) async {
+ final String token;
+ try {
+ token = await auth.accessToken();
+ } on DirectAuthException catch (error) {
+ return CliLinkConnectResult(error: error.message);
+ }
+ final result = await linkWithCode(
+ machineId: machineId,
+ code: code,
+ label: label,
+ identity: await keys.identity(),
+ accessToken: token,
+ wsBaseUrl: config.wsBaseUrl,
+ autonomousEnv: config.autonomousEnv,
+ socket: socket,
+ );
+ switch (result) {
+ case PasswordLinked(:final peerPub, :final fingerprint):
+ await keys.pin(machineId, peerPub);
+ return CliLinkConnectResult(
+ linkedMachineId: machineId,
+ fingerprint: fingerprint,
+ );
+ case PasswordLinkFailed(:final code):
+ final name = displayName == null || displayName.isEmpty
+ ? 'the computer'
+ : displayName;
+ return CliLinkConnectResult(
+ error: switch (code) {
+ 'CODE_MISMATCH' =>
+ 'That code didn’t match. Scan the new one on $name.',
+ 'TIMEOUT' => 'Keep “Add phone” open on $name, then scan again.',
+ 'PAIRING_BUSY' =>
+ '$name is pairing with something else. Try again.',
+ _ => 'Couldn’t connect to $name ($code).',
+ },
+ );
+ }
+ }
+
@override
Future<CliLinkListResult> list() async => CliLinkListResult(
machines: [
diff --git a/mobile/lib/viewer/email_code_login.dart b/mobile/lib/viewer/email_code_login.dart
index ac57a7893..0577f64ad 100644
--- a/mobile/lib/viewer/email_code_login.dart
+++ b/mobile/lib/viewer/email_code_login.dart
@@ -21,4 +21,12 @@ class EmailCodeLogin {
final tokens = await _api.signIn(email: email, code: code);
await auth.signIn(tokens, issuer: SessionIssuer.emailCode);
}
+
+ /// The other way in, with no email at all: the one-time code a signed-in
+ /// computer's Add Phone QR carries, redeemed at the Harness backend for a
+ /// session of its own.
+ Future<void> signInWithScan(String code, {required String label}) async {
+ final tokens = await auth.api.redeemHandoff(code, label: label);
+ await auth.signIn(tokens, issuer: SessionIssuer.harness);
+ }
}
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 987799209..e47f12b06 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -22,6 +22,7 @@ import '../terminal/terminal_link_opener.dart';
import '../terminal/remote_media_download.dart';
import '../terminal/terminal_links.dart';
import '../terminal/terminal_prompt_zone.dart';
+import '../phone/tty.dart';
import '../terminal/terminal_session.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
@@ -93,6 +94,14 @@ class TerminalPanel extends StatefulWidget {
final bool showHeader;
final int focusRequest;
+ /// Where the reader is while scrolled up in the history — tmux's copy-mode position,
+ /// `[above/total]`: lines between the view and the end, and lines of history in all — or null at
+ /// the end, following the stream. Null for a host that draws no position.
+ final ValueNotifier<({int above, int total})?>? scrollback;
+
+ /// Bumped by the host to go back to the end and follow the stream again — the position's tap.
+ final int jumpToEndRequest;
+
/// Takes over the tap that would raise the software keyboard. Null leaves it
/// to xterm, which is what every desktop tile does.
///
@@ -108,6 +117,10 @@ class TerminalPanel extends StatefulWidget {
/// jumping up would cover half of what they were reading.
final VoidCallback? onInputTap;
+ /// A tap on a row of output, with that row's text — before [onInputTap] is considered. True
+ /// when the host took it: on the phone, an answer's own line while a question is open.
+ final bool Function(String line)? onLineTap;
+
/// Whether this tile's composer textbox is showing. Only consulted for a remote machine.
final bool composerVisible;
final bool readOnly;
@@ -137,7 +150,10 @@ class TerminalPanel extends StatefulWidget {
this.compactHeader = false,
this.showHeader = true,
this.focusRequest = 0,
+ this.scrollback,
+ this.jumpToEndRequest = 0,
this.onInputTap,
+ this.onLineTap,
this.composerVisible = false,
this.readOnly = false,
this.notice,
@@ -240,6 +256,7 @@ class _TerminalPanelState extends State<TerminalPanel>
WidgetsBinding.instance.addObserver(this);
widget.session.attachViewport(this);
widget.session.addListener(_onSessionChanged);
+ widget.session.outputTicks.addListener(_onOutput);
terminalFontStore.addListener(_onFontChanged);
// Colours repaint the view in place — no relayout, no resize frame — but
// they still need a rebuild to reach it, and this widget reads the store
@@ -282,6 +299,7 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
void didUpdateWidget(TerminalPanel oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (oldWidget.jumpToEndRequest != widget.jumpToEndRequest) _jumpToEnd();
if (!identical(oldWidget.session, widget.session)) {
_closeFind(restore: false, focus: false, rebuild: false);
_clearLastFind();
@@ -290,9 +308,18 @@ class _TerminalPanelState extends State<TerminalPanel>
_previewProgress.value = null;
oldWidget.session.setCursorBlinkPhase(true);
oldWidget.session.removeListener(_onSessionChanged);
+ oldWidget.session.outputTicks.removeListener(_onOutput);
oldWidget.session.detachViewport(this);
widget.session.attachViewport(this);
widget.session.addListener(_onSessionChanged);
+ widget.session.outputTicks.addListener(_onOutput);
+ // A new agent starts at its end. Cleared after the frame: this is build.
+ final scrollback = widget.scrollback;
+ if (scrollback != null) {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (_) => scrollback.value = null,
+ );
+ }
_composerFocusPending = false;
_cancelDialInertia();
_controller.clearSelection();
@@ -363,6 +390,7 @@ class _TerminalPanelState extends State<TerminalPanel>
_observeLinkModifiers(false);
widget.session.setCursorBlinkPhase(true);
widget.session.removeListener(_onSessionChanged);
+ widget.session.outputTicks.removeListener(_onOutput);
widget.session.detachViewport(this);
terminalFontStore.removeListener(_onFontChanged);
terminalThemeStore.removeListener(_onFontChanged);
@@ -1044,6 +1072,16 @@ class _TerminalPanelState extends State<TerminalPanel>
_lastInertiaMicros = null;
}
+ /// Copies what is selected and lets it go — the phone's Copy: a long press, then this.
+ Future<void> _copySelection() async {
+ final selection = _controller.selection;
+ if (selection == null) return;
+ final text = widget.session.terminal.buffer.getText(selection);
+ _controller.clearSelection();
+ await Clipboard.setData(ClipboardData(text: text));
+ HapticFeedback.lightImpact();
+ }
+
Future<void> _copyOrPaste() async {
final terminal = widget.session.terminal;
final selection = _controller.selection;
@@ -1210,6 +1248,59 @@ class _TerminalPanelState extends State<TerminalPanel>
if (!_scrollController.hasClients) return;
final position = _scrollController.position;
_followTail = position.maxScrollExtent - position.pixels < 1;
+ _publishScrollback(position);
+ }
+
+ /// Tells the host where the reader is — see [TerminalPanel.scrollback].
+ void _publishScrollback(ScrollPosition position) {
+ final scrollback = widget.scrollback;
+ if (scrollback == null) return;
+ if (_followTail || _find != null) {
+ scrollback.value = null;
+ return;
+ }
+ final line = _laidOutTerminalView()?.renderTerminal.lineHeight ?? 0;
+ if (line <= 0) return;
+ final terminal = widget.session.terminal;
+ final next = (
+ above: ((position.maxScrollExtent - position.pixels) / line).round(),
+ total: math.max(0, terminal.buffer.lines.length - terminal.viewHeight),
+ );
+ if (scrollback.value != next) scrollback.value = next;
+ }
+
+ bool _scrollbackPending = false;
+
+ /// Output arrived. Below a reader scrolled up in the history the view holds still, and the
+ /// position counts the new lines — once per frame, after the layout that placed them.
+ void _onOutput() {
+ if (_followTail || !widget.visible || widget.scrollback == null) return;
+ if (_scrollbackPending) return;
+ _scrollbackPending = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _scrollbackPending = false;
+ if (!mounted || !_scrollController.hasClients) return;
+ _publishScrollback(_scrollController.position);
+ });
+ }
+
+ /// Back to the end, following the stream again — the host's position tap.
+ ///
+ /// Runs from `didUpdateWidget`, inside a build, so [scrollback] is left to the host that asked —
+ /// it clears it with the tap — and to the scroll that follows.
+ void _jumpToEnd() {
+ _cancelDialInertia();
+ // A fling still coasting up through the history would carry on past the tap and take the view
+ // straight back off the end: stopped where it is, first.
+ //
+ // Jumped to the laid-out end, so the scroll it reports reads as "at the end"; the layout the
+ // render asks for below then settles it against any output since.
+ if (_scrollController.hasClients) {
+ final position = _scrollController.position;
+ position.jumpTo(position.maxScrollExtent);
+ }
+ _followTail = true;
+ _laidOutTerminalView()?.scrollToBottom();
}
void _onScrollChanged() {
@@ -1250,12 +1341,25 @@ class _TerminalPanelState extends State<TerminalPanel>
return;
}
_inputTapClaimed = false;
- if (!isPromptTap(_viewTerminal.buffer, cell.y)) return;
+ final buffer = _viewTerminal.buffer;
+ if (cell.y >= 0 &&
+ cell.y < buffer.lines.length &&
+ (widget.onLineTap?.call(buffer.lines[cell.y].getText()) ?? false)) {
+ return;
+ }
+ if (!isPromptTap(buffer, cell.y)) return;
widget.onInputTap?.call();
}
+ /// Whether a tap on a link opens it. On a phone, always: there is no ⌘ or ctrl to hold, and a
+ /// URL or `file:line` you cannot open by touching it is a dead word. Elsewhere, with the modifier.
+ bool get _linkTapOpens =>
+ defaultTargetPlatform == TargetPlatform.iOS ||
+ defaultTargetPlatform == TargetPlatform.android ||
+ _linkModifierPressed;
+
bool _onLinkTapDown(TapDownDetails details, CellOffset cell) {
- _pressedLink = _linkModifierPressed
+ _pressedLink = _linkTapOpens
? _linkAtPointer(details.globalPosition)
: null;
return _pressedLink != null;
@@ -1267,7 +1371,7 @@ class _TerminalPanelState extends State<TerminalPanel>
// Read the current buffer again: streamed output may have replaced the
// text between press and release, or this pane may now show another agent.
if (target == null ||
- !_linkModifierPressed ||
+ !_linkTapOpens ||
target != _linkAtPointer(details.globalPosition)) {
return;
}
@@ -1467,7 +1571,9 @@ class _TerminalPanelState extends State<TerminalPanel>
// edge and the gap travelled with the content rather
// than staying put like a margin. The sides are
// margins beside chrome, not under it, and stay.
- padding: const EdgeInsets.symmetric(horizontal: 10),
+ padding: const EdgeInsets.symmetric(
+ horizontal: Tty.origin,
+ ),
textStyle: terminalFontStore.value,
// ⚠️ The terminal is NOT app chrome, and the user said so:
// it carries its own font settings (Settings ▸ Terminal,
@@ -1525,6 +1631,22 @@ class _TerminalPanelState extends State<TerminalPanel>
onCancelPreview: () => _previewCancellation?.cancel(),
),
),
+ // A long press selects on a phone, and nothing else offered to copy what it
+ // selected: `Copy` rides the selection, top right, until used or cleared.
+ // Under the phone's title (three rows, laid over the pane's top), not behind it.
+ Positioned(
+ top: 60,
+ right: 8,
+ child: ListenableBuilder(
+ listenable: _controller,
+ builder: (context, _) => _controller.selection == null
+ ? const SizedBox.shrink()
+ : _SelectionActions(
+ onCopy: () => unawaited(_copySelection()),
+ onClear: _controller.clearSelection,
+ ),
+ ),
+ ),
],
),
),
@@ -1708,3 +1830,51 @@ class _TransferOverlay extends StatelessWidget {
);
}
}
+
+/// `Copy ×` over a selection — the phone has no right click and no ⌘C.
+class _SelectionActions extends StatelessWidget {
+ const _SelectionActions({required this.onCopy, required this.onClear});
+
+ final VoidCallback onCopy;
+ final VoidCallback onClear;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ Widget action(String label, VoidCallback onTap, {bool bold = false}) =>
+ Semantics(
+ button: true,
+ label: label == '×' ? 'Clear selection' : label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minWidth: 44, minHeight: 40),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Center(
+ widthFactor: 1,
+ child: Text(
+ label,
+ style: tty.style(
+ size: 15,
+ weight: bold ? FontWeight.w700 : FontWeight.w400,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ return Material(
+ color: Color.alphaBlend(tty.text.withValues(alpha: 0.12), tty.ground),
+ elevation: 2,
+ borderRadius: BorderRadius.circular(6),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [action('Copy', onCopy, bold: true), action('×', onClear)],
+ ),
+ );
+ }
+}
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index b8aed2d11..488867a55 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -89,6 +89,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.9.0"
+ csslib:
+ dependency: transitive
+ description:
+ name: csslib
+ sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.2"
cupertino_icons:
dependency: "direct main"
description:
@@ -161,6 +169,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.1.2"
+ file:
+ dependency: transitive
+ description:
+ name: file
+ sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.1"
file_selector_linux:
dependency: transitive
description:
@@ -193,11 +209,24 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.9.3+6"
+ fixnum:
+ dependency: transitive
+ description:
+ name: fixnum
+ sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
+ flutter_driver:
+ dependency: "direct dev"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
flutter_lints:
dependency: "direct dev"
description:
@@ -280,6 +309,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.6.2+hotfix.1"
+ fuchsia_remote_debug_protocol:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
hooks:
dependency: transitive
description:
@@ -288,6 +322,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.2"
+ html:
+ dependency: transitive
+ description:
+ name: html
+ sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.15.7"
http:
dependency: transitive
description:
@@ -368,6 +410,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.2"
+ integration_test:
+ dependency: "direct dev"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
jni:
dependency: transitive
description:
@@ -480,6 +527,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.0"
+ mobile_scanner:
+ dependency: "direct main"
+ description:
+ name: mobile_scanner
+ sha256: "5a51ea79f0cf8293f616a5d08baae185b59b5e6bb24df01f2a63037ade0bade0"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.4.2"
objective_c:
dependency: transitive
description:
@@ -592,6 +647,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
+ process:
+ dependency: transitive
+ description:
+ name: process
+ sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891"
+ url: "https://pub.dev"
+ source: hosted
+ version: "5.0.6"
pub_semver:
dependency: transitive
description:
@@ -688,6 +751,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.6.1"
+ share_plus:
+ dependency: "direct main"
+ description:
+ name: share_plus
+ sha256: "34f00f9becd2743c1fb05363d624f9f70d37f7ccdcdda47450bc0b8c9d327b8c"
+ url: "https://pub.dev"
+ source: hosted
+ version: "13.3.0"
+ share_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: share_plus_platform_interface
+ sha256: "365ef7379fc22507256adda3385152942ffce08935452bc972c2e52a0bebae41"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.2.0"
sky_engine:
dependency: transitive
description: flutter
@@ -733,6 +812,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
+ sync_http:
+ dependency: transitive
+ description:
+ name: sync_http
+ sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.3.1"
synchronized:
dependency: transitive
description:
@@ -845,6 +932,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.6"
+ uuid:
+ dependency: transitive
+ description:
+ name: uuid
+ sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.6.0"
vector_math:
dependency: transitive
description:
@@ -853,6 +948,46 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.2"
+ video_player:
+ dependency: "direct main"
+ description:
+ name: video_player
+ sha256: "8c837b570dccb9ae6ff73d2e0b03c7e708bfefd3bd1194faa7f3e7f200dfc399"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.14.0"
+ video_player_android:
+ dependency: transitive
+ description:
+ name: video_player_android
+ sha256: d27054dea34d748a44f06d433a57005d2aac69944485b0abbaed3303dbcfa3f1
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.12.2"
+ video_player_avfoundation:
+ dependency: transitive
+ description:
+ name: video_player_avfoundation
+ sha256: "2fc56e537324a19eb649fca991aa308ac961b5406292876fa657b062de461fd8"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.12.0"
+ video_player_platform_interface:
+ dependency: transitive
+ description:
+ name: video_player_platform_interface
+ sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce"
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.9.0"
+ video_player_web:
+ dependency: transitive
+ description:
+ name: video_player_web
+ sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.0"
vm_service:
dependency: transitive
description:
@@ -861,6 +996,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "15.3.0"
+ wakelock_plus:
+ dependency: "direct dev"
+ description:
+ name: wakelock_plus
+ sha256: "22b3e7e937721de70e63c85e7139f4ac781dc22863b9262431a53ac030eb074b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.8.0"
+ wakelock_plus_platform_interface:
+ dependency: transitive
+ description:
+ name: wakelock_plus_platform_interface
+ sha256: "764c25504562abc8ac3406f5d175f126b276e6ba916c7c2675690b73368ca384"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.7.0"
web:
dependency: transitive
description:
@@ -885,6 +1036,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.3"
+ webdriver:
+ dependency: transitive
+ description:
+ name: webdriver
+ sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.2.0"
webrtc_interface:
dependency: transitive
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index f737c8a48..c402ccf0b 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -73,6 +73,16 @@ dependencies:
# (`lib/notify/system_notices.dart`). Local only — it fires from the machine socket,
# so it reaches a phone whose app is still alive, not one iOS has suspended.
flutter_local_notifications: ^22.2.0
+ # Connecting a computer: the first screen's "scan to connect" reads the code the desktop app
+ # shows (`phone/welcome/scan_to_connect.dart`). The camera only while that screen is up.
+ mobile_scanner: ^7.4.2
+ # "Send link to my Mac": the system share sheet, so AirDrop, Messages or email carry the
+ # download link to the computer (`phone/welcome/set_up_computer.dart`).
+ share_plus: ^13.3.0
+ # "See how it works": the 30-second recording of the app the set-up page plays
+ # (`phone/welcome/how_it_works_video.dart`, `assets/video/how_it_works.mp4`) — in place of an
+ # interactive demo.
+ video_player: ^2.14.0
dev_dependencies:
flutter_test:
@@ -81,6 +91,18 @@ dev_dependencies:
# The p2p routing is all timers (retry, migration sweep, upgrade) — tests drive
# them without waiting them out.
fake_async: ^1.3.1
+ # The on-device performance benchmark (`integration_test/perf_test.dart`,
+ # driven by `test_driver/perf_driver.dart`): production widgets in a profile
+ # build on a real phone, timed frame by frame. See `integration_test/README.md`.
+ integration_test:
+ sdk: flutter
+ flutter_driver:
+ sdk: flutter
+ # Keeps the phone from auto-locking during a benchmark run: synthetic touches
+ # do not reset iOS's idle timer, and a lock mid-run suspends the app and drops
+ # the driver's connection. A dev dependency — not in release builds — and
+ # called only by `integration_test/perf/scenarios.dart`.
+ wakelock_plus: ^1.8.0
flutter:
uses-material-design: true
@@ -93,3 +115,6 @@ flutter:
# NOT listed: Flutter cannot draw an SVG without a package this app does not
# depend on, so bundling it would only add its weight to every install.
- assets/app_icon.png
+ # "See how it works" — recorded from the sample on a simulator by
+ # `integration_test/demo_video_test.dart`, trimmed and encoded at 604px, ~630 KB.
+ - assets/video/how_it_works.mp4
diff --git a/mobile/scripts/perf_summarize.py b/mobile/scripts/perf_summarize.py
new file mode 100644
index 000000000..38fa7c157
--- /dev/null
+++ b/mobile/scripts/perf_summarize.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Pool the phone benchmark's runs in a data directory into markdown tables.
+
+ python3 mobile/scripts/perf_summarize.py docs/performance/2026-09-26-mobile-data
+
+Pools individual observations — every measured interaction, every frame of a
+window — across the runs in the directory, then takes nearest-rank
+percentiles, the rule `desktop/tool/native_benchmark/summarize_results.py`
+uses. Percentiles are never averaged. Warmups are excluded. Runs under
+`failed/` are not read; review them separately.
+
+`--label` restricts to files whose name starts with it (`baseline`, `after`).
+"""
+import argparse
+import json
+import math
+from collections import defaultdict
+from pathlib import Path
+
+
+def pct(values, q):
+ values = sorted(values)
+ return values[math.ceil(len(values) * q) - 1]
+
+
+def dist(values):
+ if not values:
+ return "—"
+ return " / ".join(f"{pct(values, q):.1f}" for q in (.5, .95, .99)) + f" / {max(values):.1f}"
+
+
+WINDOWS = [
+ ("idle", "Idle, nothing streaming"),
+ ("stream_redraw", "Reading: 8-row redraw @ 20 Hz"),
+ ("stream_append", "Reading: ~60 wrapped lines/s appended"),
+ ("scroll_read", "Scrolling back while redraw streams"),
+ ("control_panel_redraw", "Control: bare TerminalPanel, redraw"),
+]
+
+INTERACTIONS = [
+ ("find_open_tap", "idle", "Find: tap agent name"),
+ ("find_open_tap", "redraw", "Find: tap agent name, while streaming"),
+ ("find_open_swipe", "idle", "Find: swipe right (first = under finger, ready = release → settled)"),
+ ("find_switch", "idle", "Find: tap another agent → its terminal"),
+ ("mic_tap", "idle", "Mic: tap → listening face"),
+ ("mic_tap", "redraw", "Mic: tap → listening, while streaming"),
+ ("new_open_swipe", "idle", "New: swipe left → NewAgentPage"),
+]
+
+
+def load(root, label):
+ runs = []
+ for path in sorted(Path(root).glob("*.json")):
+ if label and not path.name.startswith(label):
+ continue
+ data = json.loads(path.read_text())
+ if data.get("kind") != "mobile_framework_dispatch_to_raster":
+ continue
+ if data.get("success") is not True:
+ raise SystemExit(f"{path.name} is a failed run; move it to failed/ and review it")
+ runs.append((path.name, data))
+ return runs
+
+
+def summarize(runs):
+ out = []
+ names = [name for name, _ in runs]
+ out.append(f"Runs pooled: {len(runs)} ({', '.join(names)})\n")
+
+ # Interactions: every measured observation, pooled.
+ rows = defaultdict(lambda: defaultdict(list))
+ for _, data in runs:
+ for obs in data.get("observations", []):
+ if obs["phase"] != "measured":
+ continue
+ key = (obs["operation"], obs["load"])
+ rows[key]["first"].append(obs["firstRasterMicros"] / 1000)
+ rows[key]["ready"].append(obs["readyRasterMicros"] / 1000)
+ rows[key]["build"].append(obs["buildMicros"] / 1000)
+ rows[key]["raster"].append(obs["rasterMicros"] / 1000)
+ rows[key]["wait"].append(obs["waitForBuildMicros"] / 1000)
+ out.append("### Interactions — framework dispatch → raster finish (ms, p50 / p95 / p99 / max)\n")
+ out.append("| Interaction | n | First frame with result | Ready (animation done) | First frame: build | First frame: raster | Wait for build |")
+ out.append("|---|---:|---:|---:|---:|---:|---:|")
+ for op, load_name, title in INTERACTIONS:
+ r = rows.get((op, load_name))
+ if not r:
+ continue
+ out.append(
+ f"| {title} | {len(r['first'])} | {dist(r['first'])} | {dist(r['ready'])} | "
+ f"{dist(r['build'])} | {dist(r['raster'])} | {dist(r['wait'])} |"
+ )
+ out.append("")
+
+ # Frame windows: every frame, pooled.
+ out.append("### Frames while reading and scrolling (ms, p50 / p95 / p99 / max)\n")
+ out.append("| Scenario | Frames | Frames/s | Build (UI) | Raster | Total span | Over 16.7 ms (total span) | Decoded kB/s | Session take per burst |")
+ out.append("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
+ for key, title in WINDOWS:
+ build, raster, total = [], [], []
+ seconds = 0.0
+ decoded = 0.0
+ takes = []
+ for _, data in runs:
+ scenario = data.get("scenarios", {}).get(key)
+ if not scenario:
+ continue
+ frames = scenario["frames"]
+ seconds += frames["windowMs"] / 1000
+ for row in frames.get("raw", []):
+ build.append(row[1] / 1000)
+ raster.append(row[2] / 1000)
+ total.append(row[4] / 1000)
+ output = scenario.get("output")
+ if output:
+ decoded += output["decodedBytesPerSecond"] * frames["windowMs"] / 1000
+ takes += [t / 1000 for t in output.get("sessionTakeRawUs", [])]
+ if not seconds:
+ continue
+ over = sum(1 for t in total if t > 16.667)
+ rate = f"{decoded / seconds / 1000:.1f}" if decoded else "—"
+ out.append(
+ f"| {title} | {len(total)} | {len(total) / seconds:.1f} | {dist(build)} | {dist(raster)} | "
+ f"{dist(total)} | {over} ({(over / len(total) * 100) if total else 0:.1f}%) | {rate} | {dist(takes)} |"
+ )
+ out.append("")
+
+ # Timeline rankings, per run (they are rankings, not timings).
+ for name, data in runs:
+ traces = data.get("traces") or {}
+ for key, trace in traces.items():
+ items = trace.get("bySelfTime")
+ if not items:
+ continue
+ out.append(f"#### Hottest by self time — {key} ({name})\n")
+ out.append("| Thread | Event | Count | Self ms | Inclusive ms | Max ms |")
+ out.append("|---|---|---:|---:|---:|---:|")
+ for item in items[:15]:
+ out.append(
+ f"| {item['thread']} | `{item['name']}` | {item['count']} | {item['selfMs']:.1f} | "
+ f"{item['inclusiveMs']:.1f} | {item['maxInclusiveMs']:.1f} |"
+ )
+ out.append("")
+ return "\n".join(out)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("directory", type=Path)
+ parser.add_argument("--label", default=None)
+ args = parser.parse_args()
+ print(summarize(load(args.directory, args.label)))
diff --git a/mobile/test/code_link_test.dart b/mobile/test/code_link_test.dart
new file mode 100644
index 000000000..18f3a03ed
--- /dev/null
+++ b/mobile/test/code_link_test.dart
@@ -0,0 +1,197 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/code_pake.dart';
+import 'package:harness_mobile/e2ee/cpace.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/e2ee/primitives.dart';
+import 'package:harness_mobile/viewer/code_link.dart';
+import 'package:harness_mobile/viewer/password_link.dart';
+
+String _hex(List<int> bytes) =>
+ bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
+
+/// The machine's side of the live-code pairing, as `manager.ts` `onPair` / `onPake` run it: round 1
+/// once the code is supplied, then check round 2, answer with round 3, pin on round 4.
+class _Machine {
+ _Machine(this.machineId, this.code, this.identity);
+
+ final String machineId;
+ final String code;
+ final E2eeIdentity identity;
+ final frames = StreamController<Map<String, dynamic>?>();
+ Uint8List? pinned;
+
+ late Uint8List _pairId;
+ late String _ci;
+ late BigInt _scalar;
+ late Uint8List _share;
+ Uint8List? _isk, _transcript;
+
+ void emit(String type, Map<String, Object> payload) =>
+ frames.add({'type': type, 'payload': payload});
+
+ Future<void> receive(String type, Map<String, Object> payload) async {
+ switch (type) {
+ case 'machine_select':
+ emit('connected', {'machineId': machineId});
+ case 'e2e_pair_intent':
+ emit('e2e_pair_intent_result', {
+ 'requestId': payload['requestId']!,
+ 'accepted': true,
+ 'ttl': 60,
+ });
+ // The desktop app supplies the code (`POST /api/pair`): round 1.
+ _pairId = b64d(payload['pairId']! as String);
+ _ci = pairContext(machineId, role: payload['role']! as String);
+ final start = cpaceStart(codeCpaceGenerator(code, _pairId, _ci));
+ _scalar = start.scalar;
+ _share = start.share;
+ emit('e2e_pake', {
+ 'pairId': payload['pairId']!,
+ 'round': 1,
+ 'ya': b64e(_share),
+ });
+ case 'e2e_pake' when payload['round'] == 2:
+ final yb = b64d(payload['yb']! as String);
+ final isk = _isk = cpaceIsk(
+ _pairId,
+ cpaceShared(yb, _scalar),
+ _share,
+ yb,
+ );
+ final th = _transcript = transcriptHash(_pairId, _ci, _share, yb);
+ if (!macVerify(
+ kcKeys(isk, _ci).web,
+ th,
+ b64d(payload['mac']! as String),
+ )) {
+ emit('e2e_pake', {
+ 'pairId': payload['pairId']!,
+ 'round': 5,
+ 'error': 'CODE_MISMATCH',
+ });
+ return;
+ }
+ final sealed = aeadSeal(
+ pairKey(isk, _ci),
+ 3,
+ utf8Bytes('e2e-id'),
+ utf8Bytes(
+ jsonEncode({
+ 'id': b64e(identity.pub),
+ 'sig': b64e(await pairBindSig(identity, th)),
+ }),
+ ),
+ );
+ emit('e2e_pake', {
+ 'pairId': payload['pairId']!,
+ 'round': 3,
+ 'mac': b64e(macTag(kcKeys(isk, _ci).adapter, th)),
+ 'enc': b64e(sealed),
+ });
+ case 'e2e_pake' when payload['round'] == 4:
+ final opened = aeadOpen(
+ pairKey(_isk!, _ci),
+ 4,
+ utf8Bytes('e2e-id'),
+ b64d(payload['enc']! as String),
+ )!;
+ final claim = jsonDecode(utf8.decode(opened)) as Map<String, dynamic>;
+ final pub = b64d(claim['id'] as String);
+ expect(
+ await pairBindVerify(pub, _transcript!, b64d(claim['sig'] as String)),
+ isTrue,
+ );
+ pinned = pub;
+ emit('e2e_pake', {
+ 'pairId': payload['pairId']!,
+ 'round': 5,
+ 'ok': true,
+ 'fingerprint': fingerprint(identity.pub),
+ });
+ }
+ }
+}
+
+void main() {
+ test("the generator is the CLI's, byte for byte", () {
+ // `cpaceGenerator('k7qm-4xpt 9d2w', 0..15, pairContext('machine-1','web'))` in
+ // cli/src/lib/e2ee/core.ts, run with tsx on 2026-09-27.
+ final sid = Uint8List.fromList(List.generate(16, (i) => i));
+ final ci = pairContext('machine-1');
+ expect(ci, 'autonomous-e2e-pair|agent:machine-1|a:adapter|b:web');
+ expect(
+ _hex(codeCpaceGenerator('k7qm-4xpt 9d2w', sid, ci).toBytes()),
+ '6841f15d7c5c5d50b2c82b68ebac097bd8b6e6effaa1038d5fdbc1b7e990ef59',
+ );
+ });
+
+ test("misread letters fold exactly as the CLI folds them", () {
+ // `normalizeCode('Lu-iO 7qm')` and its generator in cli/src/lib/e2ee/core.ts, via tsx.
+ expect(normalizePairCode('Lu-iO 7qm'), '1V107QM');
+ final sid = Uint8List.fromList(List.generate(16, (i) => i));
+ expect(
+ _hex(
+ codeCpaceGenerator(
+ 'Lu-iO 7qm',
+ sid,
+ pairContext('machine-1'),
+ ).toBytes(),
+ ),
+ '12801b078ff83c0896abfb75e1e9ebcd698796d62861e150c9ae7851235cb751',
+ );
+ });
+
+ Future<(PasswordLinkResult, _Machine, E2eeIdentity)> pair({
+ required String phoneCode,
+ required String machineCode,
+ }) async {
+ final machineId = 'machine-1';
+ final phone = await E2eeIdentity.generate();
+ final machine = _Machine(
+ machineId,
+ machineCode,
+ await E2eeIdentity.generate(),
+ );
+ final run = CodeLinkRun(
+ machineId: machineId,
+ code: phoneCode,
+ label: 'iPhone',
+ identity: phone,
+ send: (type, payload) => unawaited(machine.receive(type, payload)),
+ );
+ final result = await run
+ .drive(machine.frames.stream)
+ .timeout(const Duration(seconds: 10));
+ await machine.frames.close();
+ return (result, machine, phone);
+ }
+
+ test('the right code pins both sides, no password', () async {
+ final (result, machine, phone) = await pair(
+ phoneCode: 'K7QM4XPT9D2W',
+ machineCode: 'k7qm-4xpt-9d2w',
+ );
+ expect(result, isA<PasswordLinked>());
+ expect(
+ (result as PasswordLinked).peerPub,
+ machine.identity.pub,
+ reason: 'the phone pins the machine it paired with',
+ );
+ expect(machine.pinned, phone.pub, reason: 'and the machine pins the phone');
+ });
+
+ test('a wrong code pins nothing', () async {
+ final (result, machine, _) = await pair(
+ phoneCode: 'K7QM4XPT9D2W',
+ machineCode: 'AAAA4XPT9D2W',
+ );
+ expect(result, isA<PasswordLinkFailed>());
+ expect((result as PasswordLinkFailed).code, 'CODE_MISMATCH');
+ expect(machine.pinned, isNull);
+ });
+}
diff --git a/mobile/test/copy_mode_position_test.dart b/mobile/test/copy_mode_position_test.dart
new file mode 100644
index 000000000..615ab9447
--- /dev/null
+++ b/mobile/test/copy_mode_position_test.dart
@@ -0,0 +1,117 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:xterm/xterm.dart';
+
+import 'voice_fakes.dart';
+
+/// Reading back through the history while the agent keeps writing: output
+/// never moves the screen being read, tmux's copy-mode position says where the
+/// reader is, and one tap on it is back at the end.
+void main() {
+ late AppNotifier notifier;
+ late TerminalSession session;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+ late List<Map<String, dynamic>> resizes;
+
+ setUp(() {
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ resizes = [];
+ session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, payload) async {
+ if (type == 'terminal_resize') resizes.add(payload);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's';
+ for (var line = 0; line < 400; line++) {
+ session.terminal.write('output line $line\r\n');
+ }
+ notifier.adoptSessionForTest(session);
+ language = ValueNotifier('en');
+ voice = VoiceInputController(
+ transcriber: FakeTranscriber().call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ });
+
+ tearDown(() {
+ voice.dispose();
+ language.dispose();
+ // Disposes the session too: it was adopted as a pane.
+ notifier.dispose();
+ });
+
+ Future<void> pumpPage(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ /// A chunk of output, the way the session writes it.
+ void output(String text) {
+ session.outputTicks.value++;
+ session.terminal.write(text);
+ }
+
+ Finder position() => find.textContaining(RegExp(r'^\[\d+/\d+\]$'));
+
+ testWidgets('at the end there is no position', (tester) async {
+ await pumpPage(tester);
+ output('more output\r\n');
+ await tester.pump();
+ expect(position(), findsNothing);
+ });
+
+ testWidgets('scrolled up, the position shows and counts; a tap goes back', (
+ tester,
+ ) async {
+ await pumpPage(tester);
+ await tester.drag(find.byType(TerminalView), const Offset(0, 300));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(position(), findsOneWidget);
+ final before = (tester.widget(position()) as Text).data!;
+
+ output('newer output\r\n');
+ await tester.pump();
+ await tester.pump();
+ final after = (tester.widget(position()) as Text).data!;
+ expect(after, isNot(before), reason: 'new lines below count up');
+
+ await tester.tap(position());
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(position(), findsNothing);
+
+ // Following again: more output keeps it gone.
+ output('newest output\r\n');
+ await tester.pump();
+ await tester.pump();
+ expect(position(), findsNothing);
+ });
+}
diff --git a/mobile/test/desk_tab_add_test.dart b/mobile/test/desk_tab_add_test.dart
deleted file mode 100644
index 2b4a9746f..000000000
--- a/mobile/test/desk_tab_add_test.dart
+++ /dev/null
@@ -1,305 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/phone/agent_home.dart';
-import 'package:harness_mobile/phone/desk_add_agent_sheet.dart';
-import 'package:harness_mobile/phone/desk_groups.dart';
-import 'package:harness_mobile/phone/desk_tabs_panel.dart';
-import 'package:harness_mobile/phone/phone_shell_scope.dart';
-import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/state/desk_sync.dart';
-
-import 'agent_pager_fixture.dart';
-import 'desk_fixture.dart';
-
-/// The two `+`s on the tabs panel: one opens a tab, one fills the tab being
-/// read.
-///
-/// ⚠️ **They are the same glyph, so every test here asserts on what was WRITTEN
-/// to the desk rather than on what was tapped.** A `+` that made a tab where it
-/// should have added an agent would look identical on screen and be wrong on
-/// every computer the person owns.
-void main() {
- Future<AppNotifier> pumpHome(
- WidgetTester tester, {
- required List<DeskTab> tabs,
- }) async {
- final app = await deskApp(
- PagerConn(),
- // Nothing here is about the terminals themselves — see [deskApp].
- opensTerminals: false,
- tabs: tabs,
- );
- addTearDown(app.dispose);
- // ⚠️ A phone's shape, not the 800x600 a widget test defaults to. Both
- // sheets here keep half the screen for their list, and on a landscape
- // window the rows to tap sit below the bottom edge.
- tester.view.physicalSize = const Size(400, 1400);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- final request = ValueNotifier<({String machineId, String agentId})?>(null);
- addTearDown(request.dispose);
- await tester.pumpWidget(
- MaterialApp(
- home: PhoneShellScope(
- onMachineLinked: (_) {},
- onOpenAgent: (machineId, agentId) =>
- request.value = (machineId: machineId, agentId: agentId),
- child: AgentHome(notifier: app, openAgent: request),
- ),
- ),
- );
- await tester.pump();
- return app;
- }
-
- /// Open the tabs from the floating Search button — the one door to them
- /// since the header's grid mark went (see [TerminalSearchOverlay]).
- ///
- /// ⚠️ Timed pumps, never `pumpAndSettle`: these pages draw the "Attaching…"
- /// skeleton, which breathes for ever. The waits are the sheets' own
- /// animations.
- Future<void> openPanel(WidgetTester tester) async {
- await tester.tap(find.byKey(const ValueKey('terminal-search')));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- }
-
- Future<void> showTab(WidgetTester tester, String tab) async {
- await tester.tap(find.text(tab));
- await tester.pump();
- }
-
- /// The rename gesture. The pause between the two taps is inside Flutter's
- /// 300ms double-tap window, and the wait after it is the dialog's own
- /// transition.
- Future<void> doubleTap(WidgetTester tester, String tab) async {
- await tester.tap(find.text(tab));
- await tester.pump(const Duration(milliseconds: 50));
- await tester.tap(find.text(tab));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- }
-
- Future<void> settleSheet(WidgetTester tester) async {
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- }
-
- /// An agent's row, wherever it is drawn: a [DeskAgentRow] in the tabs, or
- /// its row in the sheet that adds one to a tab ([deskAddAgentRowKey]).
- Finder row(String agent) => find.byWidgetPredicate(
- (widget) =>
- (widget is DeskAgentRow && widget.entry.agent.id == agent) ||
- widget.key == deskAddAgentRowKey(agent),
- );
-
- testWidgets('the + on the tab row opens a tab holding the agent picked', (
- tester,
- ) async {
- final app = await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- ],
- );
-
- await openPanel(tester);
- await tester.tap(find.bySemanticsLabel('New tab'));
- await settleSheet(tester);
- // `c` is in no tab, so its row exists only in the sheet.
- await tester.tap(row('c'));
- await settleSheet(tester);
-
- final written = deskApiOf(app).written;
- expect(written, hasLength(2));
- expect(written.first['op'], 'tab.create');
- expect(
- written.first['name'],
- 'c',
- reason: 'a tab made for one agent is named after it',
- );
- expect(
- written.first['nameIsCustom'],
- false,
- reason: 'the name is the agent\'s, not one a person typed',
- );
- expect(written[1], {
- 'op': 'pane.add',
- 'tabId': written.first['id'],
- 'machineId': 'm',
- 'agentId': 'c',
- });
- expect(app.deskTabs.map((tab) => tab.name), [
- 'Desktop',
- 'c',
- ], reason: 'the new tab is last on the row');
- expect(
- app.activeDeskTabId,
- written.first['id'],
- reason: 'the person made it to be in it',
- );
- });
-
- testWidgets('the + under a tab adds the agent to THAT tab', (tester) async {
- final app = await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- deskTab('t2', 'Docker', ['b']),
- ],
- );
-
- await openPanel(tester);
- await showTab(tester, 'Docker');
- await tester.tap(find.bySemanticsLabel('Add harness to Docker'));
- await settleSheet(tester);
- await tester.tap(row('d'));
- await settleSheet(tester);
-
- expect(deskApiOf(app).written, [
- {'op': 'pane.add', 'tabId': 't2', 'machineId': 'm', 'agentId': 'd'},
- ]);
- expect(
- app.deskTabs
- .firstWhere((tab) => tab.id == 't2')
- .panes
- .map((pane) => pane.agentId),
- ['b', 'd'],
- );
- expect(
- row('d'),
- findsOneWidget,
- reason: 'the panel stays open, and the agent is in the list it filled',
- );
- });
-
- testWidgets('a tab is not offered the agents it already holds', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- ],
- );
-
- await openPanel(tester);
- await tester.tap(find.bySemanticsLabel('Add harness to Desktop'));
- await settleSheet(tester);
-
- // `a` and `b` are in the tab, and the panel under the sheet still draws
- // their rows — one each, from the list behind, and none from the sheet.
- expect(row('a'), findsOneWidget);
- expect(row('b'), findsOneWidget);
- expect(row('c'), findsOneWidget);
- expect(row('d'), findsOneWidget);
- });
-
- testWidgets('a tab emptied of agents says so, and can still be filled', (
- tester,
- ) async {
- await pumpHome(tester, tabs: [deskTab('t1', 'Empty', [])]);
-
- // Every agent is outside this tab, so the one on screen is in none — and
- // the panel falls back to the first tab, this one.
- //
- // ⚠️ Not tapped to: a tap on the tab already shown arms the rename
- // double-tap, whose timer outlives the test.
- await openPanel(tester);
-
- expect(find.text('This tab has no harnesses yet.'), findsOneWidget);
- expect(
- find.textContaining('asleep'),
- findsNothing,
- reason: 'a tab holding nothing is not a tab whose machine is away',
- );
- expect(find.bySemanticsLabel('Add harness to Empty'), findsOneWidget);
- });
-
- testWidgets('a name double-tapped is the tab renamed, and kept custom', (
- tester,
- ) async {
- final app = await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- deskTab('t2', 'Docker', ['b']),
- ],
- );
-
- await openPanel(tester);
- // ⚠️ Switched to first, THEN double-tapped: only the tab being shown takes
- // the gesture — see [DeskTabStrip.onRename].
- await showTab(tester, 'Docker');
- await doubleTap(tester, 'Docker');
-
- // The dialog's field: the sheet's own search field is under it.
- await tester.enterText(find.byType(TextField).last, 'Servers');
- await tester.tap(find.text('Save'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
-
- expect(deskApiOf(app).written, [
- {'op': 'tab.rename', 'id': 't2', 'name': 'Servers', 'nameIsCustom': true},
- ]);
- expect(
- app.deskTabs.firstWhere((tab) => tab.id == 't2').nameIsCustom,
- isTrue,
- reason: 'a name a person typed is not one a window may take back',
- );
- expect(find.text('Servers'), findsOneWidget);
- });
-
- testWidgets('a blank name leaves the tab as it was', (tester) async {
- final app = await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- ],
- );
-
- await openPanel(tester);
- await doubleTap(tester, 'Desktop');
-
- // The dialog's field: the sheet's own search field is under it.
- await tester.enterText(find.byType(TextField).last, ' ');
- await tester.tap(find.text('Save'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
-
- expect(deskApiOf(app).written, isEmpty);
- expect(find.text('Desktop'), findsOneWidget);
- });
-
- // ⚠️ The agents no tab holds are no group any more (see [deskGroups]); the
- // one group that is not a tab is the single one of an account with no tabs.
- testWidgets('the one group of an account with no tabs cannot be renamed', (
- tester,
- ) async {
- final app = await pumpHome(tester, tabs: []);
-
- await openPanel(tester);
- await doubleTap(tester, kEveryAgentGroupName);
-
- // Not a tab on the desk — there is no name to write.
- expect(find.text('Save'), findsNothing);
- expect(deskApiOf(app).written, isEmpty);
- });
-
- testWidgets('an account with no tabs is offered a new harness, not a + '
- 'into a tab', (tester) async {
- await pumpHome(tester, tabs: []);
-
- await openPanel(tester);
-
- // Not a tab — there is nothing on the desk to add an agent to...
- expect(find.textContaining('Add harness to'), findsNothing);
- // ...but a harness can still be started from it.
- expect(find.bySemanticsLabel('New harness, in no tab'), findsOneWidget);
- expect(
- find.bySemanticsLabel('New tab'),
- findsOneWidget,
- reason: 'the tab row keeps its own +, so the first tab can be made',
- );
- });
-}
diff --git a/mobile/test/find_models_test.dart b/mobile/test/find_models_test.dart
new file mode 100644
index 000000000..d1138fccb
--- /dev/null
+++ b/mobile/test/find_models_test.dart
@@ -0,0 +1,161 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/find_models.dart';
+import 'package:harness_mobile/phone/find_row.dart';
+import 'package:harness_mobile/phone/terminal_search.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+/// A machine that serves two local models and records what it is asked.
+class _Conn extends WsConn {
+ _Conn(this.asked)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final List<(String, Map<String, dynamic>)> asked;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ asked.add((type, payload));
+ if (type == 'grid_models_list') {
+ return {
+ 'gridName': 'mine',
+ 'models': const [],
+ 'grids': [
+ {
+ 'name': 'mine',
+ 'own': true,
+ 'models': [
+ {'id': 'qwen3-coder-30b', 'node': 'studio'},
+ {'id': 'gpt-oss-20b', 'node': 'studio'},
+ ],
+ },
+ ],
+ };
+ }
+ return {};
+ }
+}
+
+/// Find's `:` — the desktop ⌘P's models mode, for the agent on screen.
+void main() {
+ /// Unmounts and lets the machine's timers run out — the search asks every machine for its
+ /// agents as it opens, and those requests carry timeouts.
+ Future<void> settle(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ }
+
+ Future<List<(String, Map<String, dynamic>)>> pumpFind(
+ WidgetTester tester, {
+ String engine = 'claude',
+ }) async {
+ final asked = <(String, Map<String, dynamic>)>[];
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _Conn(asked),
+ );
+ addTearDown(app.dispose);
+ const machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'M2',
+ );
+ app.machines = [machine];
+ app.machineStates['m'] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [
+ Agent(id: 'a', name: 'hn', engine: engine, terminalAvailable: true),
+ ];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: TerminalSearchOverlay(
+ notifier: app,
+ animation: const AlwaysStoppedAnimation(1),
+ showing: (machineId: 'm', agentId: 'a'),
+ onClose: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.enterText(find.byType(TextField), ':');
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ return asked;
+ }
+
+ testWidgets(': lists the subscription and the machine\'s models', (
+ tester,
+ ) async {
+ await pumpFind(tester);
+ expect(find.byType(FindModels), findsOneWidget);
+ // Each model is a Find row of its own — the same rows as every other mode of Find.
+ expect(find.byType(FindRow), findsWidgets);
+ expect(
+ find.textContaining('qwen3-coder-30b', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('gpt-oss-20b', findRichText: true),
+ findsOneWidget,
+ );
+ await settle(tester);
+ });
+
+ testWidgets('typing after : narrows the models', (tester) async {
+ await pumpFind(tester);
+ await tester.enterText(find.byType(TextField), ':qwen');
+ await tester.pump();
+ expect(
+ find.textContaining('qwen3-coder-30b', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('gpt-oss-20b', findRichText: true),
+ findsNothing,
+ );
+ await settle(tester);
+ });
+
+ testWidgets('a tap moves the agent onto the model', (tester) async {
+ final asked = await pumpFind(tester);
+ await tester.tap(
+ find.textContaining('qwen3-coder-30b', findRichText: true),
+ );
+ await tester.pump();
+ final retarget = asked.where((call) => call.$1 == 'agent_retarget');
+ expect(retarget, hasLength(1));
+ expect(retarget.single.$2['gridModel'], 'qwen3-coder-30b');
+ await settle(tester);
+ });
+
+ testWidgets('an engine that cannot switch is told so in one line', (
+ tester,
+ ) async {
+ await pumpFind(tester, engine: 'cursor');
+ expect(
+ find.textContaining('keeps its own model', findRichText: true),
+ findsOneWidget,
+ );
+ await settle(tester);
+ });
+}
diff --git a/mobile/test/first_computer_flow_test.dart b/mobile/test/first_computer_flow_test.dart
new file mode 100644
index 000000000..0a3178b73
--- /dev/null
+++ b/mobile/test/first_computer_flow_test.dart
@@ -0,0 +1,101 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+class _Conn extends WsConn {
+ _Conn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'studio',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => {};
+}
+
+/// A new account's first minutes on the phone, signed in: no computer yet → how to set one up;
+/// the computer appears, locked → its unlock, right there; unlocked with nothing running → New.
+void main() {
+ testWidgets('no computer, then a locked one, then an empty one', (
+ tester,
+ ) async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _Conn(),
+ );
+ addTearDown(app.dispose);
+ final request = ValueNotifier<({String machineId, String agentId})?>(null);
+ addTearDown(request.dispose);
+ final linked = ValueNotifier<String?>(null);
+ addTearDown(linked.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: PhoneShellScope(
+ // What the shell does on a link: tell home which machine was just unlocked.
+ onMachineLinked: (machineId) => linked.value = machineId,
+ onOpenAgent: (_, _) {},
+ child: AgentHome(
+ notifier: app,
+ openAgent: request,
+ openMachineId: linked,
+ ),
+ ),
+ ),
+ );
+ Future<void> settle() async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ await settle();
+ expect(find.text('Set up your computer'), findsOneWidget);
+
+ // It appears — awake, and waiting for its phone password.
+ const studio = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'studio',
+ );
+ app.machines = [studio];
+ app.machineStates['studio'] = MachineState(studio)
+ ..nodeOnline = true
+ ..needsLink = true
+ ..agentLoadStatus = AgentLoadStatus.needsLink;
+ app.notifyListeners();
+ await settle();
+ expect(find.text('Unlock studio'), findsOneWidget);
+
+ // Unlocked (what a right password does), with nothing running: New, to start the first one.
+ linked.value = 'studio';
+ app.machineStates['studio']!
+ ..needsLink = false
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [];
+ app.notifyListeners();
+ await settle();
+ await tester.pump(const Duration(seconds: 1));
+ expect(find.text('New Harness'), findsWidgets);
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 6));
+ });
+}
diff --git a/mobile/test/focus_swipes_test.dart b/mobile/test/focus_swipes_test.dart
new file mode 100644
index 000000000..1548a9a0c
--- /dev/null
+++ b/mobile/test/focus_swipes_test.dart
@@ -0,0 +1,159 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/terminal_search.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:xterm/xterm.dart';
+
+import 'voice_fakes.dart';
+
+/// Focus is Snapchat's camera: a swipe right on the terminal pulls Find in from
+/// the left edge, a tap on the agent's name opens it too, and a swipe left
+/// opens a new agent.
+void main() {
+ late AppNotifier notifier;
+ late TerminalSession session;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+ late List<Map<String, dynamic>> resizes;
+
+ setUp(() {
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ resizes = [];
+ session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, payload) async {
+ if (type == 'terminal_resize') resizes.add(payload);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's';
+ for (var line = 0; line < 400; line++) {
+ session.terminal.write('output line $line\r\n');
+ }
+ notifier.adoptSessionForTest(session);
+ language = ValueNotifier('en');
+ voice = VoiceInputController(
+ transcriber: FakeTranscriber().call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ });
+
+ tearDown(() {
+ voice.dispose();
+ language.dispose();
+ // Disposes the session too: it was adopted as a pane.
+ notifier.dispose();
+ });
+
+ Future<List<Route<dynamic>>> pumpFocus(WidgetTester tester) async {
+ final pushed = <Route<dynamic>>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ navigatorObservers: [_Pushes(pushed)],
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ pushed.clear();
+ return pushed;
+ }
+
+ testWidgets('a swipe right on the terminal pulls Find in', (tester) async {
+ await pumpFocus(tester);
+ expect(find.byType(TerminalSearchOverlay), findsNothing);
+
+ await tester.drag(find.byType(TerminalView), const Offset(400, 0));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ });
+
+ testWidgets('a short swipe right lets Find go back', (tester) async {
+ await pumpFocus(tester);
+
+ await tester.timedDrag(
+ find.byType(TerminalView),
+ const Offset(40, 0),
+ const Duration(milliseconds: 800),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ expect(find.byType(TerminalSearchOverlay), findsNothing);
+ });
+
+ testWidgets('a tap on the agent\'s name opens Find', (tester) async {
+ await pumpFocus(tester);
+
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ });
+
+ testWidgets('a swipe left on Find sends it back', (tester) async {
+ await pumpFocus(tester);
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ await tester.fling(
+ find.byType(TerminalSearchOverlay),
+ const Offset(-300, 0),
+ 1500,
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+
+ expect(find.byType(TerminalSearchOverlay), findsNothing);
+ });
+
+ testWidgets('a swipe left on the terminal opens a new agent', (tester) async {
+ final pushed = await pumpFocus(tester);
+
+ await tester.drag(find.byType(TerminalView), const Offset(-200, 0));
+
+ // Pushed, and not pumped further: the new-agent form asks its machine for
+ // folders and engines as it opens, and this fixture has no machine to ask.
+ expect(pushed, hasLength(1));
+ expect(find.byType(TerminalSearchOverlay), findsNothing);
+ });
+}
+
+class _Pushes extends NavigatorObserver {
+ _Pushes(this.pushed);
+
+ final List<Route<dynamic>> pushed;
+
+ @override
+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) =>
+ pushed.add(route);
+}
diff --git a/mobile/test/kept_screen_test.dart b/mobile/test/kept_screen_test.dart
new file mode 100644
index 000000000..105314e62
--- /dev/null
+++ b/mobile/test/kept_screen_test.dart
@@ -0,0 +1,96 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:xterm/xterm.dart';
+
+/// Back to an agent read a moment ago: its last screen shows at once, and the
+/// live stream's first keyframe replaces it.
+void main() {
+ const streamId = '00112233-4455-6677-8899-aabbccddeeff';
+
+ TerminalSession newSession(List<Map<String, dynamic>> sent) =>
+ TerminalSession(
+ machineId: 'machine-1',
+ agentId: 'agent-1',
+ agentName: 'backend-api',
+ engineId: 'claude',
+ send: (type, payload) async {
+ sent.add(Map<String, dynamic>.from(payload));
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+
+ String screenText(Terminal terminal) =>
+ terminal.buffer.lines.toList().map((line) => line.toString()).join('\n');
+
+ test('a kept screen stands in until the keyframe replaces it', () async {
+ final sent = <Map<String, dynamic>>[];
+ final session = newSession(sent);
+ addTearDown(session.dispose);
+ final kept = Terminal(maxLines: 100)
+ ..write('what the agent said last time');
+
+ expect(session.hasScreen, isFalse);
+ session.seedScreen(kept);
+ expect(session.hasScreen, isTrue);
+ expect(session.showingKeptScreen, isTrue);
+ expect(session.hasRenderedFrame, isFalse);
+ expect(identical(session.terminal, kept), isTrue);
+
+ await session.open(initialCols: 100, initialRows: 30);
+ await session.handleFrame('terminal_ready', {
+ 'requestId': sent.single['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': streamId,
+ 'agentId': 'agent-1',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 0,
+ bytes: Uint8List.fromList(utf8.encode('live now')),
+ compressed: false,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+
+ expect(session.showingKeptScreen, isFalse);
+ expect(session.hasRenderedFrame, isTrue);
+ expect(identical(session.terminal, kept), isFalse);
+ expect(screenText(session.terminal), contains('live now'));
+ });
+
+ test('a session already showing its stream keeps it', () async {
+ final sent = <Map<String, dynamic>>[];
+ final session = newSession(sent);
+ addTearDown(session.dispose);
+ await session.open(initialCols: 100, initialRows: 30);
+ await session.handleFrame('terminal_ready', {
+ 'requestId': sent.single['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': streamId,
+ 'agentId': 'agent-1',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 0,
+ bytes: Uint8List.fromList(utf8.encode('live')),
+ compressed: false,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ final live = session.terminal;
+ session.seedScreen(Terminal(maxLines: 100)..write('stale'));
+ expect(identical(session.terminal, live), isTrue);
+ expect(session.showingKeptScreen, isFalse);
+ });
+}
diff --git a/mobile/test/key_hints_claude_test.dart b/mobile/test/key_hints_claude_test.dart
new file mode 100644
index 000000000..f49d16381
--- /dev/null
+++ b/mobile/test/key_hints_claude_test.dart
@@ -0,0 +1,23 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/key_hints.dart';
+
+void main() {
+ test(
+ "Claude Code's shift+tab to cycle becomes a key; its other chrome does not",
+ () {
+ final hints = parseKeyHints([
+ '╭──────────────────────────────────────────╮',
+ '│ > │',
+ '╰──────────────────────────────────────────╯',
+ ' ⏵⏵ accept edits on (shift+tab to cycle)',
+ ]);
+ expect(hints, hasLength(1));
+ expect(hints.single.action, 'cycle');
+ expect(hints.single.keyText, 'shift+tab');
+ },
+ );
+
+ test('esc to interrupt is not a hint: the phone already has esc', () {
+ expect(parseKeyHints(['✻ Thinking… (3s · esc to interrupt)']), isEmpty);
+ });
+}
diff --git a/mobile/test/last_opened_agent_test.dart b/mobile/test/last_opened_agent_test.dart
index 9d9cfb1b8..a4f9e2409 100644
--- a/mobile/test/last_opened_agent_test.dart
+++ b/mobile/test/last_opened_agent_test.dart
@@ -15,9 +15,10 @@ void main() {
LastOpenedAgent launch() => LastOpenedAgent(HarnessFileStore(directory: dir));
/// [LastOpenedAgent.remember] does not wait for its write; a relaunch comes
- /// long after it has landed.
+ /// long after it has landed. A second, not 200ms: under a full parallel run the
+ /// write queued behind other tests' disk work and a shorter wait read it early.
Future<void> settle() =>
- Future<void>.delayed(const Duration(milliseconds: 200));
+ Future<void>.delayed(const Duration(seconds: 1));
test('the last agent remembered is the one the next launch reads', () async {
final first = launch();
diff --git a/mobile/test/machines_load_failure_test.dart b/mobile/test/machines_load_failure_test.dart
index 8aa0d1d29..9a7d403d5 100644
--- a/mobile/test/machines_load_failure_test.dart
+++ b/mobile/test/machines_load_failure_test.dart
@@ -34,8 +34,8 @@ void main() {
// Not "No machines yet": that tells somebody with three machines to go and
// set one up.
- expect(find.text('No machines yet'), findsNothing);
- expect(find.text("Couldn't load your machines"), findsOneWidget);
+ expect(find.text('No computers yet'), findsNothing);
+ expect(find.text("Couldn't reach your computers"), findsOneWidget);
await tester.tap(find.text('Try again'));
await tester.pump();
diff --git a/mobile/test/notify/desk_tab_unread_test.dart b/mobile/test/notify/desk_tab_unread_test.dart
deleted file mode 100644
index f42b0a108..000000000
--- a/mobile/test/notify/desk_tab_unread_test.dart
+++ /dev/null
@@ -1,68 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-
-import 'package:harness_mobile/notify/agent_notice.dart';
-import 'package:harness_mobile/notify/agent_unread.dart';
-import 'package:harness_mobile/notify/unread_marks.dart';
-import 'package:harness_mobile/phone/desk_groups.dart';
-import 'package:harness_mobile/phone/desk_tab_strip.dart';
-
-/// A tab says what its agents are carrying, so the person can tell WHICH tab
-/// an agent finished in without opening every one of them.
-void main() {
- const a = (machineId: 'm', agentId: 'a');
- const b = (machineId: 'm', agentId: 'b');
- const c = (machineId: 'm', agentId: 'c');
-
- group('mostUrgentOf', () {
- test('a question outranks a finished turn, wherever it sits', () {
- final unread = AgentUnread()
- ..mark(a, NoticeKind.done)
- ..mark(b, NoticeKind.question);
- addTearDown(unread.dispose);
- expect(unread.mostUrgentOf([a, b]), NoticeKind.question);
- expect(unread.mostUrgentOf([a, c]), NoticeKind.done);
- expect(unread.mostUrgentOf([c]), isNull);
- expect(unread.mostUrgentOf(const []), isNull);
- });
- });
-
- testWidgets('each pill carries its own tab\'s mark, in its kind\'s colour', (
- tester,
- ) async {
- const kinds = {'desk': NoticeKind.done, 'docker': NoticeKind.question};
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: DeskTabStrip(
- groups: const [
- DeskGroup(id: 'desk', name: 'Desktop', entries: []),
- DeskGroup(id: 'docker', name: 'Docker', entries: []),
- DeskGroup(id: 'other', name: 'Other', entries: []),
- ],
- selectedId: 'desk',
- onPick: (_) {},
- unreadFor: (tab) => kinds[tab.id],
- ),
- ),
- ),
- );
-
- UnreadDot? dotIn(String name) {
- final dot = find.descendant(
- // The pill's own row — the nearest one — not the strip's around it.
- of: find
- .ancestor(of: find.text(name), matching: find.byType(Row))
- .first,
- matching: find.byType(UnreadDot),
- );
- return dot.evaluate().isEmpty
- ? null
- : tester.widget<UnreadDot>(dot.first);
- }
-
- expect(dotIn('Desktop')?.kind, NoticeKind.done);
- expect(dotIn('Docker')?.kind, NoticeKind.question);
- expect(dotIn('Other'), isNull);
- });
-}
diff --git a/mobile/test/notify/phone_on_screen_test.dart b/mobile/test/notify/phone_on_screen_test.dart
index 461403a66..e77c4ba6d 100644
--- a/mobile/test/notify/phone_on_screen_test.dart
+++ b/mobile/test/notify/phone_on_screen_test.dart
@@ -40,6 +40,9 @@ void main() {
),
);
await tester.pump();
+ // A new phone opens on its sessions to pick from (`PickUpPage`): `a` is picked there.
+ request.value = (machineId: 'm', agentId: 'a');
+ await tester.pump();
return app;
}
diff --git a/mobile/test/pairing_with_code_test.dart b/mobile/test/pairing_with_code_test.dart
new file mode 100644
index 000000000..00df70391
--- /dev/null
+++ b/mobile/test/pairing_with_code_test.dart
@@ -0,0 +1,129 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/auth/cli_link.dart';
+import 'package:harness_mobile/auth/peer_link_client.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/welcome/pairing_with_code.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+/// A link client that pairs by code: [result] is what the machine answered.
+class _Links implements PeerLinkClient {
+ _Links(this.result);
+
+ final CliLinkConnectResult result;
+ final codes = <(String, String, String)>[];
+
+ /// Held until the test lets the machine answer.
+ final gate = Completer<void>();
+
+ @override
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ }) async {
+ codes.add((machineId, code, label));
+ await gate.future;
+ return result;
+ }
+
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async => const CliLinkConnectResult(error: 'not used');
+
+ @override
+ Future<CliLinkListResult> list() async =>
+ const CliLinkListResult(machines: []);
+
+ @override
+ Future<String?> unlink(String machineId) async => null;
+}
+
+/// Signed in from a scanned "Add phone" QR: the computer it named shows up locked, and the phone
+/// pairs with the QR's code instead of asking for its password.
+void main() {
+ Future<AppNotifier> pumpHome(WidgetTester tester, _Links links) async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ peerLinks: links,
+ );
+ addTearDown(app.dispose);
+ const mac = Machine(
+ machineId: 'mac',
+ authMode: MachineAuthMode.remote,
+ name: 'MacBook Pro',
+ );
+ app.machines = [mac];
+ app.machineStates['mac'] = MachineState(mac)
+ ..nodeOnline = true
+ ..needsLink = true
+ ..connectionStatus = ConnectionStatus.disconnected;
+ app.pendingPairing = (machineId: 'mac', code: 'K7QM4XPT9D2W');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (_, _) {},
+ child: AgentHome(notifier: app),
+ ),
+ ),
+ );
+ await tester.pump();
+ return app;
+ }
+
+ testWidgets('pairs by the code, no password, and the computer unlocks', (
+ tester,
+ ) async {
+ final links = _Links(const CliLinkConnectResult(linkedMachineId: 'mac'));
+ final app = await pumpHome(tester, links);
+
+ expect(find.byType(PairingWithCode), findsOneWidget);
+ expect(find.textContaining('MacBook Pro'), findsOneWidget);
+ links.gate.complete();
+ await tester.pump();
+ expect(links.codes.single.$1, 'mac');
+ expect(links.codes.single.$2, 'K7QM4XPT9D2W');
+ expect(app.pendingPairing, isNull);
+ expect(app.machineStates['mac']!.needsLink, isFalse);
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 40));
+ });
+
+ testWidgets('a code that fails says why, and the password is the way on', (
+ tester,
+ ) async {
+ final links = _Links(
+ const CliLinkConnectResult(
+ error: 'That code didn’t match. Scan the new one on MacBook Pro.',
+ ),
+ );
+ final app = await pumpHome(tester, links);
+ links.gate.complete();
+ await tester.pump();
+ await tester.pump();
+
+ expect(find.textContaining('didn’t match'), findsOneWidget);
+ await tester.tap(find.text('Use its password instead'));
+ await tester.pump();
+ expect(app.pendingPairing, isNull);
+ expect(find.byType(PairingWithCode), findsNothing);
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 40));
+ });
+}
diff --git a/mobile/test/perf_fixture_test.dart b/mobile/test/perf_fixture_test.dart
new file mode 100644
index 000000000..b46026363
--- /dev/null
+++ b/mobile/test/perf_fixture_test.dart
@@ -0,0 +1,131 @@
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/find_row.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/terminal_search.dart';
+
+import '../integration_test/perf/claude_output.dart';
+import '../integration_test/perf/fixture.dart';
+
+/// The on-device benchmark's fixture (`integration_test/perf/`), checked on
+/// every `flutter test` so it cannot drift from the app it measures — and the
+/// one property of the idle screen that benchmark depends on.
+void main() {
+ /// iPhone 14: 390×844 points at 3×, with its safe-area insets.
+ void phone(WidgetTester tester) {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ tester.view.padding = const FakeViewPadding(top: 141, bottom: 102);
+ addTearDown(tester.view.reset);
+ }
+
+ testWidgets('an idle terminal page draws nothing', (tester) async {
+ phone(tester);
+ final fixture = PerfFixture.create();
+ final a = fixture.terminals['agent-a']!;
+ await tester.pumpWidget(
+ perfApp(FocusHost(fixture: fixture, initialAgentId: 'agent-a')),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ // The attach as the benchmark does it: the machine's size, the phone's
+ // resize, and a keyframe back at the phone's grid.
+ await a.keyframe(ClaudeOutput(cols: 80).keyframe(20), cols: 80, rows: 24);
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 100));
+ final (cols, rows) = a.lastResize!;
+ await a.keyframe(
+ ClaudeOutput(cols: cols).keyframe(2000),
+ cols: cols,
+ rows: rows,
+ );
+ await tester.pump(const Duration(milliseconds: 500));
+
+ // Nothing streaming, keyboard down, mic at rest: every repeating
+ // animation on the page (skeleton, header glint, mic arc/dots/bob, take
+ // meter, cursor blink) is gated off, so no frame is asked for.
+ for (var i = 0; i < 50; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(
+ tester.binding.hasScheduledFrame,
+ isFalse,
+ reason: 'a frame was scheduled ${(i + 1) * 100} ms into idle',
+ );
+ }
+ expect(tester.binding.transientCallbackCount, 0);
+ expect(a.resizes, 1, reason: 'one resize, for the grid, then none');
+
+ await tester.pumpWidget(const SizedBox.shrink());
+ fixture.dispose();
+ });
+
+ testWidgets(
+ 'the redraw load holds the screen still; the append load grows it',
+ (tester) async {
+ final fixture = PerfFixture.create();
+ final a = fixture.terminals['agent-a']!;
+ final output = ClaudeOutput(cols: 40);
+ await a.keyframe(output.keyframe(200), cols: 40, rows: 49);
+ final buffer = a.session.terminal.buffer;
+ final lines = buffer.lines.length;
+ final cursor = buffer.cursorY;
+ for (var tick = 1; tick <= 50; tick++) {
+ await a.output(FixtureTerminal.encode(output.redrawBurst(tick)));
+ }
+ // Ink's in-place redraw: an 8-row region rewritten, nothing added.
+ expect(buffer.lines.length, lines);
+ expect(buffer.cursorY, cursor);
+ for (var tick = 1; tick <= 20; tick++) {
+ await a.output(FixtureTerminal.encode(output.appendBurst(tick)));
+ }
+ // Three long lines a burst, each wrapping several times at 40 columns.
+ expect(buffer.lines.length, greaterThan(lines + 20 * 3 * 3));
+ fixture.dispose();
+ },
+ );
+
+ testWidgets('Find lists the other agent, and opening it switches the page', (
+ tester,
+ ) async {
+ phone(tester);
+ final fixture = PerfFixture.create();
+ final host = GlobalKey<FocusHostState>();
+ await tester.pumpWidget(
+ perfApp(
+ FocusHost(key: host, fixture: fixture, initialAgentId: 'agent-a'),
+ ),
+ );
+ for (final id in ['agent-a', 'agent-b']) {
+ await fixture.terminals[id]!.keyframe(
+ ClaudeOutput(cols: 40).keyframe(100),
+ cols: 40,
+ rows: 49,
+ );
+ }
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+
+ final row = find.byWidgetPredicate(
+ (w) => w is FindRow && w.title == 'tighten rate limiter',
+ );
+ expect(row, findsOneWidget);
+ await tester.tap(row);
+ await tester.pump();
+ expect(host.currentState!.agentId, 'agent-b');
+ expect(
+ find.byWidgetPredicate(
+ (w) => w is TerminalPage && w.agentId == 'agent-b',
+ ),
+ findsOneWidget,
+ );
+
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox.shrink());
+ fixture.dispose();
+ });
+}
diff --git a/mobile/test/phone_desk_tabs_test.dart b/mobile/test/phone_desk_tabs_test.dart
deleted file mode 100644
index d3e300482..000000000
--- a/mobile/test/phone_desk_tabs_test.dart
+++ /dev/null
@@ -1,365 +0,0 @@
-import 'dart:convert';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/phone/agent_home.dart';
-import 'package:harness_mobile/phone/agent_swipe.dart';
-import 'package:harness_mobile/phone/desk_groups.dart';
-import 'package:harness_mobile/phone/desk_tab_strip.dart';
-import 'package:harness_mobile/phone/desk_tabs_panel.dart';
-import 'package:harness_mobile/phone/phone_shell_scope.dart';
-import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/state/desk_sync.dart';
-
-import 'agent_pager_fixture.dart';
-import 'desk_fixture.dart';
-import 'voice_fakes.dart';
-
-/// The home screen inside its tab: a swipe walks the tab the phone is in, and
-/// the floating Search button opens the panel that reaches the others.
-///
-/// ⚠️ **The pager's `neighbours` is the assertion throughout, because it IS the
-/// swipe.** [AgentSwipeHost] pages through exactly that list and nothing else,
-/// so a list holding one tab's agents is a swipe that stays inside that tab —
-/// which is the whole change, and it can be read without flinging anything.
-void main() {
- /// The home screen as the shell mounts it: an agent picked anywhere else —
- /// the tabs panel included — arrives through [AgentHome.openAgent], and the
- /// shell is what carries it there.
- Future<AppNotifier> pumpHome(
- WidgetTester tester, {
- required List<DeskTab> tabs,
- MemoryKeyValueStore? storage,
- }) async {
- final app = await deskApp(
- PagerConn(),
- // Nothing here is about the terminals themselves — see [deskApp].
- opensTerminals: false,
- tabs: tabs,
- storage: storage,
- );
- addTearDown(app.dispose);
- final request = ValueNotifier<({String machineId, String agentId})?>(null);
- addTearDown(request.dispose);
- await tester.pumpWidget(
- MaterialApp(
- home: PhoneShellScope(
- onMachineLinked: (_) {},
- onOpenAgent: (machineId, agentId) =>
- request.value = (machineId: machineId, agentId: agentId),
- child: AgentHome(notifier: app, openAgent: request),
- ),
- ),
- );
- await tester.pump();
- return app;
- }
-
- AgentSwipeHost pager(WidgetTester tester) =>
- tester.widget<AgentSwipeHost>(find.byType(AgentSwipeHost));
-
- /// Open the tabs panel from the floating Search button — the one door to it
- /// since the header's grid mark went (see [TerminalSearchOverlay]).
- ///
- /// ⚠️ **Timed pumps, never `pumpAndSettle`.** These pages have no terminal
- /// behind them (see [deskApp]), so each one draws the "Attaching…" skeleton —
- /// which breathes for ever, and `pumpAndSettle` waits for a still frame that
- /// never comes. The waits below are the panel's own open and dismiss
- /// animations.
- Future<void> openPanel(WidgetTester tester) async {
- await tester.tap(find.byKey(const ValueKey('terminal-search')));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- }
-
- /// Tap a tab's name in the open panel, which changes the cards under it and
- /// nothing else.
- Future<void> showTab(WidgetTester tester, String tab) async {
- await tester.tap(find.text(tab));
- await tester.pump();
- }
-
- /// An agent's row in the open panel.
- Finder row(String agent) => find.byWidgetPredicate(
- (widget) => widget is DeskAgentRow && widget.entry.agent.id == agent,
- );
-
- /// Tap an agent's row, which opens it and takes the panel away.
- Future<void> openRow(WidgetTester tester, String agent) async {
- await tester.tap(row(agent));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- }
-
- DeskTabStrip strip(WidgetTester tester) =>
- tester.widget<DeskTabStrip>(find.byType(DeskTabStrip));
-
- /// The agents the panel is offering, in the order it lists them.
- List<String> agentsShown(WidgetTester tester) => [
- for (final row in tester.widgetList<DeskAgentRow>(
- find.byType(DeskAgentRow),
- ))
- row.entry.agent.id,
- ];
-
- List<String> swipesOver(WidgetTester tester) => [
- for (final entry in pager(tester).neighbours!.entries) entry.agent.id,
- ];
-
- testWidgets('a swipe walks the tab the agent on screen is in', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c']),
- ],
- );
-
- expect(pager(tester).agentId, 'a');
- expect(swipesOver(tester), ['a', 'b']);
- });
-
- testWidgets('the panel opens on the tab the agent on screen is in', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c']),
- ],
- );
-
- await openPanel(tester);
-
- expect(strip(tester).selectedId, 't1');
- expect(agentsShown(tester), ['a', 'b']);
- // Tabs and nothing else: the agents no tab holds are not a chip of their own.
- expect(strip(tester).groups.map((group) => group.name), [
- 'Desktop',
- 'Docker',
- ]);
- });
-
- testWidgets('a tab name changes the cards and leaves the terminal alone', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c', 'd']),
- ],
- );
-
- await openPanel(tester);
- await showTab(tester, 'Docker');
-
- // The other tab's agents are on offer...
- expect(strip(tester).selectedId, 't2');
- expect(agentsShown(tester), ['c', 'd']);
- // ...and the phone is still in the tab it was in, on the agent it was on.
- // Looking into another tab is not leaving this one.
- expect(pager(tester).agentId, 'a');
- expect(swipesOver(tester), ['a', 'b']);
- });
-
- testWidgets('a row opens its agent, and the swipe walks that tab', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c', 'd']),
- ],
- );
-
- await openPanel(tester);
- await showTab(tester, 'Docker');
- await openRow(tester, 'd');
-
- expect(pager(tester).agentId, 'd');
- expect(swipesOver(tester), ['c', 'd']);
- });
-
- group('with nothing of last time to reopen, a launch opens a tab', () {
- testWidgets('the one the phone was last in, on its first agent', (
- tester,
- ) async {
- await pumpHome(
- tester,
- storage: MemoryKeyValueStore()..values['phone_last_tab_v1'] = 't2',
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- deskTab('t2', 'Docker', ['d', 'c']),
- ],
- );
-
- expect(pager(tester).agentId, 'd');
- expect(swipesOver(tester), ['d', 'c']);
- // A fixture with storage persists what it loads; its write timers run out before teardown.
- await tester.pump(const Duration(seconds: 11));
- });
-
- testWidgets('and so does one whose last agent is gone', (tester) async {
- await pumpHome(
- tester,
- storage: MemoryKeyValueStore()
- ..values['phone_last_agent_v1'] = jsonEncode({
- 'machineId': 'm',
- 'agentId': 'deleted',
- })
- ..values['phone_last_tab_v1'] = 't2',
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c', 'd']),
- ],
- );
-
- expect(pager(tester).agentId, 'c');
- // A fixture with storage persists what it loads; its write timers run out before teardown.
- await tester.pump(const Duration(seconds: 11));
- });
-
- testWidgets('or, with none remembered, the first tab with an agent', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Empty', ['gone']),
- deskTab('t2', 'Docker', ['c', 'd']),
- ],
- );
-
- // Never `a` or `b`, which no tab holds — the most recent harness on the account is no
- // longer what a launch lands on while tabs exist.
- expect(pager(tester).agentId, 'c');
- expect(swipesOver(tester), ['c', 'd']);
- });
- });
-
- testWidgets('the panel stays put whatever the tab holds', (tester) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b', 'c']),
- deskTab('t2', 'Docker', ['d']),
- ],
- );
-
- await openPanel(tester);
- final names = tester.getTopLeft(find.byType(DeskTabStrip)).dy;
-
- await showTab(tester, 'Docker');
-
- // A tab of one agent after a tab of three: the panel is the same height,
- // so the names are where the thumb left them.
- expect(agentsShown(tester), ['d']);
- expect(tester.getTopLeft(find.byType(DeskTabStrip)).dy, names);
- });
-
- testWidgets('the agent on screen keeps its row, and wears the check', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c']),
- ],
- );
-
- await openPanel(tester);
-
- expect(
- tester.widget<DeskAgentRow>(row('a')).onScreen,
- isTrue,
- reason: 'the agent on screen',
- );
- expect(tester.widget<DeskAgentRow>(row('b')).onScreen, isFalse);
- });
-
- testWidgets('a tab this phone cannot reach is listed, and says why', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- // A tab of agents no machine here is listing — one asleep, in life.
- deskTab('t2', 'Away', ['gone']),
- ],
- );
-
- await openPanel(tester);
- await showTab(tester, 'Away');
-
- expect(agentsShown(tester), isEmpty);
- expect(find.textContaining('asleep'), findsOneWidget);
- });
-
- testWidgets('an account with no tabs is offered one group over them all', (
- tester,
- ) async {
- // Nothing on the desk: the panel holds one group over every agent on the
- // account, which is what a swipe already walks.
- await pumpHome(tester, tabs: []);
- expect(swipesOver(tester), ['a', 'b', 'c', 'd']);
-
- await openPanel(tester);
-
- expect(strip(tester).groups.map((group) => group.name), [
- kEveryAgentGroupName,
- ]);
- expect(agentsShown(tester), ['a', 'b', 'c', 'd']);
- });
-
- testWidgets('the tabs are a sheet over the terminal, not a row above it', (
- tester,
- ) async {
- await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c']),
- ],
- );
-
- // Nothing is stacked under the header until the Search button is tapped,
- // so the terminal keeps every line it had before the desk existed.
- expect(find.byType(DeskTabStrip), findsNothing);
-
- await openPanel(tester);
-
- expect(find.byType(DeskTabStrip), findsOneWidget);
- });
-
- testWidgets('a tab changed on another computer moves the swipe with it', (
- tester,
- ) async {
- final app = await pumpHome(
- tester,
- tabs: [
- deskTab('t1', 'Desktop', ['a']),
- deskTab('t2', 'Docker', ['c']),
- ],
- );
- expect(swipesOver(tester), ['a']);
-
- // A window on some computer adds an agent to the tab this phone is in.
- deskApiOf(app).tabs = [
- deskTab('t1', 'Desktop', ['a', 'b']),
- deskTab('t2', 'Docker', ['c']),
- ];
- deskApiOf(app).revision++;
- await syncDesk(app);
- await tester.pump();
-
- expect(pager(tester).agentId, 'a');
- expect(swipesOver(tester), ['a', 'b']);
- });
-}
diff --git a/mobile/test/phone_launch_tab_test.dart b/mobile/test/phone_launch_tab_test.dart
new file mode 100644
index 000000000..3ed40154b
--- /dev/null
+++ b/mobile/test/phone_launch_tab_test.dart
@@ -0,0 +1,116 @@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/agent_swipe.dart';
+import 'package:harness_mobile/phone/welcome/pick_up_page.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/desk_sync.dart';
+
+import 'agent_pager_fixture.dart';
+import 'desk_fixture.dart';
+import 'voice_fakes.dart';
+
+/// Which agent a launch opens when the account has desk tabs.
+///
+/// Focus holds ONE agent — there is no sideways swipe any more (see
+/// `docs/plans/2026-09-26-001-mobile-zero-questions.md`) — so the pager is
+/// handed no `neighbours`, and the tabs decide only where a launch lands.
+void main() {
+ /// The home screen as the shell mounts it: an agent picked anywhere else —
+ /// the tabs panel included — arrives through [AgentHome.openAgent], and the
+ /// shell is what carries it there.
+ Future<AppNotifier> pumpHome(
+ WidgetTester tester, {
+ required List<DeskTab> tabs,
+ MemoryKeyValueStore? storage,
+ }) async {
+ final app = await deskApp(
+ PagerConn(),
+ // Nothing here is about the terminals themselves — see [deskApp].
+ opensTerminals: false,
+ tabs: tabs,
+ storage: storage,
+ );
+ addTearDown(app.dispose);
+ final request = ValueNotifier<({String machineId, String agentId})?>(null);
+ addTearDown(request.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (machineId, agentId) =>
+ request.value = (machineId: machineId, agentId: agentId),
+ child: AgentHome(notifier: app, openAgent: request),
+ ),
+ ),
+ );
+ await tester.pump();
+ return app;
+ }
+
+ AgentSwipeHost pager(WidgetTester tester) =>
+ tester.widget<AgentSwipeHost>(find.byType(AgentSwipeHost));
+
+ group('with nothing of last time to reopen, a launch opens a tab', () {
+ testWidgets('the one the phone was last in, on its first agent', (
+ tester,
+ ) async {
+ await pumpHome(
+ tester,
+ storage: MemoryKeyValueStore()..values['phone_last_tab_v1'] = 't2',
+ tabs: [
+ deskTab('t1', 'Desktop', ['a']),
+ deskTab('t2', 'Docker', ['d', 'c']),
+ ],
+ );
+
+ expect(pager(tester).agentId, 'd');
+ expect(pager(tester).neighbours, isNull);
+ // A fixture with storage persists what it loads; its write timers run out before teardown.
+ await tester.pump(const Duration(seconds: 11));
+ });
+
+ testWidgets('and so does one whose last agent is gone', (tester) async {
+ await pumpHome(
+ tester,
+ storage: MemoryKeyValueStore()
+ ..values['phone_last_agent_v1'] = jsonEncode({
+ 'machineId': 'm',
+ 'agentId': 'deleted',
+ })
+ ..values['phone_last_tab_v1'] = 't2',
+ tabs: [
+ deskTab('t1', 'Desktop', ['a', 'b']),
+ deskTab('t2', 'Docker', ['c', 'd']),
+ ],
+ );
+
+ expect(pager(tester).agentId, 'c');
+ // A fixture with storage persists what it loads; its write timers run out before teardown.
+ await tester.pump(const Duration(seconds: 11));
+ });
+
+ testWidgets(
+ 'or, with nothing remembered at all, the sessions to pick from',
+ (tester) async {
+ await pumpHome(
+ tester,
+ tabs: [
+ deskTab('t1', 'Empty', ['gone']),
+ deskTab('t2', 'Docker', ['c', 'd']),
+ ],
+ );
+
+ // A new phone opens on "Pick up where you left off", not on a session guessed for it.
+ expect(find.byType(PickUpPage), findsOneWidget);
+ expect(find.byType(AgentSwipeHost), findsNothing);
+ // Its list reaches the machines as Find does (`reachAllMachines`): let the timers run out.
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ },
+ );
+ });
+}
diff --git a/mobile/test/phone_new_agent_opens_test.dart b/mobile/test/phone_new_agent_opens_test.dart
index aeab1cb85..095d4aa18 100644
--- a/mobile/test/phone_new_agent_opens_test.dart
+++ b/mobile/test/phone_new_agent_opens_test.dart
@@ -24,6 +24,9 @@ class _Conn extends WsConn {
onStatus: (_) {},
);
+ /// Every `agent_create` payload asked for, in order.
+ final created = <Map<String, dynamic>>[];
+
@override
Future<Map<String, dynamic>> request(
String type, {
@@ -31,6 +34,7 @@ class _Conn extends WsConn {
Duration timeout = const Duration(seconds: 20),
}) async {
if (type != 'agent_create') return {};
+ created.add(payload);
return {
'creationId': payload['creationId'],
'state': 'created',
@@ -85,8 +89,8 @@ void main() {
(tester) async {
final app = _app(_Conn());
addTearDown(app.dispose);
- // A folder this machine has been used with before. Its row is titled by the path's last
- // segment, so this is the 'grid' tapped below.
+ // A folder this machine has been used with before — the Project row's
+ // default, titled by the path's last segment.
await app.projectHistory.select('m', '/src/grid');
await tester.pumpWidget(
MaterialApp(
@@ -95,21 +99,11 @@ void main() {
);
await tester.pump();
- // PROJECT and ENGINE are folded shut — the page says what is chosen and
- // opens onto the choices. The folders already worked in are behind Search
- // project, which is a sheet rather than a second fold.
- await tester.tap(find.text('Choose a folder'));
- await tester.pump();
- await tester.tap(find.text('Search project'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- await tester.tap(find.text('grid'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- // Claude is the engine the form starts on, and the ENGINE row now shows
- // it rather than offering it — so there is nothing to tap.
- await tester.pump();
- await tester.tap(find.text('Create Harness'));
+ // The desktop's ⌘N defaults: the project last started here and the engine
+ // the form starts on are already chosen, so the button is the whole flow.
+ expect(find.text('Test host:grid', findRichText: true), findsOneWidget);
+ // Start is the button.
+ await tester.tap(find.text('Start'));
// The create resolves on a microtask, then the route it pushes has to slide in — and only once
// that transition ends does the form's own route come off the stack.
await tester.pump();
@@ -129,4 +123,39 @@ void main() {
);
},
);
+
+ testWidgets(
+ 'the task goes with Start as the first prompt, and only if there is one',
+ (tester) async {
+ final conn = _Conn();
+ final app = _app(conn);
+ addTearDown(app.dispose);
+ await app.projectHistory.select('m', '/src/grid');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: NewAgentPage(notifier: app, machineId: 'm'),
+ ),
+ );
+ await tester.pump();
+ expect(find.text('task (optional)'), findsOneWidget);
+ await tester.enterText(
+ find.byType(TextField),
+ ' fix the login test, then run the suite ',
+ );
+ await tester.pump();
+ await tester.tap(find.text('Start'));
+ await tester.pump();
+ // Not pumpAndSettle: the task field's cursor blinks for as long as it has the keyboard.
+ for (var i = 0; i < 6; i++) {
+ await tester.pump(const Duration(milliseconds: 400));
+ }
+ expect(conn.created, hasLength(1));
+ final choices = conn.created.single;
+ // Wherever the transport nests them, the trimmed task rides as `prompt`.
+ expect(
+ choices.toString(),
+ contains('prompt: fix the login test, then run the suite'),
+ );
+ },
+ );
}
diff --git a/mobile/test/phone_new_agent_test.dart b/mobile/test/phone_new_agent_test.dart
index 1c9f36485..f0b1d569d 100644
--- a/mobile/test/phone_new_agent_test.dart
+++ b/mobile/test/phone_new_agent_test.dart
@@ -7,9 +7,9 @@ import 'package:harness_mobile/phone/new_agent_page.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/ws/ws_conn.dart';
-/// A machine that answers every question with nothing.
+/// A machine that answers every question with nothing — or with [answers], by request type.
class _Conn extends WsConn {
- _Conn()
+ _Conn([this.answers = const {}])
: super(
wsBaseUrl: 'ws://fixture.invalid',
autonomousEnv: 'test',
@@ -20,25 +20,27 @@ class _Conn extends WsConn {
onStatus: (_) {},
);
+ final Map<String, Map<String, dynamic>> answers;
+
@override
Future<Map<String, dynamic>> request(
String type, {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
- }) async => {};
+ }) async => answers[type] ?? {};
}
/// A machine that is answering, and one that is not.
///
/// The second is the whole point of the picker's filter: an agent cannot be created on a machine
/// that has not listed its folders or named its engines, so it must not be offered as a host.
-AppNotifier _app() {
+AppNotifier _app({Map<String, Map<String, dynamic>> answers = const {}}) {
final app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
// The form asks the machine for its engines and Codex profiles as it opens.
- connectionForTest: (_) => _Conn(),
+ connectionForTest: (_) => _Conn(answers),
);
const ready = Machine(
machineId: 'ready',
@@ -64,26 +66,107 @@ AppNotifier _app() {
}
void main() {
- testWidgets('the form offers only machines that can host an agent', (
+ testWidgets(
+ 'the Project chooser offers only machines that can host an agent',
+ (tester) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ // A folder on each machine; the sleeping one's must not be offered.
+ await app.projectHistory.select('ready', '/code/app');
+ await app.projectHistory.select('sleeping', '/code/site');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: NewAgentPage(notifier: app, machineId: 'ready'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // The desktop's default: the project last started on this machine.
+ expect(find.text('Studio:app', findRichText: true), findsOneWidget);
+
+ await tester.tap(find.text('project'));
+ await tester.pumpAndSettle();
+
+ // One row per `machine:folder` pair.
+ expect(
+ find.textContaining('Studio:/code/app', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('Laptop', findRichText: true),
+ findsNothing,
+ reason: 'an offline machine cannot host a new agent',
+ );
+ },
+ );
+
+ testWidgets('a worktree Harness made is not the project: its repository is', (
tester,
) async {
- final app = _app();
+ const worktree =
+ '/home/u/harnesses/worktrees/autonomous-harness/silent-beacon';
+ final app = _app(
+ answers: {
+ 'git_project_info': {
+ 'isGit': true,
+ 'branch': 'silent-beacon',
+ 'root': worktree,
+ 'mainFolder': '/home/u/code/autonomous-harness',
+ 'mainBranch': 'main',
+ 'defaultRef': 'refs/remotes/origin/main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {
+ 'ref': 'refs/remotes/origin/main',
+ 'name': 'origin/main',
+ 'remote': true,
+ },
+ ],
+ },
+ },
+ );
addTearDown(app.dispose);
+ // Opened on another harness's worktree — its folder, handed over as Find hands one.
await tester.pumpWidget(
MaterialApp(
- home: NewAgentPage(notifier: app, machineId: 'ready'),
+ home: NewAgentPage(notifier: app, machineId: 'ready', folder: worktree),
),
);
await tester.pumpAndSettle();
- // The machine row unfolds into the others there are to choose from.
- await tester.tap(find.text('Studio'));
- await tester.pumpAndSettle();
- expect(find.text('Studio'), findsOneWidget);
expect(
- find.text('Laptop'),
+ find.text('Studio:autonomous-harness', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('silent-beacon', findRichText: true),
findsNothing,
- reason: 'an offline machine cannot host a new agent',
);
});
+
+ testWidgets('a swipe right anywhere goes back', (tester) async {
+ final app = _app();
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (_) => NewAgentPage(notifier: app, machineId: 'ready'),
+ ),
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(find.byType(NewAgentPage), findsOneWidget);
+
+ await tester.drag(find.text('agent'), const Offset(200, 0));
+ await tester.pumpAndSettle();
+
+ expect(find.byType(NewAgentPage), findsNothing);
+ });
}
diff --git a/mobile/test/phone_restore_last_agent_test.dart b/mobile/test/phone_restore_last_agent_test.dart
index aa4cfb882..5aa120c55 100644
--- a/mobile/test/phone_restore_last_agent_test.dart
+++ b/mobile/test/phone_restore_last_agent_test.dart
@@ -7,6 +7,7 @@ import 'package:harness_mobile/phone/agent_home.dart';
import 'package:harness_mobile/phone/agent_swipe.dart';
import 'package:harness_mobile/phone/phone_shell_scope.dart';
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/phone/welcome/pick_up_page.dart';
import 'agent_pager_fixture.dart';
import 'desk_fixture.dart';
@@ -130,17 +131,30 @@ void main() {
expect(openedAgent(tester), 'c');
});
- testWidgets('records the agent it opens, so the next launch finds it', (
- tester,
- ) async {
- final storage = MemoryKeyValueStore();
- final notifier = await app(tester, storage: storage);
- machineLists(notifier, [
- for (final id in pagerAgentIds) agent(id, terminal: true),
- ]);
- await pumpHome(tester, notifier);
- expect(storage.values['phone_last_agent_v1'], isNotNull);
- });
+ testWidgets(
+ 'a new phone opens on its sessions; the one picked is recorded for the next launch',
+ (tester) async {
+ final storage = MemoryKeyValueStore();
+ final notifier = await app(tester, storage: storage);
+ machineLists(notifier, [
+ for (final id in pagerAgentIds) agent(id, terminal: true),
+ ]);
+ await pumpHome(tester, notifier);
+ // Nothing remembered: "Pick up where you left off", not a session guessed for it.
+ expect(find.byType(PickUpPage), findsOneWidget);
+ expect(storage.values['phone_last_agent_v1'], isNull);
+
+ // A row tapped there opens through the shell, as Find's do.
+ picked!.value = (machineId: 'm', agentId: 'b');
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 700));
+ expect(openedAgent(tester), 'b');
+ expect(storage.values['phone_last_agent_v1'], contains('"agentId":"b"'));
+ // The welcome's list reaches the machines, and the storage persists: let the timers run out.
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ },
+ );
testWidgets('the next launch opens the agent picked last, not the first', (
tester,
diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dart
index 925e3d53d..7c44c8b5a 100644
--- a/mobile/test/phone_search_test.dart
+++ b/mobile/test/phone_search_test.dart
@@ -16,8 +16,10 @@ import 'package:harness_mobile/phone/phone_search_field.dart';
import 'package:harness_mobile/phone/phone_search_groups.dart';
import 'package:harness_mobile/phone/phone_search_page.dart';
import 'package:harness_mobile/phone/phone_search_rank.dart';
+import 'package:harness_mobile/phone/phone_search_results.dart';
import 'package:harness_mobile/phone/resume_agent.dart';
import 'package:harness_mobile/phone/terminal_search.dart';
+import 'package:harness_mobile/phone/tty_controls.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/pending_question.dart';
import 'package:harness_mobile/ws/ws_conn.dart';
@@ -29,6 +31,7 @@ Agent _agent(
String? title,
String cwd = '/srv/work',
int? minutesAgo,
+ int? openedMinutesAgo,
bool terminal = true,
bool stopped = false,
// Stopped work that a resume can reopen has a saved conversation; `resumable: false` is the
@@ -51,6 +54,9 @@ Agent _agent(
updatedAt: minutesAgo == null
? null
: _now.subtract(Duration(minutes: minutesAgo)),
+ lastOpenedAt: openedMinutesAgo == null
+ ? null
+ : _now.subtract(Duration(minutes: openedMinutesAgo)),
terminalAvailable: stopped ? false : terminal,
);
@@ -93,6 +99,102 @@ AppNotifier _app(
return app;
}
+/// A machine whose session index found "dial" in a Claude Code conversation Harness did not start,
+/// and that resumes it as a harness when asked.
+class _ExternalConn extends WsConn {
+ _ExternalConn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'box',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final created = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'agent_create') {
+ created.add(payload);
+ return {
+ 'state': 'created',
+ 'creationId': payload['creationId'],
+ 'agent': {
+ 'id': 'resumed',
+ 'name': 'Fix the dial',
+ 'status': 'active',
+ 'engine': 'claude',
+ 'terminal': {'available': true},
+ },
+ };
+ }
+ if (type != 'session_search') return {};
+ return {
+ 'hits': [
+ if ((payload['query'] as String).startsWith('dial'))
+ {
+ 'agentId': '',
+ 'sessionId': 'c0ffee',
+ 'engine': 'claude',
+ 'field': 'ask',
+ 'snippet': 'make the \u0002dial\u0003 scroll smoothly',
+ 'together': true,
+ 'score': 1,
+ 'external': {
+ 'cwd': '/home/u/code/dial',
+ 'title': 'Fix the dial',
+ 'origin': 'terminal',
+ 'open': false,
+ },
+ },
+ ],
+ };
+ }
+}
+
+/// A machine whose session index heard "dial" in agent 2312's conversation.
+class _SearchConn extends WsConn {
+ _SearchConn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'box',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type != 'session_search') return {};
+ return {
+ 'hits': [
+ if ((payload['query'] as String).startsWith('dial'))
+ {
+ 'agentId': '2312',
+ 'sessionId': 'session-2312',
+ 'field': 'ask',
+ 'snippet': 'fix the \u0002dial\u0003 scroll',
+ 'together': true,
+ 'score': 1,
+ },
+ ],
+ };
+ }
+}
+
/// A machine answering `agent_recent` with what was asked of each agent, and
/// nothing else.
class _RecentConn extends WsConn {
@@ -945,7 +1047,7 @@ void main() {
expect(_agentIds(_rank(app, '', cache: cache)), ['idle', 'busy']);
});
- test('with nothing typed, the desktop monitor\'s order — visits do not move it', () {
+ test('with nothing typed, last use leads — on any app — and visits only break ties', () {
final app = _app([
_machine('box', [
_agent('alpha', minutesAgo: 90),
@@ -954,17 +1056,34 @@ void main() {
]),
]);
addTearDown(app.dispose);
- // The freshest conversation leads, as it does in the Harness Monitor.
+ // The freshest conversation leads, as it does in the desktop's ⌘P.
expect(_agentIds(_rank(app, '')), ['delta', 'bravo', 'alpha']);
- // ⚠️ This phone's own visits used to outrank that, so the field opened on
- // a list the laptop beside it did not show. The monitor has no idea what
- // the phone visited; neither does its order.
- expect(_agentIds(_rank(app, '', recent: ['agent:box\u0000alpha'])), [
- 'delta',
- 'bravo',
- 'alpha',
+ // ⚠️ **This phone's own visits do not reorder the list.** Last use is
+ // the account's: the desktop's ⌘P reads the same order, and a visit here
+ // reaches it through the daemon's `lastOpenedAt`, not this history.
+ expect(
+ _agentIds(
+ _rank(
+ app,
+ '',
+ recent: ['agent:box\u0000alpha', 'agent:box\u0000bravo'],
+ ),
+ ),
+ ['delta', 'bravo', 'alpha'],
+ );
+ });
+
+ test('opening a harness on another app does not move it: the conversation that moved last leads', () {
+ // The owner: "use conversation last move, not last open — that's the true timestamp".
+ final app = _app([
+ _machine('box', [
+ _agent('alpha', minutesAgo: 90, openedMinutesAgo: 0),
+ _agent('delta', minutesAgo: 1),
+ ]),
]);
+ addTearDown(app.dispose);
+ expect(_agentIds(_rank(app, '')), ['delta', 'alpha']);
});
test('paused work keeps its place by when it last moved', () {
@@ -982,10 +1101,11 @@ void main() {
// `blank` cannot be opened, and still sits where the monitor has it.
expect(_agentIds(search.rows), ['paused', 'blank', 'live']);
- // Once something is typed the match decides, and what a tap cannot open
- // goes last, as it always has.
+ // Typing filters the same order, the desktop ⌘P's rule: every row here
+ // matches, and what a tap cannot open stays where it is, dimmed, rather
+ // than sinking.
search.setQuery('work');
- expect(_agentIds(search.rows).last, 'blank');
+ expect(_agentIds(search.rows), ['paused', 'blank', 'live']);
});
test('an agent is named as the desktop names it, and found by either', () {
@@ -1017,11 +1137,10 @@ void main() {
]);
addTearDown(app.dispose);
- expect([for (final row in _rank(app, '')) row.title], [
- 'Logo update',
- kUntitledPane,
- 'api-server',
- ]);
+ expect(
+ [for (final row in _rank(app, '')) row.title],
+ ['Logo update', kUntitledPane, 'api-server'],
+ );
// The CLI's name is what the terminal's title bar shows, so it still
// finds the row.
expect(_agentIds(_rank(app, 'Terminal harness')).first, 'bare');
@@ -1142,6 +1261,182 @@ void main() {
expect(top('work · 2312'), lessThan(top('work · 9999')));
});
+ test('typing a name puts the harness named for it first, over newer ones whose path spells it', () {
+ // Main's Cmd-P fix, on the phone: `hn` was 6th of 166 — every newer harness under
+ // `.../harnesses/worktrees/autonomous-harness/...` matched its scattered letters, and a typed
+ // list sorted by last use alone.
+ Agent worktree(int i) => Agent(
+ id: 'w$i',
+ name: 'Claude harness $i',
+ status: 'active',
+ engine: 'claude',
+ project: AgentProject(
+ name: 'autonomous-harness',
+ cwd: '/home/u/harnesses/worktrees/autonomous-harness/w$i',
+ ),
+ updatedAt: _now.subtract(Duration(minutes: i)),
+ terminalAvailable: true,
+ );
+ final machine = _machine('box', [
+ for (var i = 0; i < 5; i++) worktree(i),
+ Agent(
+ id: 'hn',
+ name: 'hn',
+ status: 'active',
+ engine: 'claude',
+ project: const AgentProject(
+ name: 'autonomous-harness',
+ cwd: '/home/u/code/autonomous-harness',
+ ),
+ updatedAt: _now.subtract(const Duration(hours: 3)),
+ terminalAvailable: true,
+ ),
+ ]);
+ final app = _app([machine]);
+ addTearDown(app.dispose);
+ final search = PhoneSearchController(notifier: app, modes: false);
+ addTearDown(search.dispose);
+
+ search.setQuery('hn');
+ expect(search.rows.first.title, 'hn');
+ // Two letters count only as initials: not every harness whose path holds an h and an n.
+ expect(search.rows, hasLength(1));
+ });
+
+ testWidgets(
+ 'a word said in a conversation finds its harness, and the row shows where it was said',
+ (tester) async {
+ final machine = _machine('box', [
+ _agent('3188', minutesAgo: 4),
+ _agent('2312', minutesAgo: 30),
+ ]);
+ final app = _app([machine], conn: _SearchConn());
+ addTearDown(app.dispose);
+ final search = PhoneSearchController(notifier: app, modes: false);
+ addTearDown(search.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: PhoneSearchResults(
+ notifier: app,
+ controller: search,
+ fzf: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+
+ // Neither name holds "dial": only what was said in 2312 does.
+ search.setQuery('dial');
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump();
+
+ expect(search.rows.map((row) => row.title), ['work · 2312']);
+ expect(
+ find.textContaining('> fix the dial scroll', findRichText: true),
+ findsOneWidget,
+ );
+ // Opening search reaches the machines (see `reachAllMachines`): let its timers run out.
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ },
+ );
+
+ testWidgets(
+ 'a conversation Harness did not start is found by what was said, and a tap resumes it',
+ (tester) async {
+ final machine = _machine('box', [_agent('3188', minutesAgo: 4)]);
+ final conn = _ExternalConn();
+ final app = _app([machine], conn: conn);
+ addTearDown(app.dispose);
+ final search = PhoneSearchController(notifier: app, modes: false);
+ addTearDown(search.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: PhoneSearchResults(
+ notifier: app,
+ controller: search,
+ fzf: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+
+ search.setQuery('dial');
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump();
+
+ // Only a search shows it — the desktop Cmd-P's rule — with where it was said, and `resume`.
+ expect(find.text('Fix the dial', findRichText: true), findsOneWidget);
+ expect(find.text('resume'), findsOneWidget);
+ expect(
+ find.textContaining('> make the dial scroll', findRichText: true),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.text('Fix the dial', findRichText: true));
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(conn.created.single['resumeSessionId'], 'c0ffee');
+ expect(conn.created.single['cwd'], '/home/u/code/dial');
+ expect(conn.created.single['engine'], 'claude');
+ expect(
+ machine.agents.map((agent) => agent.id),
+ contains('resumed'),
+ reason: 'the new harness joins its machine',
+ );
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ },
+ );
+
+ testWidgets(
+ 'Find holds the order it opened with: a harness that asks stays put',
+ (tester) async {
+ final machine = _machine('box', [
+ _agent('3188', minutesAgo: 4),
+ _agent('2312', minutesAgo: 30),
+ _agent('9999', minutesAgo: 90),
+ ]);
+ final app = _app([machine]);
+ addTearDown(app.dispose);
+ final search = PhoneSearchController(notifier: app);
+ addTearDown(search.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: PhoneSearchResults(
+ notifier: app,
+ controller: search,
+ fzf: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ double top(String name) => tester.getTopLeft(find.text(name)).dy;
+ final was = {
+ for (final id in ['3188', '2312', '9999']) id: top('work · $id'),
+ };
+ expect(find.text('needs you'), findsNothing);
+
+ // The bottom one starts asking, and another one does something new, while Find is open.
+ _markWaiting(machine, '9999');
+ machine.agentActivityAt['2312'] = DateTime.now();
+ app.notifyListeners();
+ await tester.pump();
+
+ // Nothing moved: no `needs you` pushed in above, and every row is where it was.
+ expect(find.text('needs you'), findsNothing);
+ for (final MapEntry(key: id, value: dy) in was.entries) {
+ expect(top('work · $id'), dy, reason: id);
+ }
+ },
+ );
+
testWidgets('opening search warms content; the matching line is quoted', (
tester,
) async {
@@ -1229,7 +1524,7 @@ void main() {
// ⚠️ **The sheet's own bar, not the page's.** No chevron in it: Cancel ends
// the SEARCH and leaves the sheet up on its tabs, and Back steps out of the
// search first and closes the sheet only after — never leaves the agent.
- testWidgets('terminal search: Cancel ends the search, Back then the sheet', (
+ testWidgets('Find: Back ends the search, then Find — no Cancel to find', (
tester,
) async {
final app = _app([
@@ -1249,40 +1544,34 @@ void main() {
),
);
await tester.pump();
- expect(find.byType(SheetSearchField), findsOneWidget);
- expect(find.byType(PhoneSearchField), findsNothing);
- expect(find.text('Cancel'), findsNothing);
+ // The field at the top, and no Cancel: a swipe or Back is the way out.
+ expect(find.byType(TtyField), findsOneWidget);
+ expect(find.byType(SheetSearchField), findsNothing);
- // A tap on the field starts a search; Cancel slides in over 250ms.
Future<void> search() async {
await tester.tap(find.byType(TextField));
await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- expect(find.text('Cancel'), findsOneWidget);
+ await tester.enterText(find.byType(TextField), '31');
+ await tester.pump();
}
Future<void> back() async {
await tester.binding.handlePopRoute();
await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
}
- await search();
- await tester.tap(find.text('Cancel'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
expect(find.text('Cancel'), findsNothing);
- expect(closed, 0);
-
+ // Back ends the search and leaves Find up, then closes it.
await search();
await back();
- expect(find.text('Cancel'), findsNothing);
expect(closed, 0);
-
+ expect(
+ tester.widget<TextField>(find.byType(TextField)).controller!.text,
+ '',
+ );
await back();
expect(closed, 1);
});
-
testWidgets('one bar: no Cancel beside it, and its chevron closes search', (
tester,
) async {
diff --git a/mobile/test/phone_takeover_strip_test.dart b/mobile/test/phone_takeover_strip_test.dart
index 252ddaac5..7d7c95702 100644
--- a/mobile/test/phone_takeover_strip_test.dart
+++ b/mobile/test/phone_takeover_strip_test.dart
@@ -6,18 +6,20 @@ import 'package:harness_mobile/phone/terminal_page.dart';
import 'package:harness_mobile/phone/voice_input_controller.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:xterm/xterm.dart' show TerminalView;
import 'voice_fakes.dart';
-/// Another client took this terminal: the page says who, in one line under
-/// the header, with the way back beside it. A status dot alone was easy to
-/// miss, and the person was about to wonder why typing did nothing.
+/// Another client took this terminal: there is nothing to read or find — a tap on it (or a
+/// scroll) takes it back. The owner's call: "as long as I tap or scroll it should auto take
+/// control".
void main() {
late AppNotifier notifier;
late TerminalSession session;
late VoiceInputController voice;
late ValueNotifier<String> language;
late List<String> opens;
+ late List<(String, Map<String, dynamic>)> sent;
setUp(() {
notifier = AppNotifier(
@@ -26,13 +28,15 @@ void main() {
configStore: null,
);
opens = [];
+ sent = [];
session = TerminalSession(
machineId: 'm',
agentId: 'a',
agentName: 'Agent',
engineId: 'claude',
- send: (type, _) async {
+ send: (type, payload) async {
if (type == 'terminal_open') opens.add(type);
+ sent.add((type, payload));
return true;
},
sendBinary: (_) async => true,
@@ -69,13 +73,10 @@ void main() {
await tester.pump(const Duration(milliseconds: 100));
}
- final strip = find.byKey(const ValueKey('phone-takeover-strip'));
-
testWidgets(
- 'the strip names the taker and is absent while this phone drives',
+ 'a terminal taken elsewhere shows no strip and no Take control to find',
(tester) async {
await pump(tester);
- expect(strip, findsNothing);
await session.handleFrame('terminal_closed', {
'streamId': 's',
'code': 'TERMINAL_TAKEN_OVER',
@@ -83,26 +84,45 @@ void main() {
'takenBy': {'kind': 'desktop', 'name': 'Mac mini'},
});
await tester.pump();
- expect(strip, findsOneWidget);
+ // No strip and no button to find: the terminal is still the terminal.
+ expect(find.byKey(const ValueKey('phone-takeover-strip')), findsNothing);
+ expect(find.text('Take control'), findsNothing);
+ // A tap on it goes to `_takeControl` (TerminalPanel's `onInputTap` while blocked) — which
+ // reopens through the notifier's connection, absent here.
+ await tester.tap(find.byType(TerminalView));
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+
+ testWidgets(
+ 'a take finished after the desktop took the terminal takes it back and lands',
+ (tester) async {
+ await pump(tester);
+ // The desktop took it while the take was being spoken (the log of 2026-09-27: 14:17:43).
+ await session.handleFrame('terminal_closed', {
+ 'streamId': 's',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'another client connected',
+ 'takenBy': {'kind': 'desktop', 'name': 'M2'},
+ });
+ await tester.pump();
+ expect(session.acceptsInput, isFalse);
+
+ final delivered = session.voiceDeliver!('run the tests again');
+ await tester.pump(const Duration(milliseconds: 300));
+ // Not "not sent": it waits for the terminal it asked back for. Here the reopen is
+ // answered by hand — there is no machine behind this notifier.
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's2';
+ await tester.pump(const Duration(milliseconds: 200));
+
+ expect(await delivered, isTrue);
expect(
- find.text('Mac mini took control of this terminal'),
- findsOneWidget,
+ sent
+ .where((frame) => frame.$1 == 'message')
+ .map((f) => f.$2['content']),
+ ['run the tests again'],
);
- // One way back, on the strip; the header's own button stands down.
- expect(find.text('Take control'), findsOneWidget);
},
);
-
- testWidgets('without a name it is another app', (tester) async {
- await pump(tester);
- await session.handleFrame('terminal_closed', {
- 'streamId': 's',
- 'code': 'TERMINAL_TAKEN_OVER',
- });
- await tester.pump();
- expect(
- find.text('Another app took control of this terminal'),
- findsOneWidget,
- );
- });
}
diff --git a/mobile/test/phone_welcome_first_screen_test.dart b/mobile/test/phone_welcome_first_screen_test.dart
new file mode 100644
index 000000000..d56b40e8f
--- /dev/null
+++ b/mobile/test/phone_welcome_first_screen_test.dart
@@ -0,0 +1,277 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/welcome/connect_code.dart';
+import 'package:harness_mobile/phone/welcome/phone_welcome.dart';
+import 'package:harness_mobile/phone/welcome/scan_to_connect.dart';
+import 'package:harness_mobile/phone/welcome/set_up_computer.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'viewer/fake_http.dart';
+
+/// The first screen: what Harness is, one question, and its two answers — scan the code the
+/// desktop app shows, or get Harness onto the computer.
+void main() {
+ group('ConnectCode', () {
+ test('reads the desktop app\'s link, all of it in the fragment', () {
+ final code = ConnectCode.parse(
+ ConnectCode.link('[email protected]', machineId: 'm1', pairCode: 'K7QM'),
+ )!;
+ expect(code.email, '[email protected]');
+ expect(code.machineId, 'm1');
+ expect(code.pairCode, 'K7QM');
+ expect(code.signIn, isNull);
+ final signedIn = ConnectCode.parse(
+ ConnectCode.link(
+ pairCode: 'K7QM',
+ signIn: 'hnh_x-_Y',
+ ),
+ )!;
+ expect(signedIn.signIn, 'hnh_x-_Y');
+ // Nothing secret where a browser would send it.
+ expect(
+ Uri.parse(ConnectCode.link('[email protected]', pairCode: 'K7QM')).query,
+ isEmpty,
+ );
+ });
+
+ test('ignores codes that are not ours', () {
+ expect(ConnectCode.parse('https://example.com/pair#[email protected]'), isNull);
+ expect(
+ ConnectCode.parse('http://harness.autonomous.ai/pair#[email protected]'),
+ isNull,
+ );
+ expect(
+ ConnectCode.parse('https://harness.autonomous.ai/pair#m=m1'),
+ isNull,
+ );
+ expect(ConnectCode.parse('not a link'), isNull);
+ });
+ });
+
+ late AppNotifier notifier;
+ late List<String> sent;
+ late List<String> scanned;
+ Object? scanFails;
+ Completer<void>? scanGate;
+
+ setUp(() {
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ sent = [];
+ scanned = [];
+ scanFails = null;
+ scanGate = null;
+ });
+ tearDown(() => notifier.dispose());
+
+ Future<void> pump(WidgetTester tester, {Widget? camera}) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: PhoneWelcome(
+ notifier: notifier,
+ sendCode: (email) async => sent.add(email),
+ signIn: (_, _) async {},
+ signInWithScan: (code) async {
+ scanned.add(code);
+ await scanGate?.future;
+ if (scanFails case final error?) throw error;
+ },
+ scanCamera: camera ?? const SizedBox(),
+ loadDownloads: () async => const {},
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ testWidgets('one question, two answers, and nothing else', (tester) async {
+ await pump(tester);
+ expect(find.text('Is Harness on your computer?'), findsOneWidget);
+ expect(find.text('Yes — scan to connect'), findsOneWidget);
+ expect(find.text('Not yet — set it up'), findsOneWidget);
+ expect(find.text('Continue with email'), findsNothing);
+ expect(find.text('Try it first'), findsNothing);
+ });
+
+ testWidgets(
+ 'not yet: the website\'s download menu, each row sent to the computer',
+ (tester) async {
+ // A phone's height, so the whole page is on screen.
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(430, 1400);
+ addTearDown(tester.view.reset);
+ await pump(tester);
+ await tester.tap(find.text('Not yet — set it up'));
+ await tester.pump();
+ expect(find.byType(SetUpComputerPage), findsOneWidget);
+ for (final row in [
+ 'Apple Silicon',
+ 'Intel',
+ 'Intel/AMD · Ubuntu, Omarchy and more',
+ 'ARM · Raspberry Pi, ARM servers',
+ 'curl -fsSL …/install.sh | bash',
+ ]) {
+ expect(find.text(row), findsOneWidget, reason: row);
+ }
+ expect(find.text('macOS'), findsNWidgets(2));
+ expect(find.text('Linux'), findsNWidgets(2));
+ expect(
+ find.textContaining('harness.autonomous.ai/desktop'),
+ findsOneWidget,
+ );
+
+ // The CLI row copies the website's command, and says so.
+ String? copied;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ copied = (call.arguments as Map)['text'] as String?;
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ await tester.tap(find.text('curl -fsSL …/install.sh | bash'));
+ await tester.pump();
+ expect(copied, kCliInstall);
+ expect(
+ kCliInstall,
+ 'curl -fsSL https://harness.autonomous.ai/cli/install.sh | bash',
+ );
+ expect(find.text('copied'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 2));
+ expect(find.text('copied'), findsNothing);
+
+ // Back is the first screen.
+ await tester.tap(find.bySemanticsLabel('Back'));
+ await tester.pump();
+ expect(find.text('Is Harness on your computer?'), findsOneWidget);
+ },
+ );
+
+ test('each row\'s file comes from the desktop release manifest', () async {
+ final manifest = FakeHttp({
+ kDesktopManifestUrl: (
+ status: 200,
+ body: {
+ 'desktop-macos-arm64-dmg': {
+ 'version': '1.2.6',
+ 'url': 'https://cdn.autonomous.ai/harness/desktop/1.2.6/Harness-macos-arm64.dmg',
+ },
+ 'desktop-linux-x64': {
+ 'url': 'https://cdn.example/Harness-linux-x64.AppImage',
+ },
+ 'broken': 'not an entry',
+ },
+ ),
+ });
+ final downloads = await loadDesktopDownloads(dio: manifest.dio());
+ expect(downloads, {
+ 'desktop-macos-arm64-dmg': 'https://cdn.autonomous.ai/harness/desktop/1.2.6/Harness-macos-arm64.dmg',
+ 'desktop-linux-x64': 'https://cdn.example/Harness-linux-x64.AppImage',
+ });
+ // Every row names a key the manifest publishes.
+ expect(kDesktopPlatforms.map((p) => p.key), [
+ 'desktop-macos-arm64-dmg',
+ 'desktop-macos-dmg',
+ 'desktop-linux-x64',
+ 'desktop-linux-arm64',
+ ]);
+ // Offline: no files, and every row falls back to the download page.
+ expect(await loadDesktopDownloads(dio: FakeHttp({}).dio()), isEmpty);
+ });
+
+ testWidgets('a scanned code fills in the account and sends its code', (
+ tester,
+ ) async {
+ await pump(tester);
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump();
+ final page = tester.widget<ScanToConnectPage>(
+ find.byType(ScanToConnectPage),
+ );
+ page.onCode(ConnectCode.parse(ConnectCode.link('[email protected]'))!);
+ await tester.pump();
+ await tester.pump();
+ expect(sent, ['[email protected]']);
+ expect(find.text('Check your email'), findsOneWidget);
+ expect(find.textContaining('[email protected]'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'a code that carries a sign-in signs in by the scan: no email, no digits',
+ (tester) async {
+ scanGate = Completer<void>();
+ await pump(tester);
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump();
+ final page = tester.widget<ScanToConnectPage>(
+ find.byType(ScanToConnectPage),
+ );
+ page.onCode(
+ ConnectCode.parse(
+ ConnectCode.link(
+ machineId: 'mac',
+ pairCode: 'K7QM4XPT9D2W',
+ signIn: 'hnh_one',
+ ),
+ )!,
+ );
+ await tester.pump();
+ expect(find.text('Signing in…'), findsOneWidget);
+ scanGate!.complete();
+ await tester.pump();
+ expect(scanned, ['hnh_one']);
+ expect(sent, isEmpty);
+ expect(find.text('Check your email'), findsNothing);
+ expect(notifier.pendingPairing, (machineId: 'mac', code: 'K7QM4XPT9D2W'));
+ },
+ );
+
+ testWidgets('an expired sign-in in the code falls back to the emailed code', (
+ tester,
+ ) async {
+ scanFails = Exception('That code has expired. Scan the new one.');
+ await pump(tester);
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump();
+ tester
+ .widget<ScanToConnectPage>(find.byType(ScanToConnectPage))
+ .onCode(
+ ConnectCode.parse(
+ ConnectCode.link('[email protected]', signIn: 'hnh_old'),
+ )!,
+ );
+ await tester.pump();
+ await tester.pump();
+ await tester.pump();
+ expect(scanned, ['hnh_old']);
+ expect(sent, ['[email protected]']);
+ expect(find.text('Check your email'), findsOneWidget);
+ });
+
+ testWidgets('no code at hand: email instead', (tester) async {
+ await pump(tester);
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump();
+ await tester.tap(find.text('Use email instead'));
+ await tester.pump();
+ expect(find.text('Your email'), findsOneWidget);
+ });
+}
diff --git a/mobile/test/question_keys_test.dart b/mobile/test/question_keys_test.dart
new file mode 100644
index 000000000..8933a637d
--- /dev/null
+++ b/mobile/test/question_keys_test.dart
@@ -0,0 +1,73 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/question_keys.dart';
+import 'package:harness_mobile/terminal/question_pane.dart';
+
+/// Claude's permission dialog, as the pane shows it.
+final _permission = parseQuestionLines([
+ ' Bash command',
+ ' rm -rf build/',
+ ' Do you want to proceed?',
+ ' ❯ 1. Yes',
+ " 2. Yes, and don't ask again for rm commands in /code/api",
+ ' 3. No, and tell Claude what to do differently (esc)',
+ '',
+ ' Esc to cancel · Enter to confirm',
+], QuestionEngine.claude)!;
+
+void main() {
+ test('the keys are the rows, shortened to what a person would say', () {
+ expect(questionKeys(_permission), [
+ (label: 'yes', number: '1'),
+ (label: 'always', number: '2'),
+ (label: 'no', number: '3'),
+ ]);
+ });
+
+ test('a spoken answer presses its key', () {
+ String? press(String said) => matchSpokenAnswer(said, _permission)?.number;
+ expect(press('Yes.'), '1');
+ expect(press('yeah'), '1');
+ expect(press('one'), '1');
+ expect(press('2'), '2');
+ expect(press('always'), '2');
+ expect(press('option three'), '3');
+ expect(press('nope'), '3');
+ });
+
+ test('"no, …" presses no and keeps the rest to send after', () {
+ expect(matchSpokenAnswer('No, use dist instead', _permission), (
+ number: '3',
+ rest: 'use dist instead',
+ ));
+ });
+
+ test('replies that start like yes or no press yes or no', () {
+ String? press(String said) => matchSpokenAnswer(said, _permission)?.number;
+ expect(press('yeah do it'), '1');
+ expect(press('ship it'), '1');
+ expect(press('go for it'), '1');
+ expect(press('sounds good'), '1');
+ expect(press('no wait'), '3');
+ expect(press('hold on'), '3');
+ });
+
+ test('anything else is words for the agent — never dropped, never a blind Return', () {
+ expect(matchSpokenAnswer('use the staging database instead', _permission), (
+ number: '3',
+ rest: 'use the staging database instead',
+ ));
+ expect(matchSpokenAnswer('', _permission), isNull);
+ });
+
+ test('a dialog with nowhere to put words sends nothing', () {
+ final choice = parseQuestionLines([
+ ' Which database?',
+ ' ❯ 1. Postgres',
+ ' 2. SQLite',
+ '',
+ ' Esc to cancel · Enter to confirm',
+ ], QuestionEngine.claude)!;
+ expect(matchSpokenAnswer('the fast one', choice), isNull);
+ expect(matchSpokenAnswer('two', choice)?.number, '2');
+ });
+}
diff --git a/mobile/test/render/phone_screens_render_test.dart b/mobile/test/render/phone_screens_render_test.dart
new file mode 100644
index 000000000..169968d04
--- /dev/null
+++ b/mobile/test/render/phone_screens_render_test.dart
@@ -0,0 +1,631 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/phone/welcome/how_it_works.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
+import 'package:harness_mobile/phone/welcome/focus_hints.dart';
+import 'package:harness_mobile/phone/link_page.dart';
+import 'package:harness_mobile/phone/machines_tab.dart';
+import 'package:harness_mobile/phone/welcome/connect_computer.dart';
+import 'package:harness_mobile/phone/welcome/phone_welcome.dart';
+import 'package:harness_mobile/phone/welcome/set_up_computer.dart';
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/phone/settings_page.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_face.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pending_question.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+import 'package:xterm/xterm.dart';
+
+import '../voice_fakes.dart';
+
+/// Renders the phone's three screens — Focus, Find, New — at iPhone 14 size in
+/// the real system fonts, to PNGs a reviewer (or an agent without a phone) can
+/// look at.
+///
+/// Skipped unless PHONE_RENDER_DIR names a directory to write into:
+///
+/// PHONE_RENDER_DIR=/tmp/renders flutter test test/render/phone_screens_render_test.dart
+///
+/// macOS only: it loads SF Mono and SF Pro from /Library/Fonts.
+final _outDir = Platform.environment['PHONE_RENDER_DIR'];
+
+/// Claude Code, mid-turn, the way its TUI draws on a phone-width terminal.
+const _claudeOutput = [
+ '\x1b[1m⏺\x1b[0m I\'ll look at how Find ranks agents first.\r\n',
+ '\r\n',
+ '\x1b[32m⏺\x1b[0m \x1b[1mRead\x1b[0m(lib/phone/phone_search_rank.dart)\r\n',
+ ' ⎿ Read \x1b[1m262\x1b[0m lines\r\n',
+ '\r\n',
+ '\x1b[1m⏺\x1b[0m The empty-query branch sorts by this\r\n',
+ ' phone\'s visits first, then by activity.\r\n',
+ ' The desktop does the opposite.\r\n',
+ '\r\n',
+ '\x1b[32m⏺\x1b[0m \x1b[1mUpdate\x1b[0m(lib/phone/phone_search_rank.dart)\r\n',
+ ' ⎿ Updated with \x1b[32m18\x1b[0m additions and \x1b[31m7\x1b[0m removals\r\n',
+ ' \x1b[2m183\x1b[0m \x1b[31m- if (needle.isEmpty) {\x1b[0m\r\n',
+ ' \x1b[2m183\x1b[0m \x1b[32m+ if (byActivity || empty) {\x1b[0m\r\n',
+ '\r\n',
+ '\x1b[32m⏺\x1b[0m \x1b[1mBash\x1b[0m(flutter test test/search_test.dart)\r\n',
+ ' ⎿ 00:01 +42: All tests passed!\r\n',
+ '\r\n',
+ '\x1b[1m⏺\x1b[0m Find now orders by last use, the same\r\n',
+ ' order as the desktop\'s ⌘P. Typing filters\r\n',
+ ' without reordering.\r\n',
+ '\r\n',
+ '\x1b[38;5;208m✻\x1b[0m Committing… \x1b[2m(12s · ↓ 1.8k tokens)\x1b[0m\r\n',
+ '\r\n',
+ '\x1b[2m╭──────────────────────────────────────────╮\x1b[0m\r\n',
+ '\x1b[2m│\x1b[0m > \x1b[2m │\x1b[0m\r\n',
+ '\x1b[2m╰──────────────────────────────────────────╯\x1b[0m\r\n',
+ ' \x1b[35m⏵⏵ auto mode on\x1b[0m \x1b[2m(shift+tab to cycle)\x1b[0m\r\n',
+];
+
+class _Conn extends WsConn {
+ _Conn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => {};
+}
+
+Future<void> _loadFont(
+ String family,
+ List<String> files, {
+ String dir = '/Library/Fonts',
+}) async {
+ final loader = FontLoader(family);
+ for (final file in files) {
+ final bytes = await File('$dir/$file').readAsBytes();
+ loader.addFont(Future.value(ByteData.view(bytes.buffer)));
+ }
+ await loader.load();
+}
+
+Future<void> _loadFonts() async {
+ const mono = [
+ 'SF-Mono-Regular.otf',
+ 'SF-Mono-Medium.otf',
+ 'SF-Mono-Semibold.otf',
+ 'SF-Mono-Bold.otf',
+ ];
+ const sans = [
+ 'SF-Pro-Text-Regular.otf',
+ 'SF-Pro-Text-Medium.otf',
+ 'SF-Pro-Text-Semibold.otf',
+ 'SF-Pro-Text-Bold.otf',
+ ];
+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {
+ await _loadFont(family, mono);
+ }
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text']) {
+ await _loadFont(family, sans);
+ }
+ // The icons still on screen (the mic's glyph, the key bar), from the package in the pub cache.
+ final lucide =
+ '${Platform.environment['HOME']}/.pub-cache/hosted/pub.dev/lucide_icons_flutter-3.1.19/assets';
+ if (Directory(lucide).existsSync()) {
+ await _loadFont('packages/lucide_icons_flutter/Lucide', [
+ 'lucide.ttf',
+ ], dir: lucide);
+ for (final weight in [100, 200, 300, 400, 500, 600]) {
+ await _loadFont('packages/lucide_icons_flutter/Lucide$weight', [
+ 'LucideVariable-w$weight.ttf',
+ ], dir: '$lucide/build_font');
+ }
+ }
+ // Material's, for the Apple logo on the set-up page — from the Flutter SDK running the test.
+ final material =
+ '${Platform.environment['FLUTTER_ROOT']}/bin/cache/artifacts/material_fonts';
+ if (File('$material/MaterialIcons-Regular.otf').existsSync()) {
+ await _loadFont('MaterialIcons', [
+ 'MaterialIcons-Regular.otf',
+ ], dir: material);
+ }
+}
+
+Agent _agent(
+ String id,
+ String name, {
+ required String cwd,
+ required int minutesAgo,
+}) => Agent(
+ id: id,
+ name: name,
+ engine: 'claude',
+ sessionId: 'session-$id',
+ status: 'active',
+ project: AgentProject(name: cwd.split('/').last, cwd: cwd, branch: 'main'),
+ updatedAt: DateTime.now().subtract(Duration(minutes: minutesAgo)),
+ terminalAvailable: true,
+);
+
+void main() {
+ final skip = _outDir == null || !Platform.isMacOS;
+
+ late AppNotifier notifier;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+
+ setUp(() async {
+ if (skip) return;
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _Conn(),
+ );
+ const m2 = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'M2',
+ );
+ const mini = Machine(
+ machineId: 'mini',
+ authMode: MachineAuthMode.remote,
+ name: 'mini',
+ );
+ notifier.machines = [m2, mini];
+ notifier.machineStates['m'] = MachineState(m2)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [
+ _agent(
+ 'a',
+ 'hn',
+ cwd: '/Users/me/code/autonomous-harness',
+ minutesAgo: 3,
+ ),
+ _agent(
+ 'b',
+ 'docs-rewrite',
+ cwd: '/Users/me/code/site',
+ minutesAgo: 120,
+ ),
+ ];
+ notifier.machineStates['mini'] = MachineState(mini)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [
+ _agent('c', 'api-fix', cwd: '/Users/me/code/api', minutesAgo: 40),
+ ];
+ // One asking, one working — Find's `needs you` and its state words.
+ notifier.machineStates['mini']!.blockedAgents['c'] = PendingQuestion(
+ machineId: 'mini',
+ agentId: 'c',
+ requestId: 'q1',
+ answerKey: '1',
+ prompt: 'Run the migration on the test db?',
+ options: const ['Yes', 'No'],
+ multi: false,
+ since: DateTime.now().subtract(const Duration(minutes: 2)),
+ );
+ notifier.machineStates['m']!.processingAgentIds.add('b');
+ final session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'hn',
+ engineId: 'claude',
+ send: (type, payload) async => true,
+ sendBinary: (_) async => true,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's';
+ // A screen to show — kept from "last time", which is what a render needs: the live path waits
+ // for a keyframe this fixture has no machine to send.
+ final screen = Terminal(maxLines: 1000)..resize(46, 49);
+ for (var line = 0; line < 60; line++) {
+ screen.write('earlier output line $line\r\n');
+ }
+ for (final chunk in _claudeOutput) {
+ screen.write(chunk);
+ }
+ session.seedScreen(screen);
+ notifier.adoptSessionForTest(session);
+ await notifier.projectHistory.select(
+ 'm',
+ '/Users/me/code/autonomous-harness',
+ );
+ language = ValueNotifier('en');
+ voice = VoiceInputController(
+ transcriber: FakeTranscriber().call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ });
+
+ tearDown(() {
+ if (skip) return;
+ voice.dispose();
+ language.dispose();
+ notifier.dispose();
+ });
+
+ Future<void> shoot(WidgetTester tester, GlobalKey key, String name) async {
+ await tester.runAsync(() async {
+ final boundary =
+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$_outDir/$name.png').writeAsBytes(png!.buffer.asUint8List());
+ });
+ // Done with the screen: take it down and run its clocks out, so no timer outlives the test.
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 10));
+ }
+
+ Future<GlobalKey> pumpScreen(WidgetTester tester, Widget home) async {
+ await tester.runAsync(_loadFonts);
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ tester.view.viewPadding = const FakeViewPadding(
+ top: 47 * 3,
+ bottom: 34 * 3,
+ );
+ addTearDown(tester.view.reset);
+ final key = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: key,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: home,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump(const Duration(milliseconds: 200));
+ return key;
+ }
+
+ TerminalPage focus() => TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ );
+
+ testWidgets('welcome', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ PhoneWelcome(notifier: notifier, onTrySample: (_) async => null),
+ );
+ await shoot(tester, key, '0-welcome');
+ });
+
+ testWidgets('welcome, email then code', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ PhoneWelcome(
+ notifier: notifier,
+ onTrySample: (_) async => null,
+ sendCode: (_) async {},
+ signIn: (_, _) async {},
+ scanCamera: const SizedBox(),
+ ),
+ );
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '0a-welcome-scan');
+ await tester.tap(find.text('Use email instead'));
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.enterText(
+ find.byKey(const Key('welcome-email')).last,
+ );
+ await tester.pump();
+ await shoot(tester, key, '0b-welcome-email');
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('welcome, code', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ PhoneWelcome(
+ notifier: notifier,
+ onTrySample: (_) async => null,
+ sendCode: (_) async {},
+ signIn: (_, _) async {},
+ scanCamera: const SizedBox(),
+ ),
+ );
+ await tester.tap(find.text('Yes — scan to connect'));
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.tap(find.text('Use email instead'));
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.enterText(find.byType(TextField), '[email protected]');
+ await tester.tap(find.text('Send code'));
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.enterText(find.byType(TextField), '42');
+ await tester.pump();
+ await shoot(tester, key, '0c-welcome-code');
+ });
+
+ testWidgets('set up your computer', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ ConnectComputerPage(notifier: notifier, onTrySample: (_) async => null),
+ );
+ await shoot(tester, key, '0d-connect-computer');
+ });
+
+ testWidgets('set up, download menu', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ Builder(
+ builder: (context) => Scaffold(
+ backgroundColor: Tty.of(context).ground,
+ body: SafeArea(
+ child: SetUpComputerPage(
+ onScan: () {},
+ onBack: () {},
+ loadDownloads: () async => const {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await shoot(tester, key, '0e-set-up');
+ });
+
+ void addOtherComputers() {
+ const studio = Machine(
+ machineId: 'studio',
+ authMode: MachineAuthMode.remote,
+ name: 'studio',
+ );
+ const laptop = Machine(
+ machineId: 'laptop',
+ authMode: MachineAuthMode.remote,
+ name: 'laptop',
+ );
+ notifier.machines = [...notifier.machines, studio, laptop];
+ notifier.machineStates['studio'] = MachineState(studio)
+ ..nodeOnline = true
+ ..needsLink = true
+ ..agentLoadStatus = AgentLoadStatus.needsLink;
+ notifier.machineStates['laptop'] = MachineState(laptop)..nodeOnline = false;
+ }
+
+ testWidgets('computers', skip: skip, (tester) async {
+ addOtherComputers();
+ final key = await pumpScreen(tester, MachinesTab(notifier: notifier));
+ await shoot(tester, key, '0e-computers');
+ });
+
+ testWidgets('unlock a computer', skip: skip, (tester) async {
+ addOtherComputers();
+ final key = await pumpScreen(
+ tester,
+ LinkPage(notifier: notifier, machineId: 'studio'),
+ );
+ await shoot(tester, key, '0f-unlock');
+ });
+
+ testWidgets('how it works', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, const HowItWorksPage());
+ await shoot(tester, key, '0g-how-it-works');
+ });
+
+ testWidgets('focus', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await shoot(tester, key, '1-focus');
+ });
+
+ testWidgets('focus, scrolled up while output arrives', skip: skip, (
+ tester,
+ ) async {
+ final key = await pumpScreen(tester, focus());
+ await tester.drag(find.byType(TerminalView), const Offset(0, 400));
+ await tester.pump(const Duration(milliseconds: 200));
+ final session = notifier.panes.first.session!;
+ session.outputTicks.value++;
+ session.terminal.write('more output\r\n');
+ await tester.pump(const Duration(milliseconds: 200));
+ await shoot(tester, key, '2-focus-scrolled');
+ });
+
+ testWidgets('find', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 500));
+ await shoot(tester, key, '3-find');
+ });
+
+ testWidgets('new', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ NewAgentPage(notifier: notifier, machineId: 'm', voice: voice),
+ );
+ await tester.pump(const Duration(milliseconds: 400));
+ await shoot(tester, key, '4-new');
+ });
+
+ testWidgets('focus, keyboard up', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await tester.tap(find.byType(TerminalView));
+ await tester.pump();
+ tester.view.viewInsets = const FakeViewPadding(bottom: 336 * 3);
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '1b-focus-keyboard');
+ });
+
+ testWidgets('focus, recording', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await tester.tap(find.byType(VoiceMicCore));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '1c-focus-recording');
+ // The take's clock is the controller's, not the screen's: throw the take away to stop it.
+ voice.clear();
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets('focus, prompt', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ notifier.panes.first.session!.terminal.write(
+ '\r\n\x1b[2m────────────────────────────────────────────\x1b[0m\r\n'
+ ' \x1b[1mBash command\x1b[0m\r\n'
+ ' rm -rf build/ && flutter build ios\r\n'
+ ' Do you want to proceed?\r\n'
+ ' \x1b[36m❯ 1. Yes\x1b[0m\r\n'
+ " 2. Yes, and don't ask again for rm commands\r\n"
+ ' 3. No, and tell Claude what to do differently\r\n'
+ '\r\n'
+ ' \x1b[2mEsc to cancel · Enter to confirm\x1b[0m',
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '1e-focus-prompt');
+ });
+
+ testWidgets('focus, first time', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ Stack(
+ children: [
+ focus(),
+ Positioned.fill(
+ child: FocusHints(
+ micBottom: 34 + 4 * 15.6,
+ store: FocusHintsSeen(storage: _MemoryStore()),
+ ),
+ ),
+ ],
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await shoot(tester, key, '1f-focus-first-time');
+ });
+
+ testWidgets('focus, actions', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await tester.tap(find.text('…'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 500));
+ await shoot(tester, key, '1d-focus-actions');
+ });
+
+ Future<void> openFind(WidgetTester tester) async {
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 500));
+ }
+
+ testWidgets('find, typed', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await openFind(tester);
+ await tester.enterText(find.byType(TextField), 'ap');
+ await tester.pump(const Duration(milliseconds: 200));
+ await shoot(tester, key, '3b-find-typed');
+ });
+
+ testWidgets('find, commands', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, focus());
+ await openFind(tester);
+ await tester.enterText(find.byType(TextField), '>');
+ await tester.pump(const Duration(milliseconds: 200));
+ await shoot(tester, key, '3c-find-commands');
+ });
+
+ testWidgets('new, task typed', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ NewAgentPage(notifier: notifier, machineId: 'm', voice: voice),
+ );
+ await tester.enterText(
+ find.byType(TextField),
+ 'Fix the login test that fails on CI, then run the whole suite.',
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '4b-new-task');
+ });
+
+ testWidgets('new, keyboard up', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ NewAgentPage(notifier: notifier, machineId: 'm', voice: voice),
+ );
+ await tester.tap(find.byType(TextField));
+ await tester.enterText(find.byType(TextField), 'Fix the login test');
+ tester.view.viewInsets = const FakeViewPadding(bottom: 336 * 3);
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '4e-new-keyboard');
+ });
+
+ testWidgets('new, project chooser', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ NewAgentPage(notifier: notifier, machineId: 'm', voice: voice),
+ );
+ await tester.tap(find.text('project'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '4c-new-project-chooser');
+ });
+
+ testWidgets('new, agent chooser', skip: skip, (tester) async {
+ final key = await pumpScreen(
+ tester,
+ NewAgentPage(notifier: notifier, machineId: 'm', voice: voice),
+ );
+ await tester.tap(find.text('agent'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ await shoot(tester, key, '4d-new-agent-chooser');
+ });
+
+ testWidgets('settings', skip: skip, (tester) async {
+ final key = await pumpScreen(tester, SettingsPage(notifier: notifier));
+ await shoot(tester, key, '5-settings');
+ });
+}
+
+class _MemoryStore implements LocalKeyValueStore {
+ final _values = <String, String>{};
+
+ @override
+ Future<String?> read(String key) async => _values[key];
+
+ @override
+ Future<void> write(String key, String value) async => _values[key] = value;
+
+ @override
+ Future<void> delete(String key) async => _values.remove(key);
+}
diff --git a/mobile/test/sample_mode_test.dart b/mobile/test/sample_mode_test.dart
new file mode 100644
index 000000000..c8db0b48a
--- /dev/null
+++ b/mobile/test/sample_mode_test.dart
@@ -0,0 +1,314 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/demo/sample_mode.dart';
+import 'package:harness_mobile/demo/sample_screen.dart' show SayEntry;
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/phone_shell.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/state/app_state.dart';
+
+const _studio = 'sample-studio';
+
+/// Sample mode, walked as somebody trying the app for the first time would: it opens on a
+/// harness at work, Find lists the rest, a message gets an answer, the question gets answered,
+/// New makes another harness — and leaving takes all of it away.
+void main() {
+ Future<void> settle(WidgetTester tester, Duration total) async {
+ const step = Duration(milliseconds: 100);
+ for (var spent = Duration.zero; spent < total; spent += step) {
+ await tester.pump(step);
+ }
+ }
+
+ Future<AppNotifier> openSample(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: Center(
+ child: TextButton(
+ onPressed: () => openSampleMode(context),
+ child: const Text('Try a sample'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Try a sample'));
+ await settle(tester, const Duration(seconds: 2));
+ // It opens on its sessions to pick from, as a new phone does: the working one is picked.
+ expect(find.byKey(const ValueKey('pick-up-title')), findsOneWidget);
+ await tester.tap(find.text('fix-login', findRichText: true).first);
+ await settle(tester, const Duration(seconds: 2));
+ return tester.widget<PhoneShell>(find.byType(PhoneShell)).notifier;
+ }
+
+ /// Everything in the agent's terminal, scrollback included — as one line, so a sentence the
+ /// pane wrapped still reads as the sentence.
+ String screenOf(AppNotifier notifier, String agentId, [String? machineId]) {
+ final session = notifier
+ .paneOfAgent(machineId ?? _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*'), ' ');
+ }
+
+ /// Puts [agentId] on screen the way Find does — through the shell.
+ Future<void> open(
+ WidgetTester tester,
+ String agentId, [
+ String machineId = _studio,
+ ]) async {
+ PhoneShellScope.maybeOf(tester.element(find.byType(AgentHome)))!
+ .onOpenAgent(machineId, agentId);
+ await settle(tester, const Duration(seconds: 2));
+ }
+
+ /// Takes the app down. No clock is run out after it: taking the sample down cancels every
+ /// timer it started, and the framework fails the test if one is left pending.
+ Future<void> closeDown(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ }
+
+ testWidgets('opens on the working harness, and it keeps working', (
+ tester,
+ ) async {
+ final notifier = await openSample(tester);
+
+ expect(
+ screenOf(notifier, 'sample-fix-login'),
+ contains('Read(src/auth/session.ts)'),
+ reason: 'the terminal shows the session so far',
+ );
+ expect(notifier.agentIsProcessing(_studio, 'sample-fix-login'), isTrue);
+ await settle(tester, const Duration(seconds: 6));
+ expect(
+ screenOf(notifier, 'sample-fix-login'),
+ contains('ensureSession'),
+ reason: 'new output streams in while it works',
+ );
+ await closeDown(tester);
+ });
+
+ testWidgets('Find lists every harness, and the question is waiting', (
+ tester,
+ ) async {
+ final notifier = await openSample(tester);
+
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await settle(tester, const Duration(milliseconds: 600));
+ for (final name in [
+ 'fix-login',
+ 'api-tests',
+ 'docs-site',
+ 'refactor-db',
+ 'mobile-ui',
+ ]) {
+ expect(
+ find.textContaining(name, findRichText: true),
+ findsWidgets,
+ reason: '$name is in Find',
+ );
+ }
+ expect(
+ notifier.questionFor(_studio, 'sample-refactor-db')?.prompt,
+ 'Do you want to proceed?',
+ );
+ await closeDown(tester);
+ });
+
+ testWidgets('text sent to a harness gets a reply in its terminal', (
+ tester,
+ ) async {
+ final notifier = await openSample(tester);
+ await open(tester, 'sample-docs-site', 'sample-laptop');
+ final session = notifier
+ .paneOfAgent('sample-laptop', 'sample-docs-site')!
+ .session!;
+
+ expect(await session.sendComposerText('add a search box'), isTrue);
+ await settle(tester, const Duration(seconds: 8));
+
+ final screen = screenOf(notifier, 'sample-docs-site', 'sample-laptop');
+ expect(screen, contains('> add a search box'));
+ expect(screen, contains('⏺ On it — add a search box'));
+ expect(screen, contains('Update(src/components/Header.astro)'));
+ expect(screen, contains('Done —'));
+ await closeDown(tester);
+ });
+
+ testWidgets('a voice take is heard and answered', (tester) async {
+ final notifier = await openSample(tester);
+ await open(tester, 'sample-mobile-ui', 'sample-laptop');
+
+ await tester.tap(find.byType(VoiceMicCore));
+ await settle(tester, const Duration(milliseconds: 800));
+ await tester.tap(find.byType(VoiceMicCore));
+ await settle(tester, const Duration(seconds: 12));
+
+ final screen = screenOf(notifier, 'sample-mobile-ui', 'sample-laptop');
+ expect(screen, contains('› run the tests and fix whatever fails'));
+ expect(screen, contains('• On it — run the tests and fix whatever fails'));
+ expect(screen, contains('Ran flutter test'));
+ await closeDown(tester);
+ });
+
+ testWidgets('answering the question closes it and the harness goes on', (
+ tester,
+ ) async {
+ final notifier = await openSample(tester);
+ await open(tester, 'sample-refactor-db');
+
+ expect(screenOf(notifier, 'sample-refactor-db'), contains('❯ 1. Yes'));
+ await tester.tap(find.textContaining('1 yes', findRichText: true).first);
+ await settle(tester, const Duration(seconds: 12));
+
+ final screen = screenOf(notifier, 'sample-refactor-db');
+ expect(screen, contains('COMMIT'));
+ expect(screen, contains('Migration applied'));
+ expect(notifier.questionFor(_studio, 'sample-refactor-db'), isNull);
+ await closeDown(tester);
+ });
+
+ testWidgets('answering No closes the question and asks what to do instead', (
+ tester,
+ ) async {
+ final runtime = SampleRuntime();
+ final harness = runtime.harnessOf(_studio, 'sample-refactor-db')!;
+ expect(harness.asking, isTrue);
+
+ harness.keys('3');
+ expect(runtime.notifier.questionFor(_studio, 'sample-refactor-db'), isNull);
+ await tester.pump(const Duration(seconds: 3));
+
+ expect(
+ harness.transcript.whereType<SayEntry>().last.text,
+ contains('What should I do instead?'),
+ );
+ expect(harness.working, isFalse);
+ runtime.dispose();
+ });
+
+ testWidgets('New makes a harness, and one with a first task works on it', (
+ tester,
+ ) async {
+ final notifier = await openSample(tester);
+
+ // New is a swipe left from the terminal.
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) + const Offset(120, 0),
+ const Offset(-240, 0),
+ );
+ await settle(tester, const Duration(seconds: 1));
+ await tester.tap(find.text('project'));
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.tap(
+ find.textContaining('studio:~/code/web', findRichText: true),
+ );
+ await settle(tester, const Duration(milliseconds: 500));
+ // The first task, typed into New's task field, goes with Start.
+ await tester.enterText(find.byType(TextField), 'fix the flaky test');
+ await tester.tap(find.text('Start'));
+ await settle(tester, const Duration(seconds: 3));
+
+ final made = notifier
+ .stateOf(_studio)!
+ .agents
+ .where((agent) => agent.id.startsWith('sample-new-'))
+ .single;
+ expect(notifier.focusedPane?.agentId, made.id, reason: 'it opens');
+ expect(screenOf(notifier, made.id), contains('Welcome to Claude Code'));
+
+ // A first task: what `createAgent` sends with one.
+ final reply = await notifier.connectionForTest!(_studio).request(
+ 'agent_create',
+ payload: {
+ 'engine': 'codex',
+ 'cwd': '~/code/api',
+ 'creationId': 'first-task',
+ 'prompt': 'add rate limiting to the login route',
+ },
+ );
+ final id = (reply['agent'] as Map)['id'] as String;
+ await tester.pump();
+ expect(
+ notifier.stateOf(_studio)!.agents.map((agent) => agent.id),
+ contains(id),
+ reason: 'every app hears about the new harness',
+ );
+ await open(tester, id);
+ await settle(tester, const Duration(seconds: 6));
+ final screen = screenOf(notifier, id);
+ expect(screen, contains('› add rate limiting to the login route'));
+ expect(screen, contains('• On it — add rate limiting to the login route'));
+ await closeDown(tester);
+ });
+
+ testWidgets('Rename and Stop in the … menu work', (tester) async {
+ final notifier = await openSample(tester);
+ await open(tester, 'sample-docs-site', 'sample-laptop');
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.tap(find.text('Rename…'));
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.enterText(find.byType(TextField).last, 'docs-dark-mode');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await settle(tester, const Duration(seconds: 1));
+ expect(
+ notifier
+ .stateOf('sample-laptop')!
+ .agents
+ .any((agent) => agent.name == 'docs-dark-mode'),
+ isTrue,
+ );
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.tap(find.text('Stop this harness…'));
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.tap(find.text('Stop').last);
+ await settle(tester, const Duration(seconds: 2));
+ expect(
+ notifier
+ .stateOf('sample-laptop')!
+ .agents
+ .any((agent) => agent.id == 'sample-docs-site'),
+ isFalse,
+ );
+ await closeDown(tester);
+ });
+
+ testWidgets('Leave sample in Settings goes back and ends it', (tester) async {
+ final notifier = await openSample(tester);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')).first);
+ await settle(tester, const Duration(milliseconds: 500));
+ await tester.tap(find.text('Settings'));
+ await settle(tester, const Duration(seconds: 1));
+ expect(find.text('Sign out'), findsNothing);
+ await tester.tap(find.text('Leave sample'));
+ await settle(tester, const Duration(seconds: 2));
+
+ expect(find.byType(PhoneShell), findsNothing);
+ expect(find.text('Try a sample'), findsOneWidget);
+ expect(SampleMode.ofNotifier(notifier), isNull);
+ expect(() => notifier.addListener(() {}), throwsFlutterError);
+ await closeDown(tester);
+ });
+}
diff --git a/mobile/test/search_when_test.dart b/mobile/test/search_when_test.dart
new file mode 100644
index 000000000..d049ebd9c
--- /dev/null
+++ b/mobile/test/search_when_test.dart
@@ -0,0 +1,87 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/state/search_when.dart';
+
+void main() {
+ // Saturday 26 September 2026, 14:30 local.
+ final now = DateTime(2026, 9, 26, 14, 30);
+ DateTime day(int d) => DateTime(2026, 9, d);
+
+ ({String words, DateTime? from, DateTime? to}) read(String query) {
+ final parsed = parseSearchWhen(query, now);
+ return (words: parsed.words, from: parsed.when?.from, to: parsed.when?.to);
+ }
+
+ test(
+ 'reads the common ways of saying when, and takes them out of the words',
+ () {
+ expect(read('dial today'), (words: 'dial', from: day(26), to: now));
+ expect(read('yesterday dial'), (
+ words: 'dial',
+ from: day(25),
+ to: day(26),
+ ));
+ expect(read('dial this week'), (words: 'dial', from: day(21), to: now));
+ expect(read('dial LAST WEEK scroll'), (
+ words: 'dial scroll',
+ from: day(14),
+ to: day(21),
+ ));
+ expect(read('cohorts last month'), (
+ words: 'cohorts',
+ from: DateTime(2026, 8),
+ to: DateTime(2026, 9),
+ ));
+ },
+ );
+
+ test('keeps "ago" loose, the way memory is', () {
+ expect(read('dial 3 days ago'), (
+ words: 'dial',
+ from: day(22),
+ to: day(25),
+ ));
+ expect(read('a few days ago mobile'), (
+ words: 'mobile',
+ from: day(20),
+ to: day(25),
+ ));
+ expect(read('two weeks ago'), (words: '', from: day(8), to: day(17)));
+ expect(read('a week ago dial'), (
+ words: 'dial',
+ from: day(15),
+ to: day(24),
+ ));
+ });
+
+ test('a weekday is its most recent one; "last" skips today', () {
+ // 26 September 2026 is a Saturday.
+ expect(read('dial on monday'), (words: 'dial', from: day(21), to: day(22)));
+ expect(read('on friday'), (words: '', from: day(25), to: day(26)));
+ expect(read('dial on saturday'), (words: 'dial', from: day(26), to: now));
+ expect(read('dial last saturday'), (
+ words: 'dial',
+ from: day(19),
+ to: day(20),
+ ));
+ });
+
+ test('"0 days ago" is today, as the CLI reads it', () {
+ expect(read('dial 0 days ago'), (words: 'dial', from: day(25), to: now));
+ });
+
+ test('leaves words alone that only look like time', () {
+ for (final query in [
+ 'dial',
+ 'todays menu',
+ 'sundays',
+ 'weekday parser',
+ 'lastweek',
+ 'sun mon',
+ 'days ago',
+ 'friday deploy',
+ ]) {
+ expect(parseSearchWhen(query, now).when, isNull, reason: query);
+ expect(parseSearchWhen(query, now).words, query);
+ }
+ });
+}
diff --git a/mobile/test/session_content_search_test.dart b/mobile/test/session_content_search_test.dart
new file mode 100644
index 000000000..9a60162ff
--- /dev/null
+++ b/mobile/test/session_content_search_test.dart
@@ -0,0 +1,222 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/phone_search_catalog.dart'
+ show phoneAgentId;
+import 'package:harness_mobile/phone/search_result_text.dart' show snippetLead, snippetRuns;
+import 'package:harness_mobile/state/session_content_search.dart';
+
+/// The desktop's `session_content_search_test.dart`, for the same file on the phone: Find asks
+/// every machine's session index as Cmd-P does.
+const _o = kSnippetMarkOpen;
+const _c = kSnippetMarkClose;
+
+SessionContentHit hit(
+ String agentId, {
+ String machineId = 'm',
+ bool together = true,
+ double score = .5,
+ int position = 0,
+ String snippet = 'the ${_o}dial$_c scroll',
+ String field = 'ask',
+}) => SessionContentHit(
+ machineId: machineId,
+ agentId: agentId,
+ sessionId: 'session-$agentId',
+ field: field,
+ snippet: snippet,
+ together: together,
+ score: score,
+ position: position,
+);
+
+Future<void> settle() => Future<void>.delayed(const Duration(milliseconds: 30));
+
+void main() {
+ group('SessionContentHit', () {
+ test('reads a daemon reply and refuses what it cannot use', () {
+ final hits = SessionContentHit.listFromReply('m', {
+ 'hits': [
+ {
+ 'agentId': 'a1',
+ 'sessionId': 's1',
+ 'field': 'answer',
+ 'snippet': 'halved the ${_o}scroll$_c delta',
+ 'together': true,
+ 'score': 1.7,
+ 'turn': 4,
+ 'at': 1790000000000,
+ },
+ {'sessionId': 's2'},
+ 'junk',
+ ],
+ });
+ expect(hits, hasLength(1));
+ expect(hits.single.destinationId, phoneAgentId('m', 'a1'));
+ expect(hits.single.score, 1);
+ expect(hits.single.plainSnippet, 'halved the scroll delta');
+ expect(
+ hits.single.at,
+ DateTime.fromMillisecondsSinceEpoch(1790000000000),
+ );
+ expect(SessionContentHit.listFromReply('m', {'error': 'X'}), isEmpty);
+ });
+
+ test('snippet runs bold exactly the marked words', () {
+ expect(snippetRuns('a ${_o}dial$_c and ${_o}scroll$_c.'), [
+ (text: 'a ', matched: false),
+ (text: 'dial', matched: true),
+ (text: ' and ', matched: false),
+ (text: 'scroll', matched: true),
+ (text: '.', matched: false),
+ ]);
+ expect(snippetRuns('unclosed ${_o}mark'), [
+ (text: 'unclosed ', matched: false),
+ (text: 'mark', matched: true),
+ ]);
+ expect(snippetLead('ask'), '> ');
+ expect(snippetLead('tools'), r'$ ');
+ expect(snippetLead('answer'), '');
+ });
+ });
+
+ group('SessionContentSearch', () {
+ test('asks every machine once per pause in typing and keeps the best hit per harness', () async {
+ final asked = <(String, String)>[];
+ final gate = Completer<void>();
+ final search = SessionContentSearch(
+ machines: () => ['m', 'n'],
+ debounce: const Duration(milliseconds: 5),
+ ask: (machine, query, _) async {
+ asked.add((machine, query));
+ if (machine == 'n') await gate.future;
+ return machine == 'm'
+ ? [
+ hit('a1', together: false, score: .9),
+ hit('a1', together: true, score: .2),
+ ]
+ : [hit('b1', machineId: 'n')];
+ },
+ );
+ addTearDown(search.dispose);
+ search.search('d');
+ search.search('di');
+ search.search('dia');
+ search.search('dial');
+ await settle();
+ expect(asked, [('m', 'dial'), ('n', 'dial')]);
+ // One harness, its best conversation: all words together beats spread.
+ expect(search.hits.keys, [phoneAgentId('m', 'a1')]);
+ expect(search.hits.values.single.together, isTrue);
+ expect(search.answered, 'dial');
+ gate.complete();
+ await settle();
+ expect(search.hits.keys, hasLength(2));
+ });
+
+ test(
+ 'drops a late answer to an older question and clears for new words',
+ () async {
+ final answers = <String, Completer<List<SessionContentHit>?>>{};
+ final search = SessionContentSearch(
+ machines: () => ['m'],
+ debounce: Duration.zero,
+ ask: (_, query, _) => (answers[query] = Completer()).future,
+ );
+ addTearDown(search.dispose);
+ search.search('dial');
+ await settle();
+ search.search('dial scroll');
+ await settle();
+ answers['dial']!.complete([hit('old')]);
+ await settle();
+ expect(search.hits, isEmpty);
+ answers['dial scroll']!.complete([hit('new')]);
+ await settle();
+ expect(search.hits.keys, [phoneAgentId('m', 'new')]);
+ // Typing on keeps the answer on screen; different words clear it.
+ search.search('dial scroll f');
+ expect(search.hits, isNotEmpty);
+ search.search('keyboard');
+ expect(search.hits, isEmpty);
+ search.search('k');
+ await settle();
+ expect(answers.keys, isNot(contains('k')));
+ },
+ );
+ });
+
+ test('an earlier answer vouches only for words its snippet shows', () async {
+ final search = SessionContentSearch(
+ machines: () => ['m'],
+ debounce: Duration.zero,
+ ask: (_, query, _) async => query == 'mob'
+ ? [
+ hit('a1', snippet: 'the ${_o}mobile$_c swipe feels slow'),
+ hit('a2', snippet: 'the ${_o}mobile$_c build broke'),
+ ]
+ : Completer<List<SessionContentHit>?>().future,
+ );
+ addTearDown(search.dispose);
+ search.search('mob');
+ await settle();
+ expect(search.hitsFor('mob').keys, hasLength(2));
+ search.search('mob swipe');
+ expect(search.hitsFor('mob swipe').keys, [phoneAgentId('m', 'a1')]);
+ expect(search.hitsFor('mob swi').keys, [phoneAgentId('m', 'a1')]);
+ expect(search.hitsFor('mob build keyboard'), isEmpty);
+ });
+
+ test(
+ 'a time in the words goes to the machines as a window, not as words',
+ () async {
+ final asked = <(String, DateTime?, DateTime?)>[];
+ final search = SessionContentSearch(
+ machines: () => ['m'],
+ debounce: Duration.zero,
+ now: () => DateTime(2026, 9, 26, 14, 30),
+ ask: (_, words, when) async {
+ asked.add((words, when?.from, when?.to));
+ return [hit('a1', snippet: 'fix the ${_o}dial$_c')];
+ },
+ );
+ addTearDown(search.dispose);
+ search.search('dial last week');
+ await settle();
+ expect(asked, [('dial', DateTime(2026, 9, 14), DateTime(2026, 9, 21))]);
+ expect(search.hitsFor('dial last week'), hasLength(1));
+ // Another time: that answer says nothing about it.
+ expect(search.hitsFor('dial yesterday'), isEmpty);
+ // A time alone is a search: what was worked on then.
+ search.search('yesterday');
+ await settle();
+ expect(asked.last, ('', DateTime(2026, 9, 25), DateTime(2026, 9, 26)));
+ },
+ );
+
+ test(
+ '"today" is the same window keystroke to keystroke, though now moves',
+ () async {
+ var clock = DateTime(2026, 9, 26, 14, 30);
+ final search = SessionContentSearch(
+ machines: () => ['m'],
+ debounce: Duration.zero,
+ now: () => clock = clock.add(const Duration(milliseconds: 7)),
+ ask: (_, words, when) async => words == 'dia'
+ ? [hit('a1', snippet: 'the ${_o}dial$_c scroll')]
+ : Completer<List<SessionContentHit>?>().future,
+ );
+ addTearDown(search.dispose);
+ search.search('today dia');
+ await settle();
+ search.search('today dial');
+ expect(search.hitsFor('today dial').keys, [phoneAgentId('m', 'a1')]);
+ // Read once per query and answer, however many rows ask.
+ expect(
+ identical(search.hitsFor('today dial'), search.hitsFor('today dial')),
+ isTrue,
+ );
+ expect(search.hitsFor('yesterday dial'), isEmpty);
+ },
+ );
+}
diff --git a/mobile/test/terminal_header_test.dart b/mobile/test/terminal_header_test.dart
index 4ab6fb464..264753b3f 100644
--- a/mobile/test/terminal_header_test.dart
+++ b/mobile/test/terminal_header_test.dart
@@ -41,54 +41,47 @@ void main() {
),
);
- testWidgets('two lines, and the state on the mark', (tester) async {
- await pumpHeader(tester, {
- 'name': 'api',
- 'project': {
- 'name': 'autonomous-harness',
- 'cwd': '/Users/dudu/Bitcoin_builder/Grid/autonomous-harness',
- 'branch': 'feat/mobile-ios-android',
- },
- });
+ testWidgets(
+ 'one line: the name, then the machine, and the state on the mark',
+ (tester) async {
+ await pumpHeader(tester, {
+ 'name': 'api',
+ 'project': {
+ 'name': 'autonomous-harness',
+ 'cwd': '/srv/autonomous-harness',
+ 'branch': 'feat/mobile-ios-android',
+ },
+ });
- expect(find.text('api'), findsOneWidget);
- // The desktop's order: the machine, the folder, the branch.
- final place = [
- for (final text in tester.widgetList<Text>(find.byType(Text))) text.data,
- ];
- expect(
- place,
- containsAllInOrder([
- 'MacBookPro2021.local',
- 'autonomous-harness',
- 'feat/mobile-ios-android',
- ]),
- );
- // No word for the state — the dot says it, and its tooltip.
- expect(find.text('Live'), findsNothing);
- expect(find.byType(StatusDot), findsOneWidget);
- expect(find.byTooltip('Live'), findsOneWidget);
- });
+ expect(find.text('api'), findsOneWidget);
+ expect(find.text('MacBookPro2021.local'), findsOneWidget);
+ // The folder and branch are in the ⋮ sheet: the header floats over the
+ // terminal, and every line it takes is a line of output.
+ expect(find.text('autonomous-harness'), findsNothing);
+ expect(find.text('feat/mobile-ios-android'), findsNothing);
+ // No word for the state — the dot says it, and its tooltip.
+ expect(find.text('Live'), findsNothing);
+ expect(find.byType(StatusDot), findsOneWidget);
+ expect(find.byTooltip('Live'), findsOneWidget);
+ },
+ );
- testWidgets('reads as the desktop\'s pane header does', (tester) async {
+ testWidgets('the name is the session\'s title when it has one', (
+ tester,
+ ) async {
await pumpHeader(tester, {
'name': 'harness-3',
'title': 'Worktree and branches organization',
'project': {
'name': 'autonomous-harness',
- 'cwd': '/Users/dudu/.harness/worktrees/worktree-35ab',
- 'root': '/Users/dudu/.harness/worktrees/worktree-35ab',
+ 'cwd': '/srv/worktrees/worktree-35ab',
+ 'root': '/srv/worktrees/worktree-35ab',
'branch': 'harness/3',
'branchPending': true,
},
});
- // The session's title over the CLI's made-up name, the repository over the worktree's
- // folder, and no branch while Harness's placeholder waits for the session's name.
expect(find.text('Worktree and branches organization'), findsOneWidget);
- expect(find.text('autonomous-harness'), findsOneWidget);
- expect(find.text('worktree-35ab'), findsNothing);
- expect(find.text('harness/3'), findsNothing);
});
group('the second line shares out only what overruns it', () {
diff --git a/mobile/test/terminal_key_bar_test.dart b/mobile/test/terminal_key_bar_test.dart
index 1d37c196e..36380da32 100644
--- a/mobile/test/terminal_key_bar_test.dart
+++ b/mobile/test/terminal_key_bar_test.dart
@@ -54,6 +54,39 @@ void main() {
expect(outbound, ['\x1b', '\x1b[D', '\x1b[A', '\x1b[B', '\x1b[C']);
});
+ testWidgets('^C sends interrupt at one tap', (tester) async {
+ await pumpBar(tester);
+ await tapKey(tester, 'Control C');
+ expect(outbound, ['\x03']);
+ });
+
+ testWidgets(
+ 'ctrl is the session\'s when it has one, so a typed letter can spend it',
+ (tester) async {
+ var armed = false;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: StatefulBuilder(
+ builder: (context, setState) => TerminalKeyBar(
+ terminal: terminal,
+ enabled: true,
+ onDismissKeyboard: () {},
+ ctrlArmed: armed,
+ onArmCtrl: (value) => setState(() => armed = value),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tapKey(tester, 'ctrl');
+ expect(armed, isTrue, reason: 'armed on the session, not the row alone');
+ await tapKey(tester, 'Up');
+ expect(armed, isFalse, reason: 'spent by the next key');
+ expect(outbound.single, contains('1;5A'));
+ },
+ );
+
testWidgets('tab reaches the pty and empties the keyboard buffer', (
tester,
) async {
diff --git a/mobile/test/terminal_page_header_fold_test.dart b/mobile/test/terminal_page_header_fold_test.dart
index 7a7be689c..a14aac515 100644
--- a/mobile/test/terminal_page_header_fold_test.dart
+++ b/mobile/test/terminal_page_header_fold_test.dart
@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/auth/auth_session.dart';
import 'package:harness_mobile/core/config.dart';
-import 'package:harness_mobile/phone/phone_search_field.dart';
+import 'package:harness_mobile/phone/tty_controls.dart';
import 'package:harness_mobile/phone/phone_search_results.dart';
import 'package:harness_mobile/phone/terminal_action_column.dart';
import 'package:harness_mobile/phone/terminal_header.dart';
@@ -117,7 +117,10 @@ void main() {
await tester.pump(const Duration(milliseconds: 100));
resizes.clear();
- await tester.tap(find.byKey(const ValueKey('terminal-search')));
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
await tester.pump();
// The search field's keyboard slides up, and the page shrinks above it.
tester.view.viewInsets = const FakeViewPadding(bottom: 900);
@@ -154,14 +157,17 @@ void main() {
expect(find.byType(TerminalActionColumn), findsOneWidget);
}
- await tester.tap(find.byKey(const ValueKey('terminal-search')));
+ await tester.dragFrom(
+ tester.getCenter(find.byType(TerminalPage).first) - const Offset(120, 0),
+ const Offset(300, 0),
+ );
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
- // The sheet opens on its tabs; a tap on its field is what starts a search
- // and brings the keyboard.
+ // Find opens on the recent agents; a tap on its field is what starts a
+ // search and brings the keyboard.
await tester.tap(
find.descendant(
- of: find.byType(SheetSearchField),
+ of: find.byType(TtyField),
matching: find.byType(TextField),
),
);
@@ -185,13 +191,12 @@ void main() {
// frame, through the fade AND after it, shows the terminal search opened
// over; releasing it with the fade let the falling inset raise its key bar.
//
- // The sheet has no chevron: it is flung shut from its grip, the one close
- // that leaves with the keyboard still up. The grip is the strip directly
- // above the field.
- final field = tester.getRect(find.byType(SheetSearchField));
+ // Find is flung shut to the left, the way it came in — the one close that
+ // leaves with the keyboard still up. From the list: the prompt keeps a
+ // sideways drag for moving its caret.
await tester.flingFrom(
- field.topCenter - const Offset(0, 8),
- const Offset(0, 300),
+ tester.getCenter(find.byType(PhoneSearchResults)),
+ const Offset(-300, 0),
2000,
);
await tester.pump();
@@ -204,7 +209,7 @@ void main() {
}
await tester.pump(const Duration(seconds: 1));
expect(find.byType(PhoneSearchResults), findsNothing);
- expect(find.byType(SheetSearchField), findsNothing);
+ expect(find.byType(TtyField), findsNothing);
expectUntouched();
expect(resizes, isEmpty);
});
diff --git a/mobile/test/touch_agent_test.dart b/mobile/test/touch_agent_test.dart
new file mode 100644
index 000000000..076154893
--- /dev/null
+++ b/mobile/test/touch_agent_test.dart
@@ -0,0 +1,89 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+/// A machine that records what it is asked.
+class _Conn extends WsConn {
+ _Conn(this.requests)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final List<(String, Map<String, dynamic>)> requests;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ requests.add((type, payload));
+ return {};
+ }
+}
+
+/// Opening an agent here tells the machine that owns it, so its `lastOpenedAt`
+/// — and the order every app sorts by — is the account's, not this phone's.
+void main() {
+ test('an agent opened here is reported to its machine, once', () async {
+ final requests = <(String, Map<String, dynamic>)>[];
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => _Conn(requests),
+ );
+ addTearDown(app.dispose);
+ const machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ );
+ app.machines = [machine];
+ app.machineStates['m'] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+
+ app.touchAgent('m', 'a');
+ // Opened again straight away: nothing new to say.
+ app.touchAgent('m', 'a');
+ await Future<void>.delayed(Duration.zero);
+
+ expect(requests, hasLength(1));
+ expect(requests.single.$1, 'agent_update');
+ expect(requests.single.$2, {'agentId': 'a', 'opened': true});
+ });
+
+ test('last use is the later of activity and the last open', () {
+ final activity = DateTime.utc(2026, 9, 26, 10);
+ final opened = DateTime.utc(2026, 9, 26, 11);
+ Agent agent({DateTime? updatedAt, DateTime? lastOpenedAt}) => Agent(
+ id: 'a',
+ name: 'a',
+ updatedAt: updatedAt,
+ lastOpenedAt: lastOpenedAt,
+ );
+ expect(agent(updatedAt: activity, lastOpenedAt: opened).lastUsedAt, opened);
+ expect(agent(updatedAt: opened, lastOpenedAt: activity).lastUsedAt, opened);
+ expect(agent(updatedAt: activity).lastUsedAt, activity);
+ expect(agent(lastOpenedAt: opened).lastUsedAt, opened);
+ expect(
+ Agent.fromJson({
+ 'id': 'a',
+ 'name': 'a',
+ 'lastOpenedAt': '2026-09-26T11:00:00.000Z',
+ }).lastOpenedAt,
+ opened,
+ );
+ });
+}
diff --git a/mobile/test/unlink_machine_test.dart b/mobile/test/unlink_machine_test.dart
index fb327afd3..f85d98646 100644
--- a/mobile/test/unlink_machine_test.dart
+++ b/mobile/test/unlink_machine_test.dart
@@ -18,6 +18,14 @@ class _Links implements PeerLinkClient {
String? displayName,
}) async => const CliLinkConnectResult(error: 'not used');
+ @override
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ }) async => const CliLinkConnectResult(error: 'not used');
+
@override
Future<CliLinkListResult> list() async =>
const CliLinkListResult(machines: []);
diff --git a/mobile/test/viewer/direct_auth_issuer_test.dart b/mobile/test/viewer/direct_auth_issuer_test.dart
index efa8dc6dd..a671005d5 100644
--- a/mobile/test/viewer/direct_auth_issuer_test.dart
+++ b/mobile/test/viewer/direct_auth_issuer_test.dart
@@ -69,6 +69,79 @@ void main() {
expect(account.sent, isEmpty);
});
+ test('a scanned QR signs in with Harness\'s own session, renewed and revoked at the backend', () async {
+ backend.replies['/api/auth/handoff/redeem'] = (
+ status: 200,
+ body: {
+ 'success': true,
+ 'data': {
+ 'token': 'hna_first',
+ 'refreshToken': 'hnr_1',
+ 'expiresIn': 3600,
+ 'autonomousEnv': 'prod',
+ },
+ },
+ );
+ backend.replies['/api/auth/revoke'] = (
+ status: 200,
+ body: {
+ 'success': true,
+ 'data': {'revoked': true},
+ },
+ );
+ await EmailCodeLogin(auth: auth)
+ .signInWithScan('hnh_code', label: 'iPhone');
+ expect(backend.sent.first.body, {'code': 'hnh_code', 'label': 'iPhone'});
+ expect(await session.issuer(), SessionIssuer.harness);
+ expect(await session.accessToken(), 'hna_first');
+
+ expect(await auth.accessToken(force: true), 'from-backend');
+ expect(backend.sent.last.path, '/api/auth/refresh');
+ expect(backend.sent.last.body['refreshToken'], 'hnr_1');
+ expect(account.sent, isEmpty);
+
+ await auth.signOut();
+ expect(backend.sent.last.path, '/api/auth/revoke');
+ expect(backend.sent.last.body, {'refreshToken': 'hnr_1'});
+ expect(await session.accessToken(), isNull);
+ });
+
+ test(
+ 'a spent QR code is the backend\'s own sentence, and no session',
+ () async {
+ backend.replies['/api/auth/handoff/redeem'] = (
+ status: 401,
+ body: {
+ 'success': false,
+ 'error': {
+ 'code': 'HANDOFF_INVALID',
+ 'message': 'That code has expired. Scan the new one.',
+ },
+ },
+ );
+ await expectLater(
+ EmailCodeLogin(auth: auth).signInWithScan('hnh_old', label: 'iPhone'),
+ throwsA(
+ isA<DirectAuthException>().having(
+ (e) => e.message,
+ 'message',
+ 'That code has expired. Scan the new one.',
+ ),
+ ),
+ );
+ expect(await session.accessToken(), isNull);
+ },
+ );
+
+ test('signing out offline still signs out', () async {
+ await auth.signIn(
+ const IssuedTokens(token: 'hna_t', refreshToken: 'hnr_r'),
+ issuer: SessionIssuer.harness,
+ );
+ await auth.signOut(); // no /api/auth/revoke reply: the network is down
+ expect(await session.accessToken(), isNull);
+ });
+
test('a session saved before issuers were recorded is an SSO one', () async {
final storage = MemoryKeyValueStore();
await storage.write('auth_access_token', 'old');
diff --git a/mobile/test_driver/journey_driver.dart b/mobile/test_driver/journey_driver.dart
new file mode 100644
index 000000000..e111e3f59
--- /dev/null
+++ b/mobile/test_driver/journey_driver.dart
@@ -0,0 +1,19 @@
+// 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_run_journey_test.dart`: writes each screenshot the app
+/// takes into `HARNESS_JOURNEY_OUT` (default `build/journey/`).
+Future<void> main() => integrationDriver(
+ onScreenshot: (name, bytes, [args]) async {
+ final root = Platform.environment['HARNESS_JOURNEY_OUT'] ?? 'build/journey';
+ final file = File('$root/$name.png');
+ await file.parent.create(recursive: true);
+ await file.writeAsBytes(bytes);
+ print('[journey] $name');
+ return true;
+ },
+);
diff --git a/mobile/test_driver/perf_driver.dart b/mobile/test_driver/perf_driver.dart
new file mode 100644
index 000000000..7db3b9988
--- /dev/null
+++ b/mobile/test_driver/perf_driver.dart
@@ -0,0 +1,78 @@
+// A command-line driver; printing is its interface.
+// ignore_for_file: avoid_print
+
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:integration_test/integration_test_driver.dart';
+
+/// Host side of `integration_test/perf_test.dart`: waits for the phone's
+/// results and writes them, never over an earlier run.
+///
+/// Where: `HARNESS_PERF_OUT` (relative to `mobile/`), by default
+/// `../docs/performance/2026-09-26-mobile-data`. Named
+/// `<HARNESS_PERF_LABEL>-<UTC time>.json`, the label `baseline` unless set —
+/// `after` for the redesign, say. A run with a failed scenario is written to
+/// `failed/` under the same directory: it is kept for review, but the
+/// summarizer does not pool it.
+Future<void> main() => integrationDriver(
+ timeout: const Duration(minutes: 25),
+ writeResponseOnFailure: true,
+ responseDataCallback: (data) async {
+ if (data == null) {
+ print('[perf] the phone reported no data');
+ return;
+ }
+ final env = Platform.environment;
+ final root = env['HARNESS_PERF_OUT'] ?? '../docs/performance/2026-09-26-mobile-data';
+ final label = env['HARNESS_PERF_LABEL'] ?? 'baseline';
+ final failed = data['success'] != true;
+ final directory = Directory(failed ? '$root/failed' : root);
+ await directory.create(recursive: true);
+ final stamp = DateTime.now()
+ .toUtc()
+ .toIso8601String()
+ .replaceAll(RegExp(r'[:\-]'), '')
+ .split('.')
+ .first;
+ var file = File('${directory.path}/$label-${stamp}Z.json');
+ for (var n = 2; file.existsSync(); n++) {
+ file = File('${directory.path}/$label-${stamp}Z-$n.json');
+ }
+ data['host'] = await _host();
+ await file.writeAsString(const JsonEncoder.withIndent(' ').convert(data));
+ print('[perf] wrote ${file.path}');
+ if (failed) print('[perf] FAILED scenarios: ${(data['failures'] as Map).keys}');
+ },
+);
+
+/// What built the run: the source revision, whether the app's sources had
+/// uncommitted edits, and the Flutter SDK. No paths or names from this Mac.
+Future<Map<String, Object?>> _host() async {
+ Future<String?> git(List<String> args) async {
+ try {
+ final result = await Process.run('git', args);
+ return result.exitCode == 0 ? (result.stdout as String).trim() : null;
+ } on ProcessException {
+ return null;
+ }
+ }
+
+ String? flutter;
+ final sdk = Platform.environment['FLUTTER_ROOT'];
+ if (sdk != null) {
+ final version = File('$sdk/bin/cache/flutter.version.json');
+ if (version.existsSync()) {
+ final json = jsonDecode(version.readAsStringSync()) as Map<String, dynamic>;
+ flutter = '${json['frameworkVersion']} (${json['frameworkRevision']}), '
+ 'Dart ${json['dartSdkVersion']}';
+ }
+ }
+ final dirty = await git(['status', '--porcelain', '--', 'lib', 'third_party']);
+ return {
+ 'revision': await git(['rev-parse', 'HEAD']),
+ 'appSourcesModified': dirty?.isNotEmpty,
+ 'flutter': flutter,
+ 'device': Platform.environment['HARNESS_PERF_DEVICE'],
+ };
+}