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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-02 1510: #2541 #2542 #2544 #2539 #2521 #2522 (#2547)
0xken15f7870372ba59
diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.tsindex a17e5a5a6..f1d482d6c 100644--- a/backend/integration/superTabInstructions.test.ts+++ b/backend/integration/superTabInstructions.test.ts@@ -12,7 +12,7 @@ import { SuperTabStore } from '../src/superTabs/store.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'import type { Command } from '../src/superTabs/commands.js'-import { appendRouting, instructionsHash } from '../src/superTabs/instructions.js'+import { appendRouting, FIRST_INSTRUCTIONS, instructionsHash } from '../src/superTabs/instructions.js'import { stableId } from '../src/superTabs/model.js'import { roleVersion } from '../src/superTabs/projects.js'import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'@@ -221,11 +221,12 @@ describe('reading the instructions', () => {const secret = (await run(tab, { type: 'project.create', name: 'Secret', visibility: 'private', brief: '' })).result.projectId as stringfor (const url of [doc(tab, secret), `${doc(tab, secret)}/revisions`, `${doc(tab, secret)}/revisions/1`]) expect((await get(peer, url)).statusCode).toBe(404)expect((await get(owner, doc(tab, secret))).statusCode).toBe(200)- // A project from before instructions, until the migration writes its document: the built-in template, revision 0.+ // A project from before instructions, until the migration writes its document: the built-in template, revision 0, with the+ // template's hash so a running daemon reads again when the template moves (agent-context design, section 3).const head = await db.swarmHead.findFirstOrThrow({ where: { tabId: tab } })const data = head.data as { projects: Array<Record<string, unknown>> }await db.swarmHead.update({ where: { id: head.id }, data: { data: { ...data, projects: data.projects.map(({ instructionsRevision: _r, instructionsHash: _h, ...p }) => p) } as never } })- expect((await get(owner, doc(tab))).json().data).toMatchObject({ revision: 0, hash: null, text: INSTRUCTIONS_TEMPLATE, template: true, notes: [] })+ expect((await get(owner, doc(tab))).json().data).toMatchObject({ revision: 0, hash: FIRST_INSTRUCTIONS.instructionsHash, text: INSTRUCTIONS_TEMPLATE, template: true, notes: [] })})it('reads nothing to a Buddy whose person lost the private project, as every other Buddy read (review of phase 2)', async () => {diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex bb69b712d..b783a0a83 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -773,15 +773,18 @@ describe('a review task while its build is back with the Engineer', () => {expect(await f.task()).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 5 minutes' } })})- it('still loses it to time once its build is cancelled after its verdict', async () => {+ // Task steps design (#2511): a review is a step of its build, and a task that ends cancels its open steps with its reason,+ // so a cancelled build no longer leaves its review to be lost by time later.+ it('is cancelled with its build, and is never lost by time after', async () => {const f = await reviewing()await f.requestChanges()await f.minutes(10)await f.execute({ type: 'work.cancel', conversationId: f.group, assignmentId: f.assignmentId, reason: 'Not needed' })+ expect(await f.task()).toMatchObject({ status: 'cancelled', result: 'Ship the parser was cancelled.' })await f.minutes(20, { heartbeats: false })- expect(await f.task()).toMatchObject({ status: 'working' })await f.reviewerReport(f.waitFrom + 30 * MINUTE + 1)- expect(await f.task()).toMatchObject({ status: 'lost', lost: { reason: 'no progress for 30 minutes' } })+ expect(await f.task()).toMatchObject({ status: 'cancelled', result: 'Ship the parser was cancelled.' })+ expect(await f.lost()).toEqual([])})})diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex 53ab2d4e7..c90403929 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -128,8 +128,8 @@ describe('first load (design 4.3)', () => {const { status, body } = await get(`/api/super-tabs/${s.tabId}/parts`, peer)expect(status).toBe(200)expect(Object.keys(body.data).sort()).toEqual(['agents', 'cursor', 'derived', 'epoch', 'format', 'groups', 'head', 'lastChangedAt',- 'machines', 'members', 'progress', 'serverTime', 'starts', 'tabId'].sort())- expect(body.data).toMatchObject({ format: 2, tabId: s.tabId, serverTime: NOW, epoch: 1, lastChangedAt: MIGRATED,+ 'machines', 'members', 'progress', 'serverTime', 'starts', 'steps', 'tabId'].sort())+ expect(body.data).toMatchObject({ format: 2, tabId: s.tabId, serverTime: NOW, epoch: 1, lastChangedAt: MIGRATED, steps: true,head: { key: 'head', version: R, changedAt: MIGRATED, data: { id: s.tabId, name: 'Pilot' } } })expect(JSON.parse(Buffer.from(body.data.cursor, 'base64url').toString())).toEqual({ v: 2, t: NOW - 30_000, e: 1 })expect(keys(body.data.members)).toEqual([owner.sub, peer.sub, outsider.sub])diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex 5b2579502..0afd8f264 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -291,19 +291,17 @@ describe('a review nobody reviews', () => {return { ...f, reviewed, builder, work, ready, reviews, review, closeLines, isArchived }}- it('closes 30 minutes after its last message once every pull request of the work it reviews is merged, with one line saying why', async () => {+ // Task steps design (#2511): a review is a step of the work it reviews and archives with that task, never on its own clock,+ // so a review nobody holds stays open while its task does, merged pull requests or not.+ it('is not closed on its own clock once every pull request of the work it reviews is merged: it stays with its task', async () => {const f = await waiting()expect((f.review.data as { assignment: unknown }).assignment).toBeNull()- expect(f.review.workFinished).toBe(true)- f.clock.now += 29 * MINUTE+ expect(f.review.workFinished).toBe(false)+ f.clock.now += 40 * MINUTEawait archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)expect(await f.isArchived()).toBe(false)- f.clock.now += MINUTE- await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)- expect(await f.isArchived()).toBe(true)- expect(await f.closeLines()).toEqual([expect.objectContaining({ recipientIds: [], author: expect.objectContaining({ id: f.lead }),- text: 'Closed: #9 merged; no Swarm review is needed now.' })])- // The work it reviews is untouched: its Builder still waits, for the Lead to settle.+ expect(await f.closeLines()).toEqual([])+ // The work it reviews is untouched too: its Builder still waits, for the Lead to settle.expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })).archived).toBe(false)})@@ -340,25 +338,29 @@ describe('a review nobody reviews', () => {expect(await f.isArchived()).toBe(true)})- // Review of #2322: a Ready committed inside the close's write linked a new pull request to the work; the close then- // archived its review on the older ones, and the work was left with no review, silently (the 10-28 failure).- it('stays open when a Ready for review with a new pull request commits during its close, so the work keeps a review', async () => {+ // Review of #2322 (a Ready committed inside a review's close left the work with no review): a review step no longer closes+ // on its own clock, so a Ready with a new pull request after the older ones merged still finds the work's review open.+ it('stays open when a Ready for review with a new pull request comes after the older ones merged, so the work keeps a review', async () => {const f = await waiting()- let during: (() => Promise<unknown>) | null = () => f.ready('Ready: yes, revision fff. https://github.com/example/parser/pull/11')- // Paused at the close's first write, which closes the decisions still waiting there.- const hooked = db.$extends({ query: { superTabDecision: { async updateMany({ args, query }) {- if (during && (args.where as { conversationId?: string } | undefined)?.conversationId === f.review.key) { const run = during; during = null; await run() }- return query(args)- } } } })- const closing = new SuperTabStore(hooked as unknown as PrismaClient, () => f.clock.now)f.clock.now += 40 * MINUTE- await archiveFinishedGroups(db, closing, github({ [PR]: 'merged' }), f.clock.now)- expect(during).toBeNull()+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)+ await f.ready('Ready: yes, revision fff. https://github.com/example/parser/pull/11')+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged', 'https://github.com/example/parser/pull/11': 'merged' }), f.clock.now)expect(await f.isArchived()).toBe(false)expect(await f.closeLines()).toEqual([])expect((await f.reviews()).filter(row => !row.archived)).toHaveLength(1)})+ it('archives with its task once the task ends and its pull requests are merged, the task\'s pass closing it in the same write', async () => {+ const f = await waiting()+ await f.execute({ type: 'work.cancel', conversationId: f.reviewed, assignmentId: f.work, reason: 'Landed outside the Swarm' }, host, f.lead)+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)+ expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })).archived).toBe(true)+ expect(await f.isArchived()).toBe(true)+ })+it('is cancelled by its coordinator with "current": it archives with the reason, and what waited there for the coordinator ends', async () => {const f = await waiting()await f.execute({ type: 'message.send', conversationId: f.review.key, text: 'No reviewer is free yet.', replyTo: null, recipientIds: [f.lead] }, host, f.builder)diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 4de6416ec..3c36154c1 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -2872,6 +2872,19 @@ describe('machine.remove', () => {requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as never]}+ // The phone and the web offer Pause/Resume only to the person who lent the machine; the server holds the same line.+ it('lets only the contributor pause or resume a machine', () => {+ const f = fixture()+ f.invite()+ contribute(f, 'owner')+ expect(() => f.run({ type: 'machine.pause', machineId: 'host', paused: true }, peer)).toThrow(expect.objectContaining({ code: 'OWNER_REQUIRED', status: 403 }))+ expect(f.state.machines![0]!.paused).toBe(false)+ f.run({ type: 'machine.pause', machineId: 'host', paused: true })+ expect(f.state.machines![0]!.paused).toBe(true)+ expect(() => f.run({ type: 'machine.pause', machineId: 'host', paused: false }, peer)).toThrow(expect.objectContaining({ code: 'OWNER_REQUIRED' }))+ expect(f.state.machines![0]!.paused).toBe(true)+ })+it('takes the machine out with the Swarm\'s agents on it, and tells each group whose task needs a new worker', () => {const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)f.state.agents.find(a => a.id === lead)!.machineId = 'elsewhere'diff --git a/cli/src/lib/subscriptionRelay.spec.ts b/cli/src/lib/subscriptionRelay.spec.tsindex ff5e136a2..6c4e9d6af 100644--- a/cli/src/lib/subscriptionRelay.spec.ts+++ b/cli/src/lib/subscriptionRelay.spec.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from 'node:http'import type { AddressInfo } from 'node:net'import type { OwnerCredential, OwnerSubscriptions, SubscriptionProvider } from './ownerSubscriptions.js'import {@@ -206,6 +206,188 @@ describe('Codex', () => {})})+/** A request sent with its path exactly as given, which `fetch` would normalize first. */+function raw(method: string, path: string, token: string): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ const req = request({ host: '127.0.0.1', port: relay.port, method, path, headers: { authorization: `Bearer ${token}` } }, (res) => {+ const chunks: Buffer[] = []+ res.on('data', (chunk: Buffer) => chunks.push(chunk))+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString() }))+ })+ req.on('error', reject)+ req.end(method === 'GET' || method === 'HEAD' ? undefined : '{}')+ })+}++describe('the engine calls, and nothing else', () => {+ const both = () => owner({ claude: claude(OWNER_CLAUDE), codex: codex(OWNER_CODEX) }).subscriptions++ it('forwards each call Claude Code and Codex make', async () => {+ await start(ok, both())+ const token = relay.mintToken('[email protected]')+ const calls: Array<[string, string, string]> = [+ ['POST', '/claude/v1/messages?beta=true', '/v1/messages?beta=true'],+ ['POST', '/claude/v1/messages/count_tokens?beta=true', '/v1/messages/count_tokens?beta=true'],+ ['GET', '/claude/v1/models', '/v1/models'],+ ['POST', '/codex/responses', '/backend-api/codex/responses'],+ ['GET', '/codex/models?client_version=0.165.0', '/backend-api/codex/models?client_version=0.165.0'],+ ]+ for (const [method, path] of calls) expect((await raw(method, path, token)).status, `${method} ${path}`).toBe(200)+ expect(upstream.seen.map((s) => `${s.method} ${s.url}`)).toEqual(calls.map(([method, , sent]) => `${method} ${sent}`))+ })++ it('refuses an account endpoint, whatever the method, and never reaches the vendor', async () => {+ await start(ok, both())+ const token = relay.mintToken('[email protected]')+ for (const [method, path] of [+ ['POST', '/claude/v1/organizations/api_keys'],+ ['GET', '/claude/api/oauth/profile'],+ ['POST', '/claude/api/oauth/claude_cli/create_api_key'],+ ['GET', '/claude/v1/files'],+ ['POST', '/claude/v1/messages/batches'],+ ['GET', '/codex/accounts/check'],+ ['GET', '/codex/wham/usage'],+ ['POST', '/codex/responses/compact/../../../accounts'],+ ['GET', '/claude/'],+ ['GET', '/codex'],+ ] as const) {+ const answer = await raw(method, path, token)+ expect(answer.status, `${method} ${path}`).toBe(404)+ expect(answer.body).toContain('harness_relay_error')+ }+ expect(upstream.seen).toEqual([])+ })++ it('refuses encoded separators, dot segments and doubled slashes, as sent', async () => {+ await start(ok, both())+ const token = relay.mintToken('[email protected]')+ for (const path of [+ '/claude/v1/messages/..%2f..%2fv1%2forganizations',+ '/claude/v1/messages%2fcount_tokens',+ '/claude/v1/%2e%2e/api/oauth/profile',+ '/claude/v1/messages%2F..%2F..%2Fapi',+ '/claude/v1/messages%5c..%5c..%5capi',+ '/claude/v1/messages\\..\\api',+ '/claude/v1/./messages',+ '/claude/v1/x/../messages',+ '/claude//v1/messages',+ '/claude/v1/messages/',+ '/claude/v1/Messages',+ '/codex/responses/..%2f..%2faccounts',+ '/codex/%72esponses',+ 'http://chatgpt.com/codex/responses',+ ]) expect((await raw('POST', path, token)).status, path).toBe(404)+ expect(upstream.seen).toEqual([])+ })++ it('refuses another method on an engine path', async () => {+ await start(ok, both())+ const token = relay.mintToken('[email protected]')+ for (const [method, path] of [+ ['GET', '/claude/v1/messages'],+ ['DELETE', '/claude/v1/messages'],+ ['PUT', '/claude/v1/messages/count_tokens'],+ ['POST', '/claude/v1/models'],+ ['GET', '/codex/responses'],+ ['DELETE', '/codex/models'],+ ['HEAD', '/codex/models'],+ ['OPTIONS', '/claude/v1/messages'],+ ] as const) expect((await raw(method, path, token)).status, `${method} ${path}`).toBe(405)+ expect(upstream.seen).toEqual([])+ })++ it('tells the owner what was refused, without the guest\'s path or token', async () => {+ await start(ok, both())+ const token = relay.mintToken('[email protected]')+ await raw('POST', '/claude/v1/organizations/secret-path', token)+ await raw('GET', '/claude/v1/messages', token)+ await raw('POST', '/claude/v1/organizations/secret-path', 'not-a-token')+ expect(lines).toEqual([+ expect.stringMatching(/^claude POST → 404 · not an engine call · guest [0-9a-f]{8}$/),+ expect.stringMatching(/^claude GET \/claude\/v1\/messages → 405 · not an engine call · guest [0-9a-f]{8}$/),+ 'claude POST → 401 · no guest',+ ])+ for (const line of lines) expect(line).not.toContain('secret-path')+ })+})++describe('a revoked guest', () => {+ it('loses the answer it is streaming', async () => {+ let started!: () => void+ const streaming = new Promise<void>((resolve) => { started = resolve })+ await start(async (req, res) => {+ if (req.method === 'GET') return ok(req, res)+ res.writeHead(200, { 'content-type': 'text/event-stream' })+ res.write('event: message_start\ndata: {}\n\n')+ started()+ // The vendor keeps the stream open; only the revoke can end it.+ await new Promise<void>((resolve) => res.on('close', () => resolve()))+ }, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const token = relay.mintToken('[email protected]')+ const other = relay.mintToken('[email protected]')+ const response = await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ const reader = response.body!.getReader()+ expect(new TextDecoder().decode((await reader.read()).value)).toContain('message_start')+ await streaming+ relay.revoke('[email protected]')+ const rest = await (async () => { try { for (;;) if ((await reader.read()).done) return 'ended' } catch { return 'cut' } })()+ // Cut, not a clean end: the guest cannot mistake a revoked answer for a whole one.+ expect(rest).toBe('cut')+ // Another guest is untouched.+ expect((await raw('GET', '/claude/v1/models', other)).status).toBe(200)+ })++ it('gets 401, and nothing is sent, when revoked while its request waits on the owner\'s sign-in', async () => {+ let signIn!: (credential: OwnerCredential) => void+ let asked!: () => void+ const reading = new Promise<void>((resolve) => { asked = resolve })+ const subscriptions: OwnerSubscriptions = {+ read: () => { asked(); return new Promise((resolve) => { signIn = resolve }) },+ refresh: async () => null,+ }+ await start(ok, subscriptions)+ const token = relay.mintToken('[email protected]')+ const pending = fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ await reading+ relay.revoke('[email protected]')+ signIn(claude(OWNER_CLAUDE))+ const answer = await pending+ expect(answer.status).toBe(401)+ expect(upstream.seen).toEqual([])+ })+ it('gets 401, not a vendor error, when revoked while the vendor has not answered yet', async () => {+ let asked!: () => void+ const waiting = new Promise<void>((resolve) => { asked = resolve })+ await start(async (_req, res) => {+ asked()+ await new Promise<void>((resolve) => res.on('close', () => resolve()))+ }, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)+ const token = relay.mintToken('[email protected]')+ const pending = fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ await waiting+ relay.revoke('[email protected]')+ expect((await pending).status).toBe(401)+ })++ it('is not retried with a fresh sign-in when revoked during the refresh after a 401', async () => {+ let refreshed!: (credential: OwnerCredential) => void+ let asked!: () => void+ const refreshing = new Promise<void>((resolve) => { asked = resolve })+ const subscriptions: OwnerSubscriptions = {+ read: async () => claude(OWNER_CLAUDE),+ refresh: () => { asked(); return new Promise((resolve) => { refreshed = resolve }) },+ }+ await start((_req, res) => { res.writeHead(401, { 'content-type': 'application/json' }); res.end('{}') }, subscriptions)+ const token = relay.mintToken('[email protected]')+ const pending = fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })+ await refreshing+ relay.revoke('[email protected]')+ refreshed(claude(OWNER_CLAUDE_FRESH))+ expect((await pending).status).toBe(401)+ expect(upstream.seen.map((s) => s.headers.authorization)).toEqual([`Bearer ${OWNER_CLAUDE}`])+ })+})+describe('secrets', () => {it('never put a token in a log line or in an error a guest sees', async () => {const o = owner({ claude: claude(OWNER_CLAUDE) })diff --git a/cli/src/lib/subscriptionRelay.ts b/cli/src/lib/subscriptionRelay.tsindex 49a2e46e2..2f18257c9 100644--- a/cli/src/lib/subscriptionRelay.ts+++ b/cli/src/lib/subscriptionRelay.ts@@ -6,9 +6,11 @@* - Loopback only (127.0.0.1, a random port). Every request carries a **guest token** minted here,* as `Authorization: Bearer` (what Claude Code sends for `ANTHROPIC_AUTH_TOKEN` and Codex for a* provider's `env_key`) or `x-api-key`. Tokens are random, held in memory, compared in constant- * time, and revoked per guest the moment sharing with them ends.+ * time, and revoked per guest the moment sharing with them ends; a revoke also cuts what that guest has in flight.* - `/claude/*` goes to the Anthropic API with the owner's OAuth bearer and the OAuth beta.* `/codex/*` goes to the ChatGPT Codex backend with the owner's access token and account id.+ * - Only the engines' own calls go through (`ENGINE_ROUTES`), matched on the path exactly as sent: an account+ * endpoint, another method or an encoded separator never reaches the vendor with the owner's sign-in.* - Bodies stream back as they come (SSE). An expired token is refreshed before it is spent; an* upstream 401 is refreshed and retried once (`ownerSubscriptions.ts`).*@@ -43,6 +45,15 @@ export const CLAUDE_OAUTH_BETA = 'oauth-2025-04-20'export const OWNER_CODEX_PROVIDER = 'harness_owner'export const RELAY_TOKEN_VAR = 'HARNESS_RELAY_TOKEN'+/**+ * The calls Claude Code (2.1.312) and Codex (0.165, `wire_api="responses"`, plus `team/relay.ts` reading the owner's model+ * list) make through the relay, and the one method each. Paths are after `/claude` or `/codex`.+ */+const ENGINE_ROUTES: Record<SubscriptionProvider, ReadonlyMap<string, string>> = {+ claude: new Map([['/v1/messages', 'POST'], ['/v1/messages/count_tokens', 'POST'], ['/v1/models', 'GET']]),+ codex: new Map([['/responses', 'POST'], ['/models', 'GET']]),+}+/** A request body this large is not a model request. */const MAX_BODY_BYTES = 32 * 1024 * 1024@@ -78,6 +89,8 @@ export async function startSubscriptionRelay(deps: SubscriptionRelayDeps): Promi// sha256(token) -> guest. Keyed by the digest so the secret itself is never a map key, and the// match is confirmed with timingSafeEqual on the digests.const tokens = new Map<string, { guest: string; digest: Buffer }>()+ // guest -> the requests it has open, so a revoke cuts them too.+ const inFlight = new Map<string, Set<AbortController>>()const guestFor = (presented: string | null): string | null => {if (!presented) return null@@ -95,50 +108,83 @@ export async function startSubscriptionRelay(deps: SubscriptionRelayDeps): Promi})async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {- const url = new URL(req.url ?? '/', 'http://relay')- const [, first, ...rest] = url.pathname.split('/')- const provider: SubscriptionProvider | null = first === 'claude' || first === 'codex' ? first : null+ // The path exactly as sent: `new URL` would resolve `..` and `%2e` first, and leave `%2f` for the vendor to decode.+ const raw = req.url ?? '/'+ const queryAt = raw.indexOf('?')+ const path = queryAt < 0 ? raw : raw.slice(0, queryAt)+ const search = queryAt < 0 ? '' : raw.slice(queryAt)+ const first = path.split('/')[1]+ const provider: SubscriptionProvider | null = path.startsWith('/') && (first === 'claude' || first === 'codex') ? first : nullif (!provider) return fail(res, 404, 'Unknown relay route.')+ const route = path.slice(provider.length + 1)+ const method = ENGINE_ROUTES[provider].get(route)+ // Only an engine path is logged: any other is the guest's own text.+ const shown = method ? `${req.method} /${provider}${route}` : `${req.method}`const guest = guestFor(presentedToken(req))if (!guest) {- deps.log?.(`${provider} ${req.method} ${url.pathname} → 401 · no guest`)+ deps.log?.(`${provider} ${shown} → 401 · no guest`)return fail(res, 401, 'Not a valid guest token for this relay.')}+ if (method !== req.method) {+ deps.log?.(`${provider} ${shown} → ${method ? 405 : 404} · not an engine call · guest ${fingerprint(guest)}`)+ return fail(res, method ? 405 : 404, 'Not a call this relay forwards.')+ }++ const abort = new AbortController()+ const open = inFlight.get(guest) ?? new Set<AbortController>()+ inFlight.set(guest, open.add(abort))+ res.on('close', () => {+ if (!res.writableFinished) abort.abort()+ open.delete(abort)+ if (!open.size && inFlight.get(guest) === open) inFlight.delete(guest)+ })+ // Revoked (or gone) while this request waited: nothing more is spent for it, and a stream already started is cut.+ const revoked = () => {+ if (!abort.signal.aborted) return false+ if (res.headersSent) res.destroy()+ else fail(res, 401, 'Not a valid guest token for this relay.')+ return true+ }const body = await readBody(req)if (body === null) return fail(res, 413, 'Request too large.')- const target = `${upstream[provider].replace(/\/$/, '')}/${rest.join('/')}${url.search}`+ if (revoked()) return+ const target = `${upstream[provider].replace(/\/$/, '')}${route}${search}`let credential = await deps.owner.read(provider)if (credential && expired(credential, now())) credential = await deps.owner.refresh(provider, credential)+ if (revoked()) returnif (!credential) {// Said in the owner's log too: a guest's harness retrying this is the owner's sign-in to fix.- deps.log?.(`${provider} ${req.method} ${url.pathname} → 503 · owner not signed in · guest ${fingerprint(guest)}`)+ deps.log?.(`${provider} ${shown} → 503 · owner not signed in · guest ${fingerprint(guest)}`)return fail(res, 503, provider === 'claude'? 'The owner of this computer is not signed in to Claude.': 'The owner of this computer is not signed in to ChatGPT.')}- const abort = new AbortController()- res.on('close', () => { if (!res.writableFinished) abort.abort() })const send = (spend: OwnerCredential): Promise<Response> => fetchImpl(target, {- method: req.method ?? 'GET',+ method,headers: upstreamHeaders(provider, req.headers, spend),- body: body.length > 0 && req.method !== 'GET' && req.method !== 'HEAD' ? new Uint8Array(body) : undefined,+ body: body.length > 0 && method !== 'GET' ? new Uint8Array(body) : undefined,signal: abort.signal,})- let response = await send(credential)- if (response.status === 401) {- // Once: the owner's CLI may have rotated the token, or it lapsed early.- const fresh = await deps.owner.refresh(provider, credential)- if (fresh && fresh.accessToken !== credential.accessToken) {- await response.body?.cancel().catch(() => {})- response = await send(fresh)+ try {+ let response = await send(credential)+ if (response.status === 401) {+ // Once: the owner's CLI may have rotated the token, or it lapsed early.+ const fresh = await deps.owner.refresh(provider, credential)+ if (fresh && fresh.accessToken !== credential.accessToken) {+ await response.body?.cancel().catch(() => {})+ if (revoked()) return+ response = await send(fresh)+ }}+ deps.log?.(`${provider} ${shown} → ${response.status} · guest ${fingerprint(guest)}`)+ await pipe(response, res)+ } catch (error) {+ if (!revoked()) throw error}- deps.log?.(`${provider} ${req.method} ${url.pathname} → ${response.status} · guest ${fingerprint(guest)}`)- await pipe(response, res)}await new Promise<void>((resolve, reject) => {@@ -159,6 +205,8 @@ export async function startSubscriptionRelay(deps: SubscriptionRelayDeps): Promirevoke(guestEmail) {const guest = guestEmail.toLowerCase()for (const [key, entry] of tokens) if (entry.guest === guest) tokens.delete(key)+ for (const abort of inFlight.get(guest) ?? []) abort.abort()+ inFlight.delete(guest)},close: () => new Promise<void>((resolve) => {server.closeAllConnections?.()@@ -223,19 +271,19 @@ async function pipe(response: Response, res: ServerResponse): Promise<void> {res.flushHeaders()if (!response.body) { res.end(); return }const reader = response.body.getReader()- try {- for (;;) {- const { done, value } = await reader.read()- if (done) break- if (!res.write(value)) await new Promise((resolve) => res.once('drain', resolve))- }- } finally {- res.end()+ for (;;) {+ // A stream that fails (the vendor dropped it, or the guest was revoked) is cut by the caller, not ended cleanly:+ // a guest must not take a partial answer for a whole one.+ const { done, value } = await reader.read()+ if (done) break+ if (!res.write(value)) await new Promise((resolve) => res.once('drain', resolve))}+ res.end()}+/** A refusal also closes the connection: a refused request's body is left unread, so the socket cannot be reused. */function fail(res: ServerResponse, status: number, message: string): void {- res.writeHead(status, { 'content-type': 'application/json' })+ res.writeHead(status, { 'content-type': 'application/json', connection: 'close' })res.end(JSON.stringify({ type: 'error', error: { type: 'harness_relay_error', message } }))}diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex a20103a57..90eb52461 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -1,15 +1,17 @@+import { randomUUID } from 'node:crypto'import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { delimiter, join } from 'node:path'+import { promisify } from 'node:util'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ExecFileException } from 'node:child_process'-import { TmuxBackend, clearEnvArgs, serverVariables, unsetServerEnvArgs } from './tmuxBackend.js'+import { execFile, type ExecFileException } from 'node:child_process'+import { TmuxBackend, clearEnvArgs, serverVariables, tmuxScript, tmuxWord, unsetServerEnvArgs } from './tmuxBackend.js'import { clearPaneRemainOnExit, forgetTmuxServer } from './tmux.js'import { tmuxControlGate } from './tmuxControlGate.js'-import { assumeTmuxVersion, resetTmuxVersionCache } from './tmuxVersion.js'+import { assumeTmuxVersion, resetTmuxVersionCache, tmuxFeatures } from './tmuxVersion.js'import { isHarnessdVariable } from './harnessdEnv.js'import { resolveBinaryOnPath } from './binaryOnPath.js'-import { isolatedTmux } from '../testing/isolatedTmux.js'+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'import { DEFAULT_HOST_THEME } from './hostTheme.js'/**@@ -37,7 +39,8 @@ vi.mock('./patientExec.js', async (importOriginal) => {}})}- return { ...actual, patientExec }+ // The same for a list given on stdin (`runScript`), which arms the deadline itself.+ return { ...actual, patientExec, patientDeadline: () => () => {} }})/** Until no tmux or `ps` call is running, the ones a scan left going in the background included. */@@ -383,6 +386,11 @@ exit 1expect(created.state).not.toBe('succeeded')if (created.state === 'succeeded') returnexpect(created.reason).toBe('tmux is unavailable')+ // The same with variables, whose list goes on stdin: a pipe to no process is not a throw.+ expect(await new TmuxBackend().create({ label: 'harness-test', env: { K: 'v' } }))+ .toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'tmux is unavailable' })+ expect(await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%9' }, { env: { K: 'v' }, command: ['claude'] }))+ .toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'tmux is unavailable' })})it('re-arms remain-on-exit on an already-live pane for holdOpen', async () => {@@ -520,19 +528,8 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"'display-message -t %7 -- Build status: Ready; touch /tmp/must-not-run',)})- it('hands the session its own environment, before the command it launches', async () => {- const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-env-'))- dirs.push(dir)- const calls = join(dir, 'calls')- const tmux = join(dir, 'tmux')- writeFileSync(tmux, `#!/bin/sh-printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"-printf '%%42\\n'-`)- chmodSync(tmux, 0o700)- process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`- process.env.TMUX_BACKEND_CALLS = calls-+ it('hands the session its own environment, before the command it launches, with no value on a command line', async () => {+ const tmux = scriptTmux()const created = await new TmuxBackend(undefined, () => 'daemon-a').create({cwd: '/tmp/work',label: 'harness-test',@@ -542,42 +539,85 @@ printf '%%42\\n'command: ['/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude'],})- expect(created.state).toBe('succeeded')+ expect(created).toEqual({ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%42' } })+ // Audit M2: tmux's own command line names no value. A server it starts keeps it as its title, which+ // every account on the machine reads; the list goes on stdin.+ expect(tmux.calls()[0]).toBe('start-server ; source-file -')+ expect(tmux.calls().join('\n')).not.toContain('gridkey-abc123')// Order is load-bearing: everything after the first non-flag argument is the session's// shell-command, so an `-e` placed after `command` would be handed to the engine instead of tmux.- expect(readFileSync(calls, 'utf8').trim().split('\n')[0]).toBe(- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'- + ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'- + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -p remain-on-exit on'- + ' ; set-option destroy-unattached off ; set-option -p window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',- )+ expect(tmux.stdin()).toBe(tmuxScript([+ 'new-session', '-d', '-P', '-F', '#{pane_id}', '-c', '/tmp/work', '-s', 'harness-test',+ '-e', 'ANTHROPIC_BASE_URL=https://relay.example/relay', '-e', 'ANTHROPIC_AUTH_TOKEN=gridkey-abc123',+ '/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude',+ // Each option names the new session: from `source-file`, an untargeted one went to another session's pane.+ ';', 'set-option', '-p', '-t', '=harness-test:', 'remain-on-exit', 'on', ';', 'set-option', '-t', '=harness-test:', 'destroy-unattached', 'off',+ ';', 'set-option', '-p', '-t', '=harness-test:', 'window-style', 'bg=#181818,fg=#f5f5f5',+ ';', 'set-option', '-p', '-t', '=harness-test:', '@harness_daemon', 'daemon-a',+ ]))+ })++ it.each([+ ['no name', undefined],+ ['a name tmux would read as a window', 'harness:test'],+ ['a name tmux would read as a pane', 'harness.test'],+ ])('refuses a create with variables and %s, asking tmux nothing, rather than set options on a pane it cannot name', async (_, label) => {+ const tmux = scriptTmux()+ const created = await new TmuxBackend().create({ label, env: { K: 'v' }, command: ['claude'] })+ expect(created).toMatchObject({ state: 'failed', dispatch: 'not_started' })+ expect(tmux.calls()).toEqual([])+ })++ it('takes the pane id from the first line, before the ~/.tmux.conf errors a server it started prints on stdin', async () => {+ scriptTmux(`printf '%%7\\n/home/someone/.tmux.conf:1: invalid option: bogus\\n'`)+ expect(await new TmuxBackend().create({ label: 'harness-test', env: { K: 'v' }, command: ['claude'] }))+ .toEqual({ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%7' } })+ })++ it('keeps a create with no variables on the command line it always had', async () => {+ const tmux = scriptTmux()+ await new TmuxBackend(undefined, () => 'daemon-a').create({ label: 'harness-test', command: ['claude'] })+ expect(tmux.calls()[0]).toBe('new-session -d -P -F #{pane_id} -s harness-test claude ; set-option -p remain-on-exit on'+ + ' ; set-option destroy-unattached off ; set-option -p window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a')+ expect(tmux.stdin()).toBe('')})- it('respawns a pane in place with a new environment, keeping the pane id', async () => {- const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-respawn-'))- dirs.push(dir)- const calls = join(dir, 'calls')- const tmux = join(dir, 'tmux')- writeFileSync(tmux, `#!/bin/sh-printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"-`)- chmodSync(tmux, 0o700)- process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`- process.env.TMUX_BACKEND_CALLS = calls+ it('says why tmux refused a create given on stdin', async () => {+ scriptTmux(`printf 'duplicate session: harness-test\\n' >&2; exit 1`)+ const refused = await new TmuxBackend().create({ label: 'harness-test', env: { K: 'v' }, command: ['claude'] })+ expect(refused).toMatchObject({ state: 'unknown', dispatch: 'possibly_executed', reason: 'tmux session creation did not complete: duplicate session: harness-test' })+ })++ it('respawns a pane in place with a new environment, keeping the pane id, with no value on a command line', async () => {+ const tmux = scriptTmux()const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%42' }, {cwd: '/tmp/work',- env: { ANTHROPIC_BASE_URL: 'https://relay.example/relay', ANTHROPIC_MODEL: 'GLM-4.7-Flash' },+ env: { ANTHROPIC_BASE_URL: 'https://relay.example/relay', ANTHROPIC_AUTH_TOKEN: 'gridkey-abc123' },command: ['/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude', '--resume', 'sess-1'],})expect(moved).toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(tmux.calls()).toEqual(['start-server ; source-file -'])// `remain-on-exit` is chained BEFORE the respawn, not after: an engine handed a rejected key can// exit before a follow-up call lands, taking its own error message down with it.- expect(readFileSync(calls, 'utf8').trim()).toBe(- 'set-option -p -t %42 remain-on-exit on ; set-option -p -t %42 @harness_engine_exit ; respawn-pane -k -c /tmp/work'- + ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_MODEL=GLM-4.7-Flash'- + ' -t %42 /bin/zsh -lic exec "$@" harness-engine claude --resume sess-1',- )+ expect(tmux.stdin()).toBe(tmuxScript([+ 'set-option', '-p', '-t', '%42', 'remain-on-exit', 'on', ';', 'set-option', '-p', '-t', '%42', '@harness_engine_exit', '',+ ';', 'respawn-pane', '-k', '-c', '/tmp/work',+ '-e', 'ANTHROPIC_BASE_URL=https://relay.example/relay', '-e', 'ANTHROPIC_AUTH_TOKEN=gridkey-abc123',+ '-t', '%42', '/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude', '--resume', 'sess-1',+ ]))+ })++ it('respawns a waiting pane with its variables on stdin too, and still hears a changed pane', async () => {+ const token = '0b4f6a8e-6d0c-4bd1-9a51-6c1a3b0f2e77'+ const tmux = scriptTmux(`printf 'adoption-mismatch\\n'`)+ const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%42' }, {+ env: { ANTHROPIC_AUTH_TOKEN: 'gridkey-abc123' }, command: ['claude'], expectedHeldToken: token,+ })+ expect(moved).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'The waiting pane changed' })+ expect(tmux.calls()).toEqual(['start-server ; source-file -'])+ // The if-shell's own command list is one word of the script, quoted twice over.+ expect(tmux.stdin()).toContain(tmuxWord(`'respawn-pane' '-k' '-e' 'ANTHROPIC_AUTH_TOKEN=gridkey-abc123' '-t' '%42' 'claude'`).slice(1, -1))})it('never reports a failed respawn as untouched, because -k already killed the old process', async () => {@@ -599,6 +639,29 @@ exit 1})/** A fake tmux on PATH that records every call, prints [listing] for `list-panes` and `%42` otherwise. */+/**+ * A tmux that records each command line, and what it was given on stdin for `source-file -` (read only then:+ * nothing else writes to a call's stdin, so reading it would wait for ever); then runs [script], or answers+ * as `new-session -P` does.+ */+function scriptTmux(script = `printf '%%42\\n'`): { calls: () => string[]; stdin: () => string } {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-script-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ const stdin = `${calls}.stdin`+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+case "$*" in *'source-file -') cat >> "$TMUX_BACKEND_CALLS.stdin" ;; esac+${script}+`, { mode: 0o700 })+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls+ return {+ calls: () => existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n') : [],+ stdin: () => existsSync(stdin) ? readFileSync(stdin, 'utf8') : '',+ }+}+function recordingTmux(listing = '', sessionId = '%42'): () => string[] {const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-old-'))dirs.push(dir)@@ -728,23 +791,27 @@ describe('TmuxBackend with variables on a tmux that cannot take them', () => {expect(calls()).toEqual([])})- it('refuses a respawn below 3.0, saying why, and asks tmux nothing', async () => {- assumeTmuxVersion({ major: 2, minor: 9 })+ // `respawn-pane -e` is 3.0, but its list goes on stdin (`source-file -`, 3.1): on 3.0 the value would be on+ // tmux's command line, so it is refused instead (audit M2).+ it('refuses a respawn below 3.1, saying why, and asks tmux nothing', async () => {+ assumeTmuxVersion({ major: 3, minor: 0 })const calls = recordingTmux()// Asked before a restart stops anything, with the same answer.- expect(await new TmuxBackend().respawnRefusal({ env })).toContain('older than 3.0')+ expect(await new TmuxBackend().respawnRefusal({ env })).toContain('older than 3.1')expect(await new TmuxBackend().respawnRefusal({})).toBeNull()const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%9' }, { env, command: ['codex'] })expect(moved).toMatchObject({ state: 'failed', dispatch: 'not_started' })- expect(moved.state !== 'succeeded' && moved.reason).toContain('older than 3.0')+ expect(moved.state !== 'succeeded' && moved.reason).toContain('older than 3.1')expect(calls()).toEqual([])})- it('respawns with them from 3.0, where respawn-pane takes -e', async () => {- assumeTmuxVersion({ major: 3, minor: 0 })- const calls = recordingTmux()+ it('respawns with them from 3.1, on stdin', async () => {+ assumeTmuxVersion({ major: 3, minor: 1 })+ const tmux = scriptTmux()await new TmuxBackend(undefined, () => 'daemon-a').respawn({ backend: 'tmux', paneId: '%9' }, { env, command: ['codex'] })- expect(calls()).toEqual(['set-option -p -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -e CODEX_HOME=/work/profile -t %9 codex'])+ expect(tmux.calls()).toEqual(['start-server ; source-file -'])+ expect(tmux.stdin()).toBe(tmuxScript(['set-option', '-p', '-t', '%9', 'remain-on-exit', 'on', ';', 'set-option', '-p', '-t', '%9',+ '@harness_engine_exit', '', ';', 'respawn-pane', '-k', '-e', 'CODEX_HOME=/work/profile', '-t', '%9', 'codex']))})})@@ -917,3 +984,122 @@ exit 0expect(await new TmuxBackend().capabilities()).toEqual({ sessionEnv: true })})})++// Audit M2 (docs/security/2026-11-02-team-account-boundary.md): every account on a machine reads every process's+// command line, so a list with values goes to tmux on stdin, in tmux's own command syntax.+describe('a tmux command list given on stdin', () => {+ it('quotes each word whole, and keeps `;` the separator it is on a command line', () => {+ expect(tmuxScript(['set-option', '-g', '@x', 'a b', ';', 'display-message', ''])).toBe(`'set-option' '-g' '@x' 'a b' ; 'display-message' ''\n`)+ expect(tmuxWord(`it's`)).toBe(`'it'"'"'s'`)+ })++ it('gives a newline or carriage return as an escape, never raw inside quotes', () => {+ // A raw newline in single quotes lost the next line when it began with `#` (tmux 3.7).+ expect(tmuxWord('a\n# b\r')).toBe(`'a'"\\n"'# b'"\\r"''`)+ expect(tmuxScript(['x\ny'])).not.toMatch(/\n./)+ })+})++describe.skipIf(!resolveBinaryOnPath('tmux'))('session variables on a real tmux server (audit M2)', () => {+ const exec = promisify(execFile)+ const token = `m2-fixture-token-${randomUUID()}`+ // Every character tmux's command syntax treats specially, a line that would read as a comment or a+ // directive, and a non-ASCII one: the engine must get the exact value.+ const tricky = `a'b"c $HOME ~ #{pane_id} ; { } \\ \n# next\n%if 1\r\t✓ ${token}`+ let tmux: IsolatedTmux++ beforeEach(async (context) => {+ // This machine's real tmux, not the newest the specs above assume.+ resetTmuxVersionCache()+ // `new-session -e` is 3.2: older servers are refused before tmux is asked (above).+ if (!(await tmuxFeatures()).sessionEnv) context.skip()+ tmux = await isolatedTmux()+ tmux.env.HOME = tmux.root+ // The backend's own bare `tmux` reaches this private server and no other, with no ~/.tmux.conf.+ vi.stubEnv('HOME', tmux.root)+ vi.stubEnv('ZDOTDIR', tmux.root)+ vi.stubEnv('TMUX', undefined)+ vi.stubEnv('TMUX_PANE', undefined)+ vi.stubEnv('TMUX_TMPDIR', tmux.root)+ })++ afterEach(async () => {+ await tmux?.close()+ vi.unstubAllEnvs()+ })++ /**+ * The command lines on this machine, as any other account reads them, that show [value]. Only those: a+ * failure must not print the rest, which may hold other accounts' own secrets.+ */+ const showing = async (value: string): Promise<string[]> =>+ (await exec('ps', ['-A', '-ww', '-o', 'args='], { maxBuffer: 64 * 1024 * 1024 })).stdout.split('\n').filter((line) => line.includes(value))++ /** What [file] holds once a pane's command has written it. */+ const written = async (file: string): Promise<string> => {+ await vi.waitFor(() => expect(existsSync(file)).toBe(true), { timeout: 10_000 })+ return readFileSync(file, 'utf8')+ }++ it('starts the server with no value in its title, and the engine gets each value exactly', async () => {+ // No server yet: the create starts it, and a server keeps the command line that started it for its life.+ await expect(tmux.run('list-sessions')).rejects.toThrow()+ const out = join(tmux.root, 'env.out')+ const created = await new TmuxBackend(undefined, () => 'daemon-a', () => {}).create({+ label: 'harness-m2-create',+ env: { M2_TOKEN: token, M2_TRICKY: tricky },+ command: ['/bin/sh', '-c', `printf '%s|%s' "$M2_TOKEN" "$M2_TRICKY" > '${out}.tmp' && mv '${out}.tmp' '${out}'; exec sleep 300`],+ })+ expect(created.state).toBe('succeeded')+ expect(await written(out)).toBe(`${token}|${tricky}`)+ expect(await tmux.run('show-environment', '-t', 'harness-m2-create', 'M2_TOKEN')).toBe(`M2_TOKEN=${token}`)+ expect(await showing(token)).toEqual([])+ })++ it('gives its options to the new session, never to another already on the server', async () => {+ // A person's own session, or another daemon's, with its own pane options.+ await tmux.run('new-session', '-d', '-s', 'theirs', '/bin/sleep', '300')+ await tmux.run('set-option', '-p', '-t', '=theirs:', '@harness_daemon', 'someone-else')+ const created = await new TmuxBackend(undefined, () => 'daemon-a', () => {}).create({+ label: 'harness-m2-second', env: { M2_TOKEN: token }, command: ['/bin/sleep', '300'],+ })+ if (created.state !== 'succeeded') throw new Error(created.reason)+ const option = (target: string, name: string, scope = '-p') => tmux.run('show-options', '-v', scope, '-t', target, name)+ expect(await option('=theirs:', '@harness_daemon')).toBe('someone-else')+ expect(await option('=theirs:', 'remain-on-exit')).not.toBe('on')+ expect(await option(created.runtime.paneId, '@harness_daemon')).toBe('daemon-a')+ expect(await option(created.runtime.paneId, 'remain-on-exit')).toBe('on')+ expect(await option('=harness-m2-second:', 'destroy-unattached', '-q')).toBe('off')+ expect(await showing(token)).toEqual([])+ })++ it('starts a server whose ~/.tmux.conf has an error and ends unattached sessions, and the agent stays', async () => {+ writeFileSync(join(tmux.root, '.tmux.conf'), 'set -g fixture-no-such-option on\nset -g destroy-unattached on\n')+ const created = await new TmuxBackend(undefined, () => 'daemon-a', () => {}).create({+ label: 'harness-m2-conf', env: { M2_TOKEN: token }, command: ['/bin/sleep', '300'],+ })+ expect(created).toMatchObject({ state: 'succeeded' })+ await new Promise((resolve) => setTimeout(resolve, 300))+ expect(await tmux.run('list-sessions', '-F', '#{session_name}')).toBe('harness-m2-conf')+ })++ it('respawns a pane, and a waiting one, with no value on any command line', async () => {+ const held = randomUUID()+ const created = await new TmuxBackend(undefined, () => 'daemon-a', () => {}).create({+ label: 'harness-m2-respawn', command: ['/bin/sh', '-c', 'exec sleep 300', 'harness-held', held],+ })+ if (created.state !== 'succeeded') throw new Error(created.reason)+ const backend = new TmuxBackend(undefined, () => 'daemon-a', () => {})+ const launch = (out: string) => ['/bin/sh', '-c', `printf '%s' "$M2_TRICKY" > '${out}.tmp' && mv '${out}.tmp' '${out}'; exec sleep 300`]+ // The waiting pane's own check runs inside tmux, and its command list is quoted inside the script.+ const first = join(tmux.root, 'held.out')+ expect(await backend.respawn(created.runtime, { env: { M2_TRICKY: tricky }, command: launch(first), expectedHeldToken: held }))+ .toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(await written(first)).toBe(tricky)+ const second = join(tmux.root, 'plain.out')+ expect(await backend.respawn(created.runtime, { env: { M2_TRICKY: tricky }, command: launch(second) }))+ .toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(await written(second)).toBe(tricky)+ expect(await showing(token)).toEqual([])+ })+})diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 42054ea99..a63454f27 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -1,7 +1,6 @@-import { execFile } from 'node:child_process'-import { shellSingleQuote } from './shellQuote.js'+import { execFile, type ExecFileException } from 'node:child_process'import { heldPaneFormat } from './nativePaneHold.js'-import { patientExec } from './patientExec.js'+import { patientDeadline, patientExec, type ExecDone } from './patientExec.js'import type { TerminalBackend, TerminalBackendPrepared } from './terminalBackend.js'import type { AgentEngine } from '../engines/types.js'import {@@ -111,6 +110,60 @@ export function unsetServerEnvArgs(names: readonly string[]): string[] {return names.flatMap((name, i) => [...(i ? [';'] : []), 'set-environment', '-g', '-u', name])}+/**+ * [word] as one word of tmux's command syntax, the one `source-file` and `if-shell` parse: single-quoted,+ * each `'` closed, given in double quotes and reopened. A newline or carriage return goes as a double-quoted+ * escape: measured on tmux 3.7, a raw newline inside single quotes lost the next line when it began with `#`.+ */+export function tmuxWord(word: string): string {+ return `'${word.replace(/'/g, `'"'"'`).replace(/\n/g, `'"\\n"'`).replace(/\r/g, `'"\\r"'`)}'`+}++/** The tmux command list [args] (`;` separating its commands, as on a command line) as a `source-file` script. */+export function tmuxScript(args: readonly string[]): string {+ return `${args.map((word) => word === ';' ? ';' : tmuxWord(word)).join(' ')}\n`+}++/**+ * The target that names the session called [label] exactly, and its active pane (its only one when it has just+ * been made), or null when there is no such target: a session with no name, or one whose name tmux would read+ * as a window or pane separator.+ */+export function scriptTarget(label: string | undefined): string | null {+ return label && !/[:.]/.test(label) ? `=${label}:` : null+}++/**+ * The command line that runs a script given on stdin. `source-file` alone does not start a server ("no server+ * running"), so `start-server` comes first; a server it starts takes this as its title, with no value in it.+ */+export const SCRIPT_ON_STDIN = ['start-server', ';', 'source-file', '-'] as const++/**+ * Run the tmux command list [args] with none of its words on a command line: every account on the machine+ * reads every process's command line (`ps -axww`). `new-session -e KEY=VALUE` as argv showed a Team+ * account's relay token to every account on the Mac Studio for as long as the tmux server it started lived,+ * since a server keeps that command line as its title (audit M2, docs/security/2026-11-02-team-account-boundary.md);+ * and with a server running, the short-lived client still showed it to a loop of `ps`. The list goes on stdin,+ * which only its own account can read, and touches no disk, so a crash leaves nothing behind. `source-file -` is+ * tmux 3.1. The deadline is patientExec's, for the same held-loop reason; tmux answers exactly as on argv: a+ * failing command stops the rest of the list, with its message on stderr.+ */+function runScript(args: readonly string[], timeout: number, done: ExecDone): void {+ let finished = false+ let cancel = (): void => {}+ // A child this kills for its deadline is reported `killed`, which `create` reads as a timeout.+ const child = execFile('tmux', [...SCRIPT_ON_STDIN], { encoding: 'utf8' }, (error: ExecFileException | null, stdout: string, stderr: string) => {+ finished = true+ cancel()+ done(error, stdout ?? '', stderr ?? '')+ })+ // A tmux that cannot be started (ENOENT) closes its stdin; the error is the callback's to report, not a throw.+ child.stdin?.on('error', () => {})+ child.stdin?.end(tmuxScript(args))+ if (!finished) cancel = patientDeadline(timeout, () => child.kill('SIGTERM'))+}+export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {readonly name = 'tmux' as constreadonly instanceId = 'tmux:default'@@ -187,12 +240,21 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {this.observeMachineName()const features = await this.features()const variables = Object.entries(request.env ?? {})- // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the launch argv, so a grid- // relay key never lands in `ps` output for the life of the agent. Callers refuse a grid or a+ // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the engine's argv, and a list+ // that carries them goes to tmux on stdin (`runScript`), never on tmux's own command line: either+ // would put a grid relay key in `ps` output. Callers refuse a grid or a// harness on an older tmux by name (`capabilities().sessionEnv`); whatever else reaches here with// variables on one is refused here, saying why, rather than handed to tmux to answer with its// usage text — and never moved into the argv, where a secret would show.if (variables.length && !features.sessionEnv) return terminalActionNotStarted(tmuxTooOldForEnv(TMUX_FEATURE_MIN.sessionEnv, 'a new session'))+ // On a command line, tmux gives the options chained after `new-session` to the session it just made.+ // From `source-file` it does not: they went to the session tmux takes as current, another one's pane+ // when the server had one, which took this daemon's tag and left the new pane with none, nor+ // `remain-on-exit`, nor `destroy-unattached off` (found in review of #2542, tmux 3.7 and 3.8). There each+ // option names the new session exactly (`=NAME:`), so the session needs a name that target can hold.+ const target = variables.length ? scriptTarget(request.label) : undefined+ if (target === null) return terminalActionNotStarted('a session with its own variables needs a name without ":" or "."')+ const option = target ? ['-t', target] : []const owner = this.owner()const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']if (request.cwd) args.push('-c', request.cwd)@@ -210,20 +272,20 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// millisecond, and a second `set-option` call loses that race — measured, the session was// already gone before the follow-up command could reach the server.// Whoever created the pane owns turning this back off; see `clearPaneRemainOnExit`.- args.push(';', 'set-option', scope, 'remain-on-exit', 'on')+ args.push(';', 'set-option', scope, ...option, 'remain-on-exit', 'on')// An agent's session never has a client attached, so a person's `set -g destroy-unattached on`// (in their ~/.tmux.conf, which this server loads) ended every agent the moment it was made, and// Harness could not run at all on their machine (found end to end, e2e/tmuxconf.e2e.ts). Turned// off for this session only, in this same invocation, before the server can act on it.- args.push(';', 'set-option', 'destroy-unattached', 'off')+ args.push(';', 'set-option', ...option, 'destroy-unattached', 'off')// Same invocation, same reason: an engine asks its terminal for its colours (OSC 10/11) in its// first milliseconds and never again, so the style has to be there before the engine is.const style = windowStyleOf(this.hostTheme())- args.push(';', ...paneStyleArgs(features, style))+ args.push(';', ...paneStyleArgs(features, style, target))// Whose pane it is, from its first instant: another daemon on this tmux server scanning a moment// later must already see it is not its own. On the pane, which keeps it wherever the person moves// it (see HARNESS_OWNER_OPTION); before tmux 3.0, on the window, and in the start command.- args.push(';', 'set-option', scope, HARNESS_OWNER_OPTION, owner)+ args.push(';', 'set-option', scope, ...option, HARNESS_OWNER_OPTION, owner)// `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }// A new session is a notification to every control client: on a tmux before 3.7, not while one@@ -231,11 +293,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {const result = await inTmuxRoom('notify', () => new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {if (request.current?.() === false) { resolve({ error: Object.assign(new Error('The harness changed before pane dispatch'), { code: 'HARNESS_CANCELLED' }), stdout: '', stderr: '' }); return }request.onDispatch?.()- run('tmux', args, { timeout: 5_000 }, (error, stdout, stderr) => resolve({- error: error as ExecError | null,- stdout,- stderr,- }))+ const done: ExecDone = (error, stdout, stderr) => resolve({ error: error as ExecError | null, stdout, stderr })+ if (variables.length) runScript(args, 5_000, done)+ else run('tmux', args, { timeout: 5_000 }, done)}), features)if (result.error) {if (result.error.code === 'HARNESS_CANCELLED') return terminalActionNotStarted(result.error.message)@@ -250,7 +310,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {|| (result.error.killed ? 'tmux did not answer within 5s' : result.error.message.slice(0, 200))return terminalActionPossiblyExecuted(`tmux session creation did not complete: ${detail}`)}- const paneId = result.stdout.trim()+ // The first line: on stdin, a tmux that `start-server` just started prints its ~/.tmux.conf's errors to the+ // client after the pane id, where on a command line it shows them in the session instead.+ const paneId = result.stdout.trim().split('\n')[0]?.trim() ?? ''if (!/^%\d+$/.test(paneId)) {return terminalActionPossiblyExecuted('tmux created a session without returning its root pane')}@@ -283,7 +345,8 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {* a dead pane and no engine.*/async respawnRefusal(request: Pick<TerminalRespawnRequest, 'env'>): Promise<string | null> {- // `respawn-pane -e` is tmux 3.0; refused before, for the reason `create` gives.+ // `respawn-pane -e` is tmux 3.0, and the stdin its list goes on (`runScript`) 3.1; refused before, for+ // the reason `create` gives.return Object.keys(request.env ?? {}).length && !(await this.features()).respawnEnv ? tmuxTooOldForEnv(TMUX_FEATURE_MIN.respawnEnv, 'a respawned pane') : null}@@ -309,15 +372,18 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {if (request.expectedHeldToken && !/^[a-f0-9-]{36}$/.test(request.expectedHeldToken)) return terminalActionNotStarted('invalid waiting pane identity')const command = request.expectedHeldToken? ['if-shell', '-F', '-t', runtime.paneId, heldPaneFormat(request.expectedHeldToken),- commands.map(parts => parts.map(shellSingleQuote).join(' ')).join('; '), 'display-message -p adoption-mismatch']+ commands.map(parts => parts.map(tmuxWord).join(' ')).join('; '), 'display-message -p adoption-mismatch']: commands.flatMap((parts, index) => index ? [';', ...parts] : parts)const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {if (request.current?.() === false) { resolve({ error: Object.assign(new Error('The harness changed before pane dispatch'), { code: 'HARNESS_CANCELLED' }), stderr: '' }); return }request.onDispatch?.()- run('tmux', command, { timeout: 5_000 }, (error, stdout, stderr) => resolve({+ const done: ExecDone = (error, stdout, stderr) => resolve({error: stdout.trim() === 'adoption-mismatch' ? Object.assign(new Error('The waiting pane changed'), { code: 'HARNESS_CANCELLED' }) : error as NodeJS.ErrnoException | null,stderr,- }))+ })+ // With variables, on stdin, never on tmux's command line (`runScript`, as in `create`).+ if (variables.length) runScript(command, 5_000, done)+ else run('tmux', command, { timeout: 5_000 }, done)})if (!result.error) return TERMINAL_ACTION_SUCCEEDEDif (result.error.code === 'HARNESS_CANCELLED') return terminalActionNotStarted(result.error.message)diff --git a/cli/src/lib/tmuxVersion.spec.ts b/cli/src/lib/tmuxVersion.spec.tsindex 50d283e64..51352969e 100644--- a/cli/src/lib/tmuxVersion.spec.ts+++ b/cli/src/lib/tmuxVersion.spec.ts@@ -50,11 +50,13 @@ describe('tmuxFeaturesOf', () => {expect(tmuxFeaturesOf({ major: 2, minor: 7 })).toEqual(none)expect(tmuxFeaturesOf({ major: 2, minor: 8 })).toEqual(none)expect(tmuxFeaturesOf({ major: 2, minor: 9 })).toEqual({ ...none, resizeWindow: true })- // Ubuntu 20.04 ships 3.0a: pane options, but no client flags or session environment yet.- const three = { ...none, resizeWindow: true, paneOptions: true, sendKeysHex: true, respawnEnv: true }+ // Ubuntu 20.04 ships 3.0a: pane options, but no client flags or session environment yet, and no+ // `source-file -` to give a respawn its variables off the command line.+ const three = { ...none, resizeWindow: true, paneOptions: true, sendKeysHex: true }expect(tmuxFeaturesOf({ major: 3, minor: 0 })).toEqual(three)- expect(tmuxFeaturesOf({ major: 3, minor: 1 })).toEqual({ ...three, captureTrailingSpaces: true })- const threeTwo = { ...three, captureTrailingSpaces: true, clientFlags: true, sessionEnv: true }+ const threeOne = { ...three, respawnEnv: true, captureTrailingSpaces: true }+ expect(tmuxFeaturesOf({ major: 3, minor: 1 })).toEqual(threeOne)+ const threeTwo = { ...threeOne, clientFlags: true, sessionEnv: true }expect(tmuxFeaturesOf({ major: 3, minor: 2 })).toEqual(threeTwo)// Ubuntu 24.04 ships 3.4, Fedora 3.5a: a notification can still reach a control client mid-attach.expect(tmuxFeaturesOf({ major: 3, minor: 6 })).toEqual(threeTwo)diff --git a/cli/src/lib/tmuxVersion.ts b/cli/src/lib/tmuxVersion.tsindex b177d81fe..747130afb 100644--- a/cli/src/lib/tmuxVersion.ts+++ b/cli/src/lib/tmuxVersion.ts@@ -30,8 +30,8 @@ export const TMUX_FEATURE_MIN = {paneOptions: { major: 3, minor: 0 },/** `send-keys -H`, keys given as hex bytes (3.0). */sendKeysHex: { major: 3, minor: 0 },- /** `respawn-pane -e` (3.0). */- respawnEnv: { major: 3, minor: 0 },+ /** `respawn-pane -e` (3.0), given on stdin with `source-file -` (3.1) so no value shows in `ps` (tmuxBackend.ts `runScript`). */+ respawnEnv: { major: 3, minor: 1 },/** `capture-pane -N`, a row's trailing spaces kept (3.1). */captureTrailingSpaces: { major: 3, minor: 1 },/** Client flags (3.2): `attach-session -f ignore-size`. */diff --git a/desktop/lib/shortcuts/keymap_host.dart b/desktop/lib/shortcuts/keymap_host.dartindex 08737c475..7ecb1d057 100644--- a/desktop/lib/shortcuts/keymap_host.dart+++ b/desktop/lib/shortcuts/keymap_host.dart@@ -1,3 +1,4 @@+import 'package:flutter/foundation.dart' show defaultTargetPlatform;import 'package:flutter/services.dart';import 'package:flutter/widgets.dart';@@ -6,6 +7,7 @@ import 'keymap.dart';import 'keymap_commands.dart';import 'keymap_dispatch.dart';import 'keymap_keyboard.dart';+import 'text_editing_keys.dart';const composerOwnedStrokes = [KeyStroke('w', control: true),@@ -133,16 +135,41 @@ class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {_notifyPending();return KeyEventResult.ignored;}- final value = context- .findAncestorStateOfType<EditableTextState>()- ?.widget- .controller- .value;+ final editable = context.findAncestorStateOfType<EditableTextState>();+ final value = editable?.widget.controller.value;final composing =region?.composing?.call() == true ||(value != null &&value.composing.isValid &&!value.composing.isCollapsed);+ // A caret in a text field owns the standard editing keys: ⌘← is the line+ // start there, not "focus the pane to the left". Not so for text that only+ // reads (selectable text is a read-only field: no caret to move), for text+ // being composed (the IME owns the keys; Ctrl+K would cut into it), for the+ // menus built on a field (the picker, the project menu, which keep their+ // own keys), nor mid-chord (a chord already under way finishes first).+ final contextKind = region?.contextKind ?? KeymapContext.workspace;+ if (editable != null &&+ value != null &&+ !editable.widget.readOnly &&+ !composing &&+ !_dispatch.hasPending &&+ contextKind != KeymapContext.picker &&+ contextKind != KeymapContext.project) {+ final typed = keyStrokeForEvent(event);+ final platform = defaultTargetPlatform;+ if (textFieldKillsLine(typed, platform: platform)) {+ Actions.maybeInvoke(context, killLineIntent);+ return KeyEventResult.handled;+ }+ if (textFieldKeepsStroke(+ typed,+ platform: platform,+ hasText: value.text.isNotEmpty,+ )) {+ return KeyEventResult.ignored;+ }+ }final stroke = keyStrokeForEvent(event);final aliasesBlocked =region?.contextKind == KeymapContext.terminal &&diff --git a/desktop/lib/shortcuts/text_editing_keys.dart b/desktop/lib/shortcuts/text_editing_keys.dartnew file mode 100644index 000000000..48aca9c13--- /dev/null+++ b/desktop/lib/shortcuts/text_editing_keys.dart@@ -0,0 +1,65 @@+import 'package:flutter/widgets.dart';++import 'keymap.dart';++/// Whether a focused text field keeps [stroke] for editing, ahead of any app+/// shortcut. The window's keymap runs before the field does, so without this+/// ⌘← moved the pane focus instead of the caret and ⇧⌘← moved the pane itself.+///+/// [hasText] is whether the field holds any text. Only the ⌘-arrows depend on+/// it: in an empty box they have nothing to move, so they keep focusing and+/// moving panes. Every other key here is editing only.+///+/// macOS: ⌥←/→ by word, ⌘←/→ to line start/end, ⌘↑/↓ to text start/end (⇧+/// selects); ⌥⌫ deletes a word, ⌘⌫ to line start; Ctrl+A/E. Ctrl+K+/// is [textFieldKillsLine]: Flutter has no shortcut for it.+/// Others: Ctrl+←/→ by word, Home/End (Ctrl for the text ends) with ⇧ selecting;+/// Ctrl+Backspace/Delete delete a word.+///+/// Pane focus on ⌘H/J/K/L and the tab keys on ⌥⌘-arrows are not here: a stroke+/// with ⌘ and ⌥ together, or ⌘ with a letter, is never an editing key.+bool textFieldKeepsStroke(+ KeyStroke? stroke, {+ required TargetPlatform platform,+ required bool hasText,+}) {+ if (stroke == null) return false;+ final key = stroke.key;+ final arrow = key == 'left' || key == 'right' || key == 'up' || key == 'down';+ final horizontal = key == 'left' || key == 'right';+ final deletes = key == 'backspace' || key == 'delete';+ final command = stroke.command, alt = stroke.alt, control = stroke.control;++ if (platform == TargetPlatform.macOS) {+ if (command && !alt && !control) {+ if (arrow) return hasText;+ return key == 'backspace' && !stroke.shift;+ }+ if (alt && !command && !control) return horizontal || deletes;+ if (control && !command && !alt && !stroke.shift) {+ return key == 'a' || key == 'e';+ }+ return false;+ }++ if (command || alt) return false;+ if (key == 'home' || key == 'end') return true;+ return control && (horizontal || deletes);+}++/// macOS Ctrl+K deletes to the end of the line. Flutter serves it only through+/// the system's `deleteToEndOfParagraph:` selector, which it does not map, so+/// the host runs [killLineIntent] itself for a field that holds the caret.+bool textFieldKillsLine(+ KeyStroke? stroke, {+ required TargetPlatform platform,+}) =>+ platform == TargetPlatform.macOS &&+ stroke != null &&+ stroke.key == 'k' &&+ stroke.control &&+ !stroke.command &&+ !stroke.alt &&+ !stroke.shift;++const killLineIntent = DeleteToLineBreakIntent(forward: true);diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 08ac13e5b..08c219f97 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1972,6 +1972,7 @@ class AppNotifier extends ChangeNotifier {throw const SuperTabFailure('MACHINE_UNAVAILABLE',teamComputerSwarmMessage,+ settled: true,);}throw const SuperTabFailure(@@ -7615,10 +7616,16 @@ class AppNotifier extends ChangeNotifier {_deskEnsure(_authRevision);// A daemon whose backend was away answered the last read with an error.if (_desk.enabled) unawaited(agentMessages.refresh());+ // The same for the Swarm's: a daemon just started has its backend a few seconds later+ // (6 s on 10-30), and the Swarm on screen would otherwise wait for its next poll.+ if (viewer == null) superTabs.serverAvailable();}notifyListeners();}+ @visibleForTesting+ void noteBackendOnlineForTest(bool online) => _noteBackendOnline(online);+/// Supervision starts once the daemon is at least ANSWERING — ready or still connecting. It used to/// wait for ready, out of fear of a concurrent `harness start` from both places; the supervisor/// no longer spawns while anything answers on the port, so that race is gone, and starting it on@@ -9694,7 +9701,8 @@ class AppNotifier extends ChangeNotifier {// (`SuperTabReading.readsOnConnect`). The web reads the backend itself,// so a machine connecting there is no reason to read.if (viewer == null) {- final served = sharedTabsTarget != null;+ final served =+ sharedTabsTarget?.connectionStatus == ConnectionStatus.connected;if (served && !_superTabsServed) superTabs.serverAvailable();_superTabsServed = served;}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex c6adff114..3e77204a0 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -76,9 +76,18 @@ const superTabRefusedAsSent = "The server couldn't take this message.";final _schemaWords = RegExp(r'Unrecognized key|^command(\.\w+)*: ');class SuperTabFailure implements Exception {- const SuperTabFailure(this.code, this.message, {this.statusCode = 0});+ const SuperTabFailure(+ this.code,+ this.message, {+ this.statusCode = 0,+ this.settled = false,+ });final String code, message;final int statusCode;++ /// No wait changes this answer, whatever its code ([SuperTabReading.retriesFirstRead]): a Team+ /// computer that may not speak as the person, beside a computer that is only still starting.+ final bool settled;@overrideString toString() => message;}@@ -563,6 +572,8 @@ class SuperTabController extends ChangeNotifier {/// ([SuperTabReading.connectGrace]): still loading rather than failed.bool _waitingForMachine = false;Object? _graceFailure;+ Timer? _firstReadRetry;+ int _firstReadTries = 0;/// Not on screen: another tab is shown, or the page is hidden. Only a/// reading that [SuperTabReading.pausesAway] stops polling for it; coming@@ -604,6 +615,10 @@ class SuperTabController extends ChangeNotifier {/// Since when the reads have been failing, while [backendUnreachable]: the first failure of this run of them.DateTime? unreachableSince;+ /// While [backendUnreachable], no read has been answered yet since this Swarm opened: nothing was+ /// lost, so it says Connecting rather than Reconnecting.+ bool get stillConnecting => backendUnreachable && stateReads == 0;+/// How many reads of the Swarm's state have been answered. A sidebar that is waiting for a new reading (back from/// the background) knows it has one when this moves.int stateReads = 0;@@ -3169,6 +3184,7 @@ class SuperTabController extends ChangeNotifier {unreachableSince = null;_waitingForMachine = false;_graceEnd?.cancel();+ _firstReadRetry?.cancel();stateReads++;// How long the Swarm took to answer, and nothing it said: the log shows a slow or failing// backend, which the sidebar's ages and the machines' states otherwise only hint at.@@ -3299,6 +3315,7 @@ class SuperTabController extends ChangeNotifier {if (_inConnectGrace(failure)) {_waitingForMachine = true;_graceFailure = failure;+ _retryFirstRead();} else {_waitingForMachine = false;_readFailure(failure);@@ -3314,7 +3331,8 @@ class SuperTabController extends ChangeNotifier {'${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',);} finally {- loading = _waitingForMachine;+ // A saved view stays drawn through the grace; only an empty pane waits on a spinner.+ loading = _waitingForMachine && snapshot == null;if (!quiet || stateChanged || _shown != before) _changed();}}@@ -3493,10 +3511,7 @@ class SuperTabController extends ChangeNotifier {/// ([SuperTabReading.connectGrace]) runs out: its error waits for the grace.bool _inConnectGrace(Object failure) {final since = _startedAt;- if (stateReads > 0 ||- since == null ||- failure is! SuperTabFailure ||- failure.code != 'MACHINE_UNAVAILABLE') {+ if (stateReads > 0 || since == null || !_graceCovers(failure)) {return false;}final left = _policy.connectGrace - clock.now().difference(since);@@ -3511,6 +3526,32 @@ class SuperTabController extends ChangeNotifier {return true;}+ bool _graceCovers(Object failure) {+ final code = failure is SuperTabFailure ? failure.code : null;+ if (!_policy.retriesFirstRead) return code == 'MACHINE_UNAVAILABLE';+ if (_isUpdateRequired(failure)) return false;+ // In passing: no answer at all, a 5xx, or a read before this computer has its row, which a+ // Swarm restored at launch can make. A refusal (401, 403, 404) is the server's word.+ return failure is! SuperTabFailure ||+ (!failure.settled &&+ (failure.statusCode == 0 || failure.statusCode >= 500));+ }++ /// Bounded by [SuperTabReading.firstReadRetryDelays]; the grace's end then says what failed.+ void _retryFirstRead() {+ final delays = SuperTabReading.firstReadRetryDelays;+ if (!_policy.retriesFirstRead ||+ _disposed ||+ accessRevoked ||+ _firstReadTries >= delays.length) {+ return;+ }+ _firstReadRetry?.cancel();+ _firstReadRetry = Timer(delays[_firstReadTries++], () {+ if (!_disposed && !accessRevoked && stateReads == 0) unawaited(refresh());+ });+ }+/// The same messages with the same receipts: posted text does not change./// Whether [answer] says a reaction changed in [id] since its rows were/// last refreshed: a poll then reads the page shown again (backend@@ -3636,6 +3677,7 @@ class SuperTabController extends ChangeNotifier {_quoting.clear();_forgetThreads();_poll?.cancel();+ _firstReadRetry?.cancel();cancelUpload();}}@@ -4549,6 +4591,7 @@ class SuperTabController extends ChangeNotifier {_poll?.cancel();_toldRead?.cancel();_graceEnd?.cancel();+ _firstReadRetry?.cancel();_draftSave?.cancel();for (final retry in _quoteRetries) {retry.cancel();diff --git a/desktop/lib/super_tabs/machine_status.dart b/desktop/lib/super_tabs/machine_status.dartindex 44ab44bcb..925ef732c 100644--- a/desktop/lib/super_tabs/machine_status.dart+++ b/desktop/lib/super_tabs/machine_status.dart@@ -278,22 +278,29 @@ class _DotPainter extends CustomPainter {old.quiet != quiet;}-/// The pill beside the Machines heading while the Swarm cannot be read: "Reconnecting · 1m". A live-/// Swarm shows no pill. Where the heading leaves too little room for the words (the minimum pane), it is+/// The pill beside the Machines heading while the Swarm cannot be read: "Reconnecting · 1m", or+/// "Connecting · 4s" when it has not been read yet since it opened. A live Swarm shows no pill. Where the heading leaves too little room for the words (the minimum pane), it is/// only its dot, which says the same on hover.class SuperTabMachinesPill extends StatelessWidget {- const SuperTabMachinesPill({super.key, required this.reconnectingFor});+ const SuperTabMachinesPill({+ super.key,+ required this.reconnectingFor,+ this.connecting = false,+ });/// How long the Swarm has failed to be read.final Duration reconnectingFor;+ /// Nothing has been read yet ([SuperTabController.stillConnecting]).+ final bool connecting;+/// Below this width the words would ellipsize to almost nothing.static const _minWordsWidth = 56.0;@overrideWidget build(BuildContext context) {final failingFor = superTabAgoShort(reconnectingFor);- final text = 'Reconnecting · $failingFor';+ final text = '${connecting ? 'Connecting' : 'Reconnecting'} · $failingFor';final dot = DecoratedBox(decoration: BoxDecoration(shape: BoxShape.circle,@@ -302,7 +309,8 @@ class SuperTabMachinesPill extends StatelessWidget {child: const SizedBox.square(dimension: 6),);return Semantics(- label: 'Machines: reconnecting, for $failingFor',+ label:+ 'Machines: ${connecting ? 'connecting' : 'reconnecting'}, for $failingFor',excludeSemantics: true,child: LayoutBuilder(builder: (context, constraints) => constraints.maxWidth < _minWordsWidthdiff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex b1c3ff8c6..288d3b642 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -2193,6 +2193,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {// Only a Swarm that can't be read is news; a live one says nothing.trailing: c.backendUnreachable? SuperTabMachinesPill(+ connecting: c.stillConnecting,reconnectingFor: failingSince == null? Duration.zero: widget.now().difference(failingSince),diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dartindex c4e40dc7a..fd5682b1d 100644--- a/desktop/lib/super_tabs/reading.dart+++ b/desktop/lib/super_tabs/reading.dart@@ -13,6 +13,7 @@ class SuperTabReading {this.messagesWhenChanged = false,this.readsOnConnect = false,this.connectGrace = Duration.zero,+ this.retriesFirstRead = false,this.messagesWithState = false,this.drawsSaved = false,this.confirmsSaved = false,@@ -24,6 +25,9 @@ class SuperTabReading {static const desktop = SuperTabReading(awayPoll: Duration(seconds: 15),messagesWhenChanged: true,+ readsOnConnect: true,+ connectGrace: Duration(seconds: 10),+ retriesFirstRead: true,messagesWithState: true,drawsSaved: true,confirmsSaved: true,@@ -62,6 +66,23 @@ class SuperTabReading {/// state before it shows the error; a machine is usually still connecting.final Duration connectGrace;+ /// True (Desktop) tries a first read that failed in passing again after+ /// [firstReadRetryDelays], within [connectGrace]. Its reads go through this+ /// computer's daemon, which may still be starting while the app opens: such a+ /// read used to wait for the next poll, 15 s for a Swarm not on screen, with the+ /// heading saying Reconnecting. The grace then covers any such failure, but not+ /// a settled one ([SuperTabFailure.settled]).+ final bool retriesFirstRead;++ /// The waits between tries of a first read ([retriesFirstRead]).+ static const firstReadRetryDelays = <Duration>[+ Duration(milliseconds: 500),+ Duration(seconds: 1),+ Duration(seconds: 2),+ Duration(seconds: 2),+ Duration(seconds: 2),+ ];+/// True starts the saved conversation's messages read beside the first/// state read, instead of after it.final bool messagesWithState;diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 855646157..8c6e698d0 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -44,6 +44,25 @@ Duration reconnectDelay(int attempt, Random random) {);}+/// How many times a Desktop connection that has never been up retries quickly while it opens+/// ([firstConnectRetryDelay]). It says connecting through them: nothing has been lost yet, and+/// `reconnecting` is what marks a machine offline. Few, because each can cost the daemon a backend+/// dial, and only once per connection: the socket that fails at once for good goes on to the backoff.+const firstConnectRetries = 3;++/// The wait before the [attempt]th retry of a first connect, of [firstConnectRetries]. Opening used+/// to spend these tries on the backoff's 0.5 to 7 s, on top of the 1 and 2 s the daemon itself holds a+/// failed machine for (a retry inside that hold is answered from its memory, without a dial).+Duration firstConnectRetryDelay(int attempt) => attempt <= 1+ ? const Duration(milliseconds: 500)+ : const Duration(seconds: 1);++/// How long a Desktop connection that has never been up goes on saying connecting, past its quick+/// tries. `reconnecting` marks a machine offline, and a daemon just started has its backend some+/// seconds later (6 s on 10-30): those seconds are not a computer that is off. As long as the+/// daemon's own wait for one dial. A relay that says the machine is off is believed at once ([_park]).+const firstConnectWindow = Duration(seconds: 15);+/// How long a connection has to stay up before its next drop starts the backoff over. Resetting it/// the moment a socket was up made a socket the backend dropped right after its handshake redial/// every second, for good: about 54 dials a minute from one browser tab (prod, 2026-10-28).@@ -197,6 +216,9 @@ class WsConn {@visibleForTestingfinal CloudSocketFactory? cloudSocket;+ /// [firstConnectWindow]; a test's own.+ final Duration firstConnectFor;+/// The reconnect jitter's source. Null is a fresh [Random].final Random _random;@@ -220,6 +242,12 @@ class WsConn {bool _connecting = false;bool _ready = false;int _attempt = 0;++ /// Has been up at least once. Until then, a Desktop connection is still on its first connect.+ bool _everReady = false;++ /// From the first dial to the first time up, for the log: what opening the app waited for.+ Stopwatch? _firstConnect;Timer? _reconnectTimer;Timer? _stableTimer;Timer? _observerHandshakeTimer;@@ -359,6 +387,7 @@ class WsConn {this.transportPlugins,this.cloudSocket,Random? random,+ @visibleForTesting this.firstConnectFor = firstConnectWindow,}) : _random = random ?? Random();/// The socket to dial, decided afresh on every connect: whether the file is@@ -433,8 +462,9 @@ class WsConn {}_connecting = true;_ready = false;+ _firstConnect ??= Stopwatch()..start();onStatus(- _attempt == 0+ _attempt == 0 || _saysConnecting? ConnectionStatus.connecting: ConnectionStatus.reconnecting,);@@ -634,6 +664,15 @@ class WsConn {_observerHandshakeTimer?.cancel();_parkedRechecks = 0;_ready = true;+ if (!_everReady) {+ _everReady = true;+ // The short id and the times only: what a person's opening really took, on their own Mac.+ appLog.debug(+ 'ws',+ 'first connect ${machineId.length > 8 ? machineId.substring(0, 8) : machineId} '+ 'in ${_firstConnect?.elapsedMilliseconds ?? 0} ms, $_attempt retries',+ );+ }_refreshedToken = null;_stableTimer?.cancel();_stableTimer = Timer(connectionStableAfter, () => _attempt = 0);@@ -1202,12 +1241,38 @@ class WsConn {}}+ /// A Desktop connection that has not been up yet, within its quick retries. A browser's sockets+ /// each reach the backend itself, so it keeps the plain backoff.+ bool get _onFirstConnect =>+ isLocal && !_everReady && _attempt <= firstConnectRetries;++ /// Nothing has been lost yet: its quick tries, or the seconds of [firstConnectFor].+ bool get _saysConnecting =>+ _onFirstConnect ||+ (isLocal &&+ !_everReady &&+ (_firstConnect?.elapsed ?? Duration.zero) < firstConnectFor);+void _scheduleReconnect() {if (_closing) return;_attempt++;- onStatus(ConnectionStatus.reconnecting);+ onStatus(+ _saysConnecting+ ? ConnectionStatus.connecting+ : ConnectionStatus.reconnecting,+ );_reconnectTimer?.cancel();- final delay = fixedReconnectDelay ?? reconnectDelay(_attempt, _random);+ final delay =+ fixedReconnectDelay ??+ (_onFirstConnect+ ? firstConnectRetryDelay(_attempt)+ // The backoff starts from its beginning once the quick tries are spent.+ : reconnectDelay(+ isLocal && !_everReady+ ? _attempt - firstConnectRetries+ : _attempt,+ _random,+ ));_reconnectTimer = Timer(delay, connect);}diff --git a/desktop/test/first_connect_test.dart b/desktop/test/first_connect_test.dartnew file mode 100644index 000000000..9268bc9ab--- /dev/null+++ b/desktop/test/first_connect_test.dart@@ -0,0 +1,246 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/ws/ws_conn.dart';++/// A daemon's local socket whose relay fails the first [failSelects] selects, as a dial that fails+/// does (close 1011), and then answers. A machine in [hanging] never answers: a slow handshake.+class _Daemon {+ _Daemon._(this.server);+ final HttpServer server;+ int failSelects = 0;+ int selects = 0;+ final hanging = <String>{};+ final sockets = <WebSocket>[];++ static Future<_Daemon> start() async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final daemon = _Daemon._(server);+ server.listen((request) async {+ // Whatever else finds a loopback port on a shared machine is not a dial of this test's.+ if (!WebSocketTransformer.isUpgradeRequest(request)) {+ request.response.statusCode = HttpStatus.notFound;+ await request.response.close();+ return;+ }+ final ws = await WebSocketTransformer.upgrade(request);+ daemon.sockets.add(ws);+ ws.listen((raw) {+ final frame = jsonDecode(raw as String) as Map<String, dynamic>;+ if (frame['type'] != 'machine_select') return;+ daemon.selects++;+ final machineId = (frame['payload'] as Map)['machineId'] as String;+ if (daemon.hanging.contains(machineId)) return;+ if (daemon.failSelects > 0) {+ daemon.failSelects--;+ unawaited(ws.close(1011, 'relay failed'));+ return;+ }+ ws.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': machineId},+ }),+ );+ });+ });+ return daemon;+ }++ Future<void> stop() async {+ for (final ws in sockets) {+ await ws.close();+ }+ await server.close(force: true);+ }+}++/// The longest wait the backoff's jitter can draw, so a test of how soon a retry goes cannot pass on+/// a lucky draw.+class _LongestWait implements Random {+ @override+ double nextDouble() => 1;+ @override+ bool nextBool() => true;+ @override+ int nextInt(int max) => max - 1;+}++void main() {+ late _Daemon daemon;+ final conns = <WsConn>[];++ setUp(() async => daemon = await _Daemon.start());+ tearDown(() async {+ for (final conn in conns) {+ await conn.close();+ }+ conns.clear();+ await daemon.stop();+ });++ WsConn local(+ List<ConnectionStatus> statuses, {+ String machineId = 'm1',+ Duration firstConnectFor = firstConnectWindow,+ }) {+ final conn = WsConn(+ wsBaseUrl: 'wss://unused.example',+ autonomousEnv: 'prod',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: statuses.add,+ random: _LongestWait(),+ firstConnectFor: firstConnectFor,+ transportKind: WsTransportKind.localPlaintext,+ allowLocalTcpFixture: true,+ localWsUri: Uri.parse(+ 'ws://127.0.0.1:${daemon.server.port}/api/local-ws',+ ),+ );+ conns.add(conn);+ return conn;+ }++ Future<void> untilReady(WsConn conn, Duration within) async {+ final clock = Stopwatch()..start();+ while (!conn.isReady) {+ if (clock.elapsed > within) {+ fail('not ready after ${clock.elapsedMilliseconds} ms');+ }+ await Future<void>.delayed(const Duration(milliseconds: 20));+ }+ }++ test('a first connect that has not failed says connecting', () async {+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses);+ await conn.connect();+ expect(statuses.first, ConnectionStatus.connecting);+ await untilReady(conn, const Duration(seconds: 2));+ expect(statuses, isNot(contains(ConnectionStatus.reconnecting)));+ expect(statuses.last, ConnectionStatus.connected);+ });++ test('three failed first tries say connecting and connect sooner than the backoff could', () async {+ // The backoff's shortest waits for these three are 0.5 + 1 + 2 = 3.5 s; these wait 2.5 s.+ daemon.failSelects = 3;+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses);+ final clock = Stopwatch()..start();+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 10));+ expect(clock.elapsed, lessThan(const Duration(milliseconds: 3400)));+ expect(daemon.selects, 4);+ expect(statuses, isNot(contains(ConnectionStatus.reconnecting)));+ });++ test('the first retry goes within about half a second', () async {+ daemon.failSelects = 1;+ final conn = local([]);+ final clock = Stopwatch()..start();+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 5));+ expect(clock.elapsed, lessThan(const Duration(milliseconds: 900)));+ });++ test('past the quick tries it still says connecting within the window, and backs off from the start', () async {+ daemon.failSelects = firstConnectRetries + 1;+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses);+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 10));+ expect(statuses, isNot(contains(ConnectionStatus.reconnecting)));+ expect(daemon.selects, firstConnectRetries + 2);+ });++ test(+ 'past the window it says reconnecting, which reads as offline',+ () async {+ daemon.failSelects = firstConnectRetries + 1;+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses, firstConnectFor: Duration.zero);+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 10));+ expect(statuses, contains(ConnectionStatus.reconnecting));+ },+ );++ test('a connection that was up and dropped says reconnecting', () async {+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses);+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 2));+ statuses.clear();+ await daemon.sockets.single.close(1011, 'dropped');+ while (statuses.isEmpty) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ await untilReady(conn, const Duration(seconds: 5));+ expect(statuses.first, ConnectionStatus.reconnecting);+ expect(statuses.last, ConnectionStatus.connected);+ });++ test('a browser socket keeps the plain backoff and words', () async {+ daemon.failSelects = 1;+ final statuses = <ConnectionStatus>[];+ final conn = WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${daemon.server.port}',+ autonomousEnv: 'prod',+ machineId: 'm1',+ accessTokenProvider: (_, _) async => 'token',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: statuses.add,+ );+ conns.add(conn);+ await conn.connect();+ await untilReady(conn, const Duration(seconds: 5));+ expect(statuses, contains(ConnectionStatus.reconnecting));+ });++ test('closed while it waits to retry, it dials no more', () async {+ daemon.failSelects = 1;+ final statuses = <ConnectionStatus>[];+ final conn = local(statuses);+ await conn.connect();+ while (daemon.selects == 0) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ await Future<void>.delayed(const Duration(milliseconds: 100));+ await conn.close();+ final selects = daemon.selects;+ await Future<void>.delayed(const Duration(milliseconds: 800));+ expect(daemon.selects, selects);+ expect(conn.isReady, isFalse);+ expect(statuses.last, ConnectionStatus.disconnected);+ });++ test('one slow handshake holds up no other machine', () async {+ daemon.hanging.add('slow');+ final slowStatuses = <ConnectionStatus>[];+ final slow = local(slowStatuses, machineId: 'slow');+ final fast = local([], machineId: 'fast');+ await Future.wait([slow.connect(), fast.connect()]);+ await untilReady(fast, const Duration(milliseconds: 500));+ expect(slow.isReady, isFalse);+ expect(slowStatuses, isNot(contains(ConnectionStatus.reconnecting)));+ });++ test('a request asked during a failed first try is answered or fails, never stuck', () async {+ daemon.failSelects = 1;+ final conn = local([]);+ await conn.connect();+ final asked = conn.request(+ 'agents_list',+ timeout: const Duration(milliseconds: 300),+ );+ await expectLater(asked, throwsA(anything));+ });+}diff --git a/desktop/test/remote_connect_measurement_test.dart b/desktop/test/remote_connect_measurement_test.dartindex 119843461..665dddb1a 100644--- a/desktop/test/remote_connect_measurement_test.dart+++ b/desktop/test/remote_connect_measurement_test.dart@@ -216,17 +216,8 @@ void main() {),isFalse,);- for (var wait = 0; wait < 50; wait++) {- if (pooled.stateOf(mid)!.connectionStatus ==- ConnectionStatus.reconnecting) {- break;- }- await Future<void>.delayed(const Duration(milliseconds: 100));- }- expect(- pooled.stateOf(mid)!.connectionStatus,- ConnectionStatus.reconnecting,- );+ // A first connect redials saying connecting (test/first_connect_test.dart).+ expect(pooled.stateOf(mid)!.connectionStatus, ConnectionStatus.connecting);// Connect again, mid-redial: the socket is closed and replaced.expect(await pooled.connectTrusted(diff --git a/desktop/test/super_tab_first_read_test.dart b/desktop/test/super_tab_first_read_test.dartnew file mode 100644index 000000000..e32df32b7--- /dev/null+++ b/desktop/test/super_tab_first_read_test.dart@@ -0,0 +1,310 @@+import 'package:fake_async/fake_async.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/machine_status.dart';+import 'package:harness/super_tabs/reading.dart';++import 'support/super_tab_fixture.dart';++/// Reads through a daemon that may still be starting: while [failure] is set, every read fails so.+class _Daemon {+ _Daemon(this.server);+ final ConversationServer server;+ Object? failure;+ int states = 0;++ Future<Map<String, dynamic>> call(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) {+ if (method == 'GET' &&+ (path == '/api/super-tabs/tab/parts' ||+ path.startsWith('/api/super-tabs/tab/changes?'))) {+ states++;+ }+ final failing = failure;+ if (failing != null) return Future.error(failing);+ return server.request(method, path, body: body);+ }+}++const _unreachable = SuperTabFailure(+ 'BACKEND_UNREACHABLE',+ 'Could not reach the Harness backend.',+ statusCode: 502,+);++SuperTabController _controller(_Daemon daemon) => SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: daemon.call,+ save: daemon.server.save,+ reading: SuperTabReading.desktop,+);++void main() {+ test(+ 'a failed first read tries again in half a second, not at the next poll',+ () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ expect(daemon.states, 1);+ expect(c.stillConnecting, isTrue);+ daemon.failure = null;+ async.elapse(const Duration(milliseconds: 500));+ expect(daemon.states, 2);+ expect(c.snapshot, isNotNull);+ expect(c.backendUnreachable, isFalse);+ expect(c.stillConnecting, isFalse);+ expect(c.unreachableSince, isNull);+ c.dispose();+ });+ },+ );++ test('a Swarm not on screen retries as soon: it does not wait 15 s', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)+ ..away = true+ ..start();+ async.flushMicrotasks();+ daemon.failure = null;+ async.elapse(const Duration(milliseconds: 500));+ expect(c.snapshot, isNotNull);+ c.dispose();+ });+ });++ test('a daemon not answering at all is retried too, with no error shown', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())+ ..failure = StateError('connection refused');+ final c = _controller(daemon)..start();+ final errors = <String?>[];+ c.addListener(() => errors.add(c.error));+ async.elapse(const Duration(seconds: 2));+ expect(daemon.states, greaterThan(1));+ expect(c.loading, isTrue);+ daemon.failure = null;+ async.elapse(const Duration(seconds: 3));+ expect(c.snapshot, isNotNull);+ expect(errors.whereType<String>(), isEmpty);+ c.dispose();+ });+ });++ test(+ 'the retries end: past the grace it says what failed, and no Loading stays',+ () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.elapse(const Duration(seconds: 11));+ expect(c.error, _unreachable.message);+ expect(c.loading, isFalse);+ expect(c.stillConnecting, isTrue);+ // Quick tries spent, it reads no faster than its poll.+ final reads = daemon.states;+ async.elapse(const Duration(seconds: 9));+ expect(daemon.states, lessThanOrEqualTo(reads + 3));+ c.dispose();+ });+ },+ );++ test('a first load that failed for good still recovers on a later poll', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.elapse(const Duration(seconds: 20));+ daemon.failure = null;+ async.elapse(const Duration(seconds: 3));+ expect(c.snapshot, isNotNull);+ expect(c.error, isNull);+ expect(c.backendUnreachable, isFalse);+ c.dispose();+ });+ });++ test('a machine connecting joins the read, one read not two', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ daemon.failure = null;+ c.machineAvailable();+ async.flushMicrotasks();+ expect(c.snapshot, isNotNull);+ final reads = daemon.states;+ // The retry that was waiting finds it answered.+ async.elapse(const Duration(milliseconds: 600));+ expect(daemon.states, reads);+ c.dispose();+ });+ });++ test('access refused on the first read is final: no retry, nothing kept', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())+ ..failure = const SuperTabFailure(+ 'FORBIDDEN',+ 'You cannot read this Swarm.',+ statusCode: 403,+ );+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ expect(c.accessRevoked, isTrue);+ expect(c.stillConnecting, isFalse);+ final reads = daemon.states;+ daemon.failure = null;+ async.elapse(const Duration(seconds: 30));+ expect(daemon.states, reads);+ expect(c.snapshot, isNull);+ c.dispose();+ });+ });++ test('access lost while a retry waits: the retry reads nothing', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ daemon.failure = const SuperTabFailure(+ 'NOT_FOUND',+ 'Gone.',+ statusCode: 404,+ );+ async.elapse(const Duration(milliseconds: 500));+ expect(c.accessRevoked, isTrue);+ final reads = daemon.states;+ daemon.failure = null;+ async.elapse(const Duration(seconds: 12));+ expect(daemon.states, reads);+ expect(c.snapshot, isNull);+ c.dispose();+ });+ });++ test('closed or signed out while a retry waits: no read lands', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())..failure = _unreachable;+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ final reads = daemon.states;+ c.dispose();+ daemon.failure = null;+ async.elapse(const Duration(seconds: 12));+ expect(daemon.states, reads);+ });+ });++ test(+ 'a read that failed after a good one is reconnecting, with no quick retry',+ () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer());+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ expect(c.snapshot, isNotNull);+ daemon.failure = _unreachable;+ final reads = daemon.states;+ async.elapse(const Duration(seconds: 3));+ expect(c.backendUnreachable, isTrue);+ expect(c.stillConnecting, isFalse);+ expect(daemon.states, reads + 1);+ c.dispose();+ });+ },+ );++ test(+ 'a read before this computer has its row waits, with no error shown',+ () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())+ ..failure = const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your machines to open Swarm.',+ );+ final c = _controller(daemon)..start();+ final errors = <String?>[];+ c.addListener(() => errors.add(c.error));+ async.flushMicrotasks();+ expect(c.error, isNull);+ expect(c.loading, isTrue);+ expect(c.stillConnecting, isTrue);+ daemon.failure = null;+ async.elapse(const Duration(milliseconds: 500));+ expect(c.snapshot, isNotNull);+ expect(errors.whereType<String>(), isEmpty);+ c.dispose();+ });+ },+ );++ test('a computer that never gets its row says so once the grace ends', () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())+ ..failure = const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your machines to open Swarm.',+ );+ final c = _controller(daemon)..start();+ async.elapse(const Duration(seconds: 11));+ expect(c.error, 'Connect one of your machines to open Swarm.');+ expect(c.loading, isFalse);+ c.dispose();+ });+ });++ test(+ 'a Team computer is told at once: its refusal is no passing failure',+ () {+ fakeAsync((async) {+ final daemon = _Daemon(ConversationServer())+ ..failure = const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'This computer runs Swarm agents for a Harness Team account.',+ settled: true,+ );+ final c = _controller(daemon)..start();+ async.flushMicrotasks();+ expect(c.error, contains('Team account'));+ expect(c.loading, isFalse);+ c.dispose();+ });+ },+ );++ testWidgets('the pill says Connecting until a read has been answered', (+ tester,+ ) async {+ Widget pill({required bool connecting}) => MaterialApp(+ home: Scaffold(+ body: Center(+ child: SuperTabMachinesPill(+ connecting: connecting,+ reconnectingFor: const Duration(seconds: 4),+ ),+ ),+ ),+ );+ await tester.pumpWidget(pill(connecting: true));+ expect(find.text('Connecting · 4s'), findsOneWidget);+ expect(+ find.bySemanticsLabel('Machines: connecting, for 4s'),+ findsOneWidget,+ );+ await tester.pumpWidget(pill(connecting: false));+ expect(find.text('Reconnecting · 4s'), findsOneWidget);+ expect(+ find.bySemanticsLabel('Machines: reconnecting, for 4s'),+ findsOneWidget,+ );+ });+}diff --git a/desktop/test/super_tab_reading_workspace_test.dart b/desktop/test/super_tab_reading_workspace_test.dartindex 72b870f7e..9688d343c 100644--- a/desktop/test/super_tab_reading_workspace_test.dart+++ b/desktop/test/super_tab_reading_workspace_test.dart@@ -8,6 +8,7 @@ import 'package:harness/state/pane_layout_store.dart';import 'package:harness/viewer/viewer_key_store.dart';import 'package:harness/viewer/viewer_services.dart';import 'package:harness/state/workspace_chrome.dart';+import 'package:harness/super_tabs/reading.dart';import 'package:harness/super_tabs/workspace.dart';import 'package:harness/web/shell/web_chrome.dart';@@ -112,6 +113,53 @@ Future<void> _mountApp(}void main() {+ group('Desktop: the daemon coming up reads the Swarm at once', () {+ late SuperTabLaunchFixture f;++ Future<void> opened() async {+ f = SuperTabLaunchFixture(local: true);+ f.app.superTabs.reading = SuperTabReading.desktop;+ f.app.machineStates['m']!.connectionStatus =+ ConnectionStatus.disconnected;+ f.app.connectionStatusForTest('m', ConnectionStatus.disconnected);+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ }++ test('when this computer connects', () async {+ await opened();+ final before = _stateReads(f);+ f.app.connectionStatusForTest('m', ConnectionStatus.connected);+ await Future<void>.delayed(Duration.zero);+ expect(_stateReads(f), before + 1);+ // Still connected: another status says nothing new.+ f.app.connectionStatusForTest('m', ConnectionStatus.connected);+ await Future<void>.delayed(Duration.zero);+ expect(_stateReads(f), before + 1);+ f.app.superTabs.dispose();+ });++ test('and not while it is only connecting', () async {+ await opened();+ final before = _stateReads(f);+ f.app.connectionStatusForTest('m', ConnectionStatus.connecting);+ await Future<void>.delayed(Duration.zero);+ expect(_stateReads(f), before);+ f.app.superTabs.dispose();+ });++ test('when its backend comes back', () async {+ await opened();+ f.app.status = AppStatus.authenticated;+ f.app.noteBackendOnlineForTest(false);+ final before = _stateReads(f);+ f.app.noteBackendOnlineForTest(true);+ await Future<void>.delayed(Duration.zero);+ expect(_stateReads(f), before + 1);+ f.app.superTabs.dispose();+ });+ });+testWidgets('Desktop: a Swarm tab not shown, or a hidden app, polls every 15 s',(tester) async {diff --git a/desktop/test/text_field_editing_keys_test.dart b/desktop/test/text_field_editing_keys_test.dartnew file mode 100644index 000000000..20701b47d--- /dev/null+++ b/desktop/test/text_field_editing_keys_test.dart@@ -0,0 +1,566 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shortcuts/app_keymap.dart';+import 'package:harness/shortcuts/keymap.dart';+import 'package:harness/shortcuts/keymap_host.dart';+import 'package:harness/shortcuts/text_editing_keys.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/widgets/terminal_composer.dart';++import 'keymap_host_test.dart'+ show MemoryKeymap, key, liveComposerSession, terminalKeymapHost;+import 'support/super_tab_fixture.dart';++/// ⌘← is "focus the pane to the left" and ⇧⌘← "move this pane", but with the+/// caret in a text field they are the line start and a selection to it. The+/// window's keymap runs before the field, so each editing key has to be given+/// back to it.+/// Offsets only: a move may leave the caret's affinity upstream or downstream.+Matcher caret(int offset) => isA<TextSelection>()+ .having((s) => s.isCollapsed, 'collapsed', true)+ .having((s) => s.baseOffset, 'offset', offset);+Matcher range(int base, int extent) => isA<TextSelection>()+ .having((s) => s.baseOffset, 'base', base)+ .having((s) => s.extentOffset, 'extent', extent);++void main() {+ const text = 'hello world there';+ final mac = TargetPlatformVariant.only(TargetPlatform.macOS);+ final windows = TargetPlatformVariant.only(TargetPlatform.windows);++ group('which strokes a text field keeps', () {+ KeyStroke s(String source) => KeyStroke.parse(source);+ bool keeps(String stroke, TargetPlatform platform, {bool hasText = true}) =>+ textFieldKeepsStroke(s(stroke), platform: platform, hasText: hasText);++ test('macOS word, line and text moves, with and without Shift', () {+ for (final stroke in [+ 'alt+left',+ 'alt+right',+ 'alt+shift+left',+ 'alt+shift+right',+ 'cmd+left',+ 'cmd+right',+ 'cmd+up',+ 'cmd+down',+ 'cmd+shift+left',+ 'cmd+shift+right',+ 'cmd+shift+up',+ 'cmd+shift+down',+ 'alt+backspace',+ 'cmd+backspace',+ 'ctrl+a',+ 'ctrl+e',+ ]) {+ expect(keeps(stroke, TargetPlatform.macOS), isTrue, reason: stroke);+ }+ });++ test('macOS pane and tab keys are never kept', () {+ for (final stroke in [+ 'cmd+h',+ 'cmd+j',+ 'cmd+k',+ 'cmd+l',+ 'cmd+alt+left',+ 'cmd+alt+right',+ 'cmd+t',+ 'cmd+shift+backspace',+ 'ctrl+shift+a',+ 'ctrl+w',+ ]) {+ expect(keeps(stroke, TargetPlatform.macOS), isFalse, reason: stroke);+ }+ });++ test('the ⌘-arrows are kept only when the box has text', () {+ for (final stroke in ['cmd+left', 'cmd+shift+down']) {+ expect(+ keeps(stroke, TargetPlatform.macOS, hasText: false),+ isFalse,+ reason: stroke,+ );+ }+ expect(keeps('alt+left', TargetPlatform.macOS, hasText: false), isTrue);+ });++ test('Ctrl+K kills the line on macOS only, and only unmodified', () {+ expect(+ textFieldKillsLine(s('ctrl+k'), platform: TargetPlatform.macOS),+ isTrue,+ );+ for (final stroke in ['cmd+k', 'ctrl+shift+k', 'ctrl+alt+k', 'k']) {+ expect(+ textFieldKillsLine(s(stroke), platform: TargetPlatform.macOS),+ isFalse,+ reason: stroke,+ );+ }+ expect(+ textFieldKillsLine(s('ctrl+k'), platform: TargetPlatform.windows),+ isFalse,+ );+ });++ test('Windows and Linux word moves, Home/End and word deletes', () {+ for (final platform in [TargetPlatform.windows, TargetPlatform.linux]) {+ for (final stroke in [+ 'ctrl+left',+ 'ctrl+right',+ 'ctrl+shift+left',+ 'home',+ 'end',+ 'ctrl+home',+ 'ctrl+shift+end',+ 'shift+home',+ 'ctrl+backspace',+ 'ctrl+delete',+ ]) {+ expect(keeps(stroke, platform), isTrue, reason: '$platform $stroke');+ }+ // Alt+arrows are Windows Terminal's pane keys; they stay with the app.+ for (final stroke in ['alt+left', 'alt+shift+right', 'ctrl+t']) {+ expect(keeps(stroke, platform), isFalse, reason: '$platform $stroke');+ }+ }+ });+ });++ group('the message box and the thread reply box', () {+ late SuperTabController shown;++ /// Takes the view down and settles the controller's draft save before the+ /// test ends, as the chat's own tests do.+ void testBox(+ String description,+ Future<void> Function(WidgetTester tester) body, {+ required TestVariant<Object?> variant,+ }) => testWidgets(description, (tester) async {+ await body(tester);+ await tester.pumpWidget(const SizedBox());+ await shown.flush();+ shown.dispose();+ }, variant: variant);++ Future<(MemoryKeymap, List<String>)> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetDevicePixelRatio);+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ await c.refresh();+ final map = MemoryKeymap();+ final ran = <String>[];+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: KeymapProvider(+ keymap: map,+ child: KeymapHost(+ keymap: map,+ enabled: () => true,+ actions: {+ for (final id in [+ 'pane.focus_left',+ 'pane.focus_right',+ 'pane.focus_above',+ 'pane.focus_below',+ 'pane.move_left',+ 'pane.move_right',+ 'pane.move_up',+ 'pane.move_down',+ ])+ id: () => ran.add(id),+ },+ child: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ shown = c;+ return (map, ran);+ }++ final boxes = {+ 'message box': (WidgetTester tester) async {+ final box = find.byKey(const ValueKey('super-message-composer'));+ return box;+ },+ 'thread reply box': (WidgetTester tester) async {+ await tester.tap(+ find.byKey(const ValueKey('super-thread-line-message-1')),+ );+ await tester.pumpAndSettle();+ return find.byKey(const ValueKey('super-thread-composer'));+ },+ };++ /// A root with one reply, so the thread line is there to open.+ ConversationServer server() {+ final server = ConversationServer()..threads = true;+ server.append('Should we do thread replies?');+ server.append('Yes, like Slack.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ return server;+ }++ for (final entry in boxes.entries) {+ Future<(Finder, TextEditingController, List<String>)> focused(+ WidgetTester tester,+ String value,+ ) async {+ final (_, ran) = await show(tester, server());+ final box = await entry.value(tester);+ await tester.tap(box);+ await tester.enterText(box, value);+ await tester.pump();+ final controller = tester.widget<TextField>(box).controller!;+ return (box, controller, ran);+ }++ testBox('${entry.key}: macOS editing keys reach the text', (+ tester,+ ) async {+ final (_, field, ran) = await focused(tester, text);+ TextSelection sel() => field.selection;++ await key(tester, LogicalKeyboardKey.arrowLeft, alt: true);+ expect(sel(), caret(12));+ await key(tester, LogicalKeyboardKey.arrowLeft, alt: true);+ expect(sel(), caret(6));+ await key(tester, LogicalKeyboardKey.arrowRight, alt: true);+ expect(sel(), caret(11));++ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ expect(sel(), caret(0));+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true);+ expect(sel(), caret(text.length));+ await key(tester, LogicalKeyboardKey.arrowUp, cmd: true);+ expect(sel(), caret(0));+ await key(tester, LogicalKeyboardKey.arrowDown, cmd: true);+ expect(sel(), caret(text.length));++ // Shift selects: ⇧⌘← would have moved the pane.+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true, shift: true);+ expect(sel(), range(text.length, 0));+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true);+ await key(tester, LogicalKeyboardKey.arrowLeft, alt: true, shift: true);+ expect(sel(), range(text.length, 12));++ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true);+ await key(tester, LogicalKeyboardKey.backspace, alt: true);+ expect(field.text, 'hello world ');+ await key(tester, LogicalKeyboardKey.backspace, cmd: true);+ expect(field.text, '');++ field.value = const TextEditingValue(+ text: text,+ selection: TextSelection.collapsed(offset: 5),+ );+ await tester.pump();+ await key(tester, LogicalKeyboardKey.keyE, ctrl: true);+ expect(sel(), caret(text.length));+ await key(tester, LogicalKeyboardKey.keyA, ctrl: true);+ expect(sel(), caret(0));+ field.selection = const TextSelection.collapsed(offset: 5);+ await tester.pump();+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);+ expect(field.text, 'hello');++ expect(ran, isEmpty, reason: 'no pane moved while typing');+ }, variant: mac);++ testBox('${entry.key}: Windows editing keys reach the text', (+ tester,+ ) async {+ final (_, field, ran) = await focused(tester, text);+ TextSelection sel() => field.selection;++ await key(tester, LogicalKeyboardKey.arrowLeft, ctrl: true);+ expect(sel(), caret(12));+ await key(tester, LogicalKeyboardKey.home);+ expect(sel(), caret(0));+ await key(tester, LogicalKeyboardKey.end);+ expect(sel(), caret(text.length));+ await key(+ tester,+ LogicalKeyboardKey.arrowLeft,+ ctrl: true,+ shift: true,+ );+ expect(sel(), range(text.length, 12));+ await key(tester, LogicalKeyboardKey.end);+ await key(tester, LogicalKeyboardKey.backspace, ctrl: true);+ expect(field.text, 'hello world ');+ expect(ran, isEmpty);+ }, variant: windows);++ testBox(+ '${entry.key}: ⌘-arrows still move panes while the box is empty',+ (tester) async {+ final (_, field, ran) = await focused(tester, '');+ expect(field.text, isEmpty);+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ await key(tester, LogicalKeyboardKey.arrowDown, cmd: true);+ await key(+ tester,+ LogicalKeyboardKey.arrowRight,+ cmd: true,+ shift: true,+ );+ expect(ran, [+ 'pane.focus_left',+ 'pane.focus_below',+ 'pane.move_right',+ ]);+ },+ variant: mac,+ );++ testBox('${entry.key}: ⌘H/J/K/L still focus panes with text in the box', (+ tester,+ ) async {+ final (_, _, ran) = await focused(tester, text);+ await key(tester, LogicalKeyboardKey.keyH, cmd: true);+ await key(tester, LogicalKeyboardKey.keyL, cmd: true);+ expect(ran, ['pane.focus_left', 'pane.focus_right']);+ }, variant: mac);+ }+ });++ group('the terminal composer', () {+ testWidgets('macOS editing keys reach the line', (tester) async {+ final map = MemoryKeymap();+ final focus = FocusNode();+ final session = await liveComposerSession();+ final ran = <String>[];+ await tester.pumpWidget(+ terminalKeymapHost(map, {+ 'pane.focus_left': () => ran.add('focus_left'),+ 'pane.move_left': () => ran.add('move_left'),+ }, TerminalComposer(session: session, focusNode: focus)),+ );+ focus.requestFocus();+ await tester.pump();+ await tester.enterText(find.byType(TextField), text);+ final field = tester+ .widget<TextField>(find.byType(TextField))+ .controller!;+ field.selection = const TextSelection.collapsed(offset: text.length);+ await tester.pump();++ await key(tester, LogicalKeyboardKey.arrowLeft, alt: true);+ expect(field.selection, caret(12));+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ expect(field.selection, caret(0));+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true, shift: true);+ expect(field.selection, range(0, text.length));+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true);+ await key(tester, LogicalKeyboardKey.backspace, alt: true);+ expect(field.text, 'hello world ');+ await key(tester, LogicalKeyboardKey.keyA, ctrl: true);+ expect(field.selection, caret(0));+ field.selection = const TextSelection.collapsed(offset: 5);+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);+ expect(field.text, 'hello');+ expect(ran, isEmpty);+ await tester.pumpWidget(const SizedBox());+ session.dispose();+ focus.dispose();+ map.dispose();+ }, variant: mac);++ testWidgets('⌘← focuses the pane when the composer is empty', (+ tester,+ ) async {+ final map = MemoryKeymap();+ final focus = FocusNode();+ final session = await liveComposerSession();+ final ran = <String>[];+ await tester.pumpWidget(+ terminalKeymapHost(map, {+ 'pane.focus_left': () => ran.add('focus_left'),+ }, TerminalComposer(session: session, focusNode: focus)),+ );+ focus.requestFocus();+ await tester.pump();+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ expect(ran, ['focus_left']);+ await tester.pumpWidget(const SizedBox());+ session.dispose();+ focus.dispose();+ map.dispose();+ }, variant: mac);+ });++ group('where the field does not own the keys', () {+ Future<(MemoryKeymap, List<String>)> host(+ WidgetTester tester,+ Widget field, {+ String? bindings,+ KeymapContext? region,+ Map<String, VoidCallback>? local,+ }) async {+ final map = MemoryKeymap();+ if (bindings != null) map.apply(bindings);+ final ran = <String>[];+ Widget child = Material(child: field);+ if (region != null) {+ child = KeymapRegion(contextKind: region, actions: local, child: child);+ }+ await tester.pumpWidget(+ MaterialApp(+ home: KeymapProvider(+ keymap: map,+ child: KeymapHost(+ keymap: map,+ enabled: () => true,+ actions: {+ 'pane.focus_left': () => ran.add('pane.focus_left'),+ 'pane.zoom': () => ran.add('pane.zoom'),+ },+ child: child,+ ),+ ),+ ),+ );+ await tester.pump();+ addTearDown(map.dispose);+ return (map, ran);+ }++ testWidgets('read-only text keeps the pane keys', (tester) async {+ // Selectable text is a read-only field: it has no caret to move, so ⌘←+ // is still "focus the pane to the left" and Ctrl+K is still the app's.+ final (_, ran) = await host(+ tester,+ const SelectableText(text, autofocus: true),+ bindings: '{"bindings":[{"keys":"ctrl+k","command":"pane.zoom"}]}',+ );+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);+ expect(ran, ['pane.focus_left', 'pane.zoom']);+ }, variant: mac);++ testWidgets('Ctrl+K does not cut into text being composed', (tester) async {+ final controller = TextEditingController.fromValue(+ const TextEditingValue(+ text: 'hello world',+ selection: TextSelection.collapsed(offset: 5),+ composing: TextRange(start: 0, end: 5),+ ),+ );+ addTearDown(controller.dispose);+ await host(tester, TextField(controller: controller, autofocus: true));+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);+ expect(controller.text, 'hello world');+ }, variant: mac);++ for (final kind in [KeymapContext.picker, KeymapContext.project]) {+ testWidgets('a ${kind.name} search field keeps Ctrl+K as "previous"', (+ tester,+ ) async {+ final controller = TextEditingController(text: 'draft');+ addTearDown(controller.dispose);+ var previous = 0;+ await host(+ tester,+ TextField(controller: controller, autofocus: true),+ region: kind,+ local: {'picker.previous': () => previous++},+ );+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);+ expect(previous, 1);+ expect(controller.text, 'draft');+ }, variant: mac);+ }++ testWidgets('a chord under way finishes on an editing key', (tester) async {+ final controller = TextEditingController(text: text);+ addTearDown(controller.dispose);+ final (_, ran) = await host(+ tester,+ TextField(controller: controller, autofocus: true),+ bindings: '{"bindings":[{"keys":"cmd+alt+shift+y alt+left","command":"pane.zoom"}]}',+ );+ controller.selection = const TextSelection.collapsed(offset: 17);+ await key(+ tester,+ LogicalKeyboardKey.keyY,+ cmd: true,+ alt: true,+ shift: true,+ );+ await key(tester, LogicalKeyboardKey.arrowLeft, alt: true);+ expect(ran, ['pane.zoom']);+ expect(controller.selection, caret(17), reason: 'the caret stayed');+ }, variant: mac);+ });++ testWidgets('pane and tab keys work with focus outside a text field', (+ tester,+ ) async {+ final map = MemoryKeymap();+ final ran = <String>[];+ final focus = FocusNode();+ await tester.pumpWidget(+ MaterialApp(+ home: KeymapProvider(+ keymap: map,+ child: KeymapHost(+ keymap: map,+ enabled: () => true,+ actions: {+ for (final id in [+ 'pane.focus_left',+ 'pane.move_left',+ 'pane.focus_above',+ 'swarm.next',+ 'swarm.previous',+ ])+ id: () => ran.add(id),+ },+ child: Material(+ child: TextButton(+ focusNode: focus,+ autofocus: true,+ onPressed: () {},+ child: const Text('A pane'),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true);+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true, shift: true);+ await key(tester, LogicalKeyboardKey.keyK, cmd: true);+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true, alt: true);+ await key(tester, LogicalKeyboardKey.arrowLeft, cmd: true, alt: true);+ expect(ran, [+ 'pane.focus_left',+ 'pane.move_left',+ 'pane.focus_above',+ 'swarm.next',+ 'swarm.previous',+ ]);+ }, variant: mac);+}diff --git a/desktop/test/ws_conn_test.dart b/desktop/test/ws_conn_test.dartindex 86efc7a22..77e870a2a 100644--- a/desktop/test/ws_conn_test.dart+++ b/desktop/test/ws_conn_test.dart@@ -697,7 +697,7 @@ void main() {request.response.statusCode = HttpStatus.serviceUnavailable;await request.response.close();});- var reconnecting = 0;+ var dials = 0;conn = WsConn(wsBaseUrl: 'wss://unused.example',autonomousEnv: 'prod',@@ -706,7 +706,10 @@ void main() {onAuthFailure: (_) {},onEvent: (_) {},onStatus: (status) {- if (status == ConnectionStatus.reconnecting) reconnecting++;+ if (status == ConnectionStatus.reconnecting ||+ status == ConnectionStatus.connecting) {+ dials++;+ }},transportKind: WsTransportKind.localPlaintext,allowLocalTcpFixture: true,@@ -716,7 +719,7 @@ void main() {await conn!.connect();await Future<void>.delayed(const Duration(milliseconds: 650));expect(- reconnecting,+ dials,greaterThanOrEqualTo(4),reason: 'backoff would allow one',);@@ -747,7 +750,11 @@ void main() {await Future<void>.delayed(const Duration(milliseconds: 250));expect(failures, hasLength(1));expect(failures.single, startsWith('4403:'));- expect(statuses, contains(ConnectionStatus.reconnecting));+ // Dialled again, on its first connect's quick tries (test/first_connect_test.dart).+ expect(+ statuses.where((status) => status == ConnectionStatus.connecting),+ hasLength(greaterThan(1)),+ );expect(conn!.isClosed, isFalse);});diff --git a/desktop/tool/measure_connect.dart b/desktop/tool/measure_connect.dartnew file mode 100644index 000000000..0184226c2--- /dev/null+++ b/desktop/tool/measure_connect.dart@@ -0,0 +1,132 @@+// ignore_for_file: avoid_print+// Times what opening Desktop waits for, against this computer's running daemon:+// the machine list, the local socket, and a cold relay dial to every other machine.+//+// dart run tool/measure_connect.dart [rounds]+//+// It reads and selects only: each remote select takes the daemon's isolated relay path, which+// dials afresh and leaves the windows' live sessions alone. It prints short machine ids and+// timings, never names, tokens or anything a machine answers.+import 'dart:async';+import 'dart:convert';+import 'dart:io';++const _protocol = 1;+const _givesUpAfter = Duration(seconds: 20);++Future<void> main(List<String> args) async {+ final rounds = args.isEmpty ? 1 : int.parse(args.first);+ final home = Platform.environment['HOME']!;+ final socket = '$home/.harness/cli/data/daemon-18473.sock';+ HttpClient client() => HttpClient()+ ..connectionFactory = (uri, proxyHost, proxyPort) => Socket.startConnect(+ InternetAddress(socket, type: InternetAddressType.unix),+ 0,+ );++ final http = client();+ final status = await _getJson(http, '/api/status');+ final local = status.value['machineId'] as String?;+ print('status ${status.ms} ms');+ final listed = await _getJson(http, '/api/machines');+ print('machines ${listed.ms} ms');+ http.close();+ final raw = listed.value['data'];+ final rows = (raw is Map ? raw['machines'] : raw) as List;++ for (var round = 1; round <= rounds; round++) {+ print('round $round: every machine at once, as opening does');+ final clock = Stopwatch()..start();+ final results = await Future.wait([+ for (final row in rows)+ _select(+ client,+ row['machineId'] as String,+ row['status'] as String?,+ isLocal: row['machineId'] == local,+ ),+ ]);+ for (final result in results) {+ print(result);+ }+ print('all answered in ${clock.elapsedMilliseconds} ms');+ }+}++Future<({int ms, Map<String, dynamic> value})> _getJson(+ HttpClient http,+ String path,+) async {+ final clock = Stopwatch()..start();+ final request = await http.getUrl(Uri.parse('http://localhost$path'));+ final response = await request.close();+ final body = await response.transform(utf8.decoder).join();+ final decoded = jsonDecode(body) as Map<String, dynamic>;+ final data = decoded['data'];+ return (+ ms: clock.elapsedMilliseconds,+ value: path == '/api/status' && data is Map<String, dynamic>+ ? data+ : decoded,+ );+}++Future<String> _select(+ HttpClient Function() client,+ String machineId,+ String? status, {+ required bool isLocal,+}) async {+ final label =+ '${machineId.substring(0, 8)} ${isLocal ? 'this computer' : 'remote'} ($status)';+ final clock = Stopwatch()..start();+ final WebSocket ws;+ try {+ ws = await WebSocket.connect(+ 'ws://localhost/api/local-ws',+ customClient: client(),+ );+ } catch (error) {+ return '$label: socket failed after ${clock.elapsedMilliseconds} ms (${error.runtimeType})';+ }+ final opened = clock.elapsedMilliseconds;+ final answered = Completer<String>();+ void finish(String text) {+ if (!answered.isCompleted) answered.complete(text);+ }++ final sub = ws.listen(+ (raw) {+ if (raw is! String) return;+ final frame = jsonDecode(raw) as Map<String, dynamic>;+ final payload = frame['payload'];+ if (frame['type'] == 'connected' &&+ payload is Map &&+ payload['machineId'] == machineId) {+ finish('connected ${clock.elapsedMilliseconds} ms');+ }+ },+ onDone: () => finish(+ 'closed ${clock.elapsedMilliseconds} ms (${ws.closeCode} ${ws.closeReason})',+ ),+ onError: (_) => finish('error ${clock.elapsedMilliseconds} ms'),+ );+ ws.add(+ jsonEncode({+ 'type': 'machine_select',+ 'payload': {+ 'machineId': machineId,+ 'localProtocolVersion': _protocol,+ 'tool': true,+ if (!isLocal) 'relayIsolation': true,+ },+ }),+ );+ final outcome = await answered.future.timeout(+ _givesUpAfter,+ onTimeout: () => 'no answer in ${_givesUpAfter.inSeconds} s',+ );+ await sub.cancel();+ await ws.close();+ return '$label: socket $opened ms, $outcome';+}diff --git a/docs/plans/2026-11-02-relay-engine-routes-plan.md b/docs/plans/2026-11-02-relay-engine-routes-plan.mdnew file mode 100644index 000000000..4d37971f4--- /dev/null+++ b/docs/plans/2026-11-02-relay-engine-routes-plan.md@@ -0,0 +1,54 @@+# The subscription relay forwards only the engines' calls++Audit M4 (`docs/security/2026-11-02-team-account-boundary.md`, PR #2538): `lib/subscriptionRelay.ts` forwarded any path+under `/claude/` or `/codex/`, for any method, with the owner's vendor sign-in. A guest or Team agent holding a relay+token could therefore reach account endpoints, not only model calls, and an encoded `..%2f` went to the vendor as sent.++## Change++- **Routes.** Only these are forwarded; every other path is 404, a listed path with another method is 405:++ | Provider | Method | Path (after `/claude` or `/codex`) | Who sends it |+ | --- | --- | --- | --- |+ | claude | POST | `/v1/messages` | Claude Code's model calls (`?beta=true`) |+ | claude | POST | `/v1/messages/count_tokens` | Claude Code's token counts |+ | claude | GET | `/v1/models` | Claude Code's model list |+ | codex | POST | `/responses` | Codex's Responses calls (`wire_api="responses"`) |+ | codex | GET | `/models` | `team/relay.ts` `prepareCodexHome`, Codex's model list |++ Read from Claude Code 2.1.312, Codex 0.165 and our own callers.+- **Exact match on the path as sent.** The raw request path (before `?`) must equal a listed route byte for byte, so+ `%2f`, `%2e`, `%5c`, `\`, `//`, `.` and `..` segments are all refused, before the body is read and before the owner's+ sign-in is read. The query string is still passed through (`?beta=true`, `?client_version=`): it cannot change the path.+- **Revoke ends what is in flight.** `revoke(guest)` aborts that guest's open requests: a stream stops, and a request still+ reading its body or the owner's sign-in answers 401 instead of being sent.+- **Log.** A refusal is one owner-log line with the method, the status and the guest's fingerprint; the refused path is+ not logged (it is the guest's text).++Not here: a per-launch token (M2's task; `mintToken` already gives each launch its own token).++## Design++- growth: N/A because the route list is a constant; the per-guest in-flight set deletes each entry when its request ends.+- concurrency: N/A because the relay is one Node process; the in-flight set is touched only on its event loop.+- read cost: N/A because no data is stored or read beyond one request.+- scale: N/A because the check is a constant lookup per request.+- compatibility: an engine version that calls a new path gets 404 until the route is added; the refusal is in the+ owner's log, so it shows.+- migration + rollback: N/A because nothing is stored; revert the commit.+- audience: the relay (the owner's daemon) enforces it, not the guest's engine.+- identity: unchanged: the owner's sign-in is spent only for listed engine calls.+- failure: a refused call answers 404/405 with a relay error body and an owner-log line.+- platforms: macOS and Linux, wherever the daemon runs the relay.++## Tests (each fails on main, except the first, which keeps the engines working)++- An engine path passes for each listed route.+- An account path (`/claude/v1/organizations/...`, `/codex/accounts/...`, `/claude/api/oauth/...`) is 404 and never reaches+ the vendor.+- `..%2f`, `%2e%2e`, `%5c`, `//` and dot segments are 404 and never reach the vendor.+- A listed path with another method is 405.+- A guest revoked mid-stream: the stream is cut (an error, not a clean end), and another guest is untouched.+- A guest revoked while its request waits on the owner's sign-in, on the vendor's first answer, or on the refresh after a+ 401: it gets 401, and nothing more is sent upstream.+- A refusal closes the connection, so the next request on a reused socket is not reset.diff --git a/docs/plans/2026-11-02-text-field-editing-keys-plan.md b/docs/plans/2026-11-02-text-field-editing-keys-plan.mdnew file mode 100644index 000000000..b7cf27b3f--- /dev/null+++ b/docs/plans/2026-11-02-text-field-editing-keys-plan.md@@ -0,0 +1,58 @@+# Text-field editing keys Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** With the caret in a Desktop text field, the standard editing keys (word, line and text moves, selects, word and line deletes) edit the text instead of running an app shortcut.++**Architecture:** `KeymapHost` (`desktop/lib/shortcuts/keymap_host.dart`) is an early key handler, so it sees every key before the focused field and turns ⌘-arrows into pane focus and ⇧⌘-arrows into pane moves. A new pure predicate, `textFieldKeepsStroke`, says which strokes a field keeps for itself; the host returns `ignored` for them when the primary focus sits under an `EditableTextState`, so Flutter's own text-editing shortcuts serve them. Only the ⌘-arrows depend on the field holding text: an empty box keeps pane focus and pane moves.++**Tech Stack:** Flutter 3.47.2 (Desktop `desktop/`), `flutter_test`.++**Spec:** Task #2010 brief (Scholes's Buddy 11-02): Mac Option+Left/Right by word; Cmd+Left/Right line start/end; Cmd+Up/Down text start/end; Shift selects; Option+Backspace deletes a word; Cmd+Backspace to line start; Ctrl+A/E/K. Windows Ctrl+arrows by word, Home/End, Ctrl+Backspace. Pane focus stays on Cmd+H/J/K/L and on the arrows when the box is empty or not focused; tab switching on Cmd+Option+arrows unchanged. Out: keymap editing, emoji, IME.++## Global Constraints++- Desktop only; no change to `app_shortcuts.dart` bindings, the keymap file format or the native menu.+- Never run a test that signs the Mac out of the real CLI; tests use `MemoryKeymap` and fake sessions.+- Format only the files touched (`dart format <files>`), never a folder.+- Picker and project menu contexts keep their own keys (`ctrl+j/k/n/p` navigate there).+- IME composition keeps today's path (`composing` cancels dispatch).++## Review Focus++1. Empty box: ⌘←/→/↑/↓ and ⇧⌘-arrows still focus and move panes (test `⌘-arrows still move panes while the box is empty`, both boxes plus the terminal composer).+2. A chord already pending (a prefix pressed first) must finish, not be cut by an editing key (`!_dispatch.hasPending` guard in the host).+3. Picker and project menu search fields still take Ctrl+K/J as "up/down" (context guard; covered by the existing `keymap_host_test.dart` picker tests, which must stay green).+4. Pane focus on ⌘H/J/K/L and tabs on ⌘⌥-arrows with text in the box (tests `⌘H/J/K/L still focus panes with text in the box` and `pane and tab keys work with focus outside a text field`).+5. Windows/Linux: Alt+arrows stay pane keys with text in the box (predicate test `Windows and Linux word moves...`).++---++### Task 1: The predicate++**Files:**+- Create: `desktop/lib/shortcuts/text_editing_keys.dart`+- Test: `desktop/test/text_field_editing_keys_test.dart` (group `which strokes a text field keeps`)++**Interfaces:**+- Produces: `bool textFieldKeepsStroke(KeyStroke? stroke, {required TargetPlatform platform, required bool hasText})`.++- [ ] **Step 1: Write the failing tests** — macOS list kept (`alt+left`, `cmd+shift+up`, `alt+backspace`, `cmd+backspace`, `ctrl+a/e/k`…), never kept (`cmd+h/j/k/l`, `cmd+alt+left/right`, `cmd+t`, `cmd+shift+backspace`, `ctrl+w`), ⌘-arrows only with `hasText`, Windows/Linux list (`ctrl+left`, `home`, `end`, `ctrl+backspace`…) and `alt+left` not kept.+- [ ] **Step 2: Run it, expect a compile failure** — `flutter test test/text_field_editing_keys_test.dart`.+- [ ] **Step 3: Implement the predicate** as a pure function of platform, modifiers and key name.+- [ ] **Step 4: Run it, expect PASS.**++### Task 2: The host gives the keys back++**Files:**+- Modify: `desktop/lib/shortcuts/keymap_host.dart` (`_handle`, before the `composing` check)+- Test: `desktop/test/text_field_editing_keys_test.dart` (groups `the message box and the thread reply box`, `the terminal composer`, and the outside-a-field test)++**Interfaces:**+- Consumes: `textFieldKeepsStroke`, `KeymapRegion.contextKind`, the `EditableTextState` already read for `value`.++- [ ] **Step 1: Write the failing widget tests** — for the Super Tab message box (`super-message-composer`), the thread reply box (`super-thread-composer`) and `TerminalComposer`: each listed key reaches the field (selection or text asserted), and no `pane.*` action runs; empty box keeps `pane.focus_left`, `pane.focus_below`, `pane.move_right`; ⌘H/L still run with text; focus on a button still runs pane, move and tab actions.+- [ ] **Step 2: Run them on main's host, expect FAIL** (record the assertion lines for the PR comment).+- [ ] **Step 3: Return `KeyEventResult.ignored`** when `value != null`, no chord is pending, the context is neither `picker` nor `project`, and the predicate keeps the stroke.+- [ ] **Step 4: Run the new file and `keymap_host_test.dart`, `keymap_dispatch_test.dart`, `terminal_composer_test.dart`, `windows_shortcuts_test.dart`, `shortcuts_test.dart`, expect PASS.**+- [ ] **Step 5: Commit** — `git add` the four files by name (no `node_modules`, no symlinks), then commit and open the PR with the privacy/concurrency/lifecycle checklist.diff --git a/docs/plans/2026-11-02-tmux-env-off-argv-plan.md b/docs/plans/2026-11-02-tmux-env-off-argv-plan.mdnew file mode 100644index 000000000..94bfd6c71--- /dev/null+++ b/docs/plans/2026-11-02-tmux-env-off-argv-plan.md@@ -0,0 +1,59 @@+# Session variables never on tmux's command line (audit M2)++Task #2017, from the Team account audit (`docs/security/2026-11-02-team-account-boundary.md`, M2, on PR #2538).++## Problem++`TmuxBackend.create` passed a session's variables as `new-session -e KEY=VALUE`, and `respawn` as+`respawn-pane -e KEY=VALUE`. Every account on a Mac can read every process's command line (`ps -axww`).++- When `new-session` starts the tmux server, the server keeps that command line as its title for its whole+ life. On the Mac Studio the Team account's tmux server showed its `ANTHROPIC_AUTH_TOKEN` to every account.+- Even with a server already running, the client lives for milliseconds with the value on its command line:+ a loop of `ps` catches it.++## Change++When a create or respawn carries variables, the backend runs `tmux start-server ; source-file -` and writes+the same command list on the client's standard input. The command line holds no value, so neither the client+nor a server it starts shows one. Nothing is written to disk, so a crash leaves no file behind.++- The list is written in tmux's command syntax: each word single-quoted, a `'` closed and given in double+ quotes, and a newline or carriage return given as `"\n"`/`"\r"`. Measured on tmux 3.7: a raw newline in a+ single-quoted word lost a following line that started with `#`. Quotes, `$`, `~`, `#{…}`, `%if`, `;`,+ braces, control characters and a 200 KB value all came back unchanged.+- `start-server` first, because `source-file` alone does not start a server ("no server running").+- A create or respawn with no variables keeps today's command line exactly.+- `source-file -` is tmux 3.1. `create` with variables already needs 3.2. A respawn with variables needed 3.0;+ it now needs 3.1 and is refused by name below it (`respawnRefusal`), never sent with the value in argv.+- The `-P` pane id prints from inside `source-file`. A server that `start-server` just started prints its+ `~/.tmux.conf` errors to the client after it, so `create` reads the first line only.+- From `source-file`, tmux does not give the options chained after `new-session` to the new session, as it does+ on a command line: they went to another session's pane (found in review). On this path each option names the+ new session exactly (`-t =NAME:`), so a create with variables needs a name without `:` or `.`; every caller+ gives one, and one without is refused.++Not changed: the engine's own command line (the launch script carries what it needs), and `clearEnv`, which+sends names only.++## Tests (each fails on main)++- Unit, fake tmux: a create and a respawn with a token send no value in any argument; the value arrives on+ stdin and parses back to the same `-e` words. Tricky values round-trip through the quoting.+- Unit: a respawn with variables on tmux 3.0 is refused and asks tmux nothing.+- Real tmux, private server: a create with a token, on a machine with no server running, leaves the token in+ no process's command line (`ps -axww`), and the session's environment has the exact value. A respawn the same.++## Design++- growth: N/A because nothing is stored; the input pipe closes with the call.+- concurrency: N/A because each call is one tmux client, as before.+- read cost: N/A because no reads are added.+- scale: N/A; one extra pipe write per create or respawn that has variables.+- compatibility: tmux 3.1 or newer for a respawn with variables (was 3.0); refused by name below.+- migration + rollback: none; a server started before this keeps its title until it restarts, so the Mac+ Studio's Team tmux server needs one restart, and its token should be rotated.+- audience: N/A; local processes only.+- identity: N/A.+- failure: a tmux error still answers with tmux's first stderr line, as before.+- platforms: macOS and Linux (tmux only).diff --git a/mobile/lib/swarm/swarm_devices_page.dart b/mobile/lib/swarm/swarm_devices_page.dartindex 711a9cb95..02da8feda 100644--- a/mobile/lib/swarm/swarm_devices_page.dart+++ b/mobile/lib/swarm/swarm_devices_page.dart@@ -8,6 +8,7 @@ import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/theme/app_theme.dart' show AppColors;+import 'swarm_machine_menu.dart';import 'swarm_machines.dart';import 'swarm_row.dart';import 'swarm_session.dart';@@ -18,7 +19,8 @@ import 'swarm_style.dart';/// not, from the list Swarm's start screens read ([SwarmComputers]); then/// each Swarm's machines, which its people lend it, with what each can do/// and runs ([SwarmMachinesSection]) — the drawer's until it went slim (Lead,-/// 2026-10-29). Read only. Desktop's Your devices shows the hardware plugged+/// 2026-10-29). Read only, except a machine's long-press menu: Details, and for the person who lent it Pause or+/// Resume new work and Remove from Swarm (Huy, 2026-11-02). Desktop's Your devices shows the hardware plugged/// into computers; the phone has no read of that, so it lists the computers/// (Tony, 2026-10-28).class SwarmDevicesPage extends StatelessWidget {@@ -114,6 +116,9 @@ class SwarmDevicesPage extends StatelessWidget {reader: reader,swarmName: swarms.length > 1 ? swarm.name : null,open: (id) => unawaited(showSwarmMachine(context, reader, id)),+ menu: (id, name) => unawaited(+ showSwarmMachineMenu(context, reader, id, name: name),+ ),),),];diff --git a/mobile/lib/swarm/swarm_machine_menu.dart b/mobile/lib/swarm/swarm_machine_menu.dartnew file mode 100644index 000000000..7ecf6f4c7--- /dev/null+++ b/mobile/lib/swarm/swarm_machine_menu.dart@@ -0,0 +1,370 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_sheet.dart';++import 'swarm_buddy.dart' show swarmCanWrite;+import 'swarm_machines.dart' show showSwarmMachine;+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// What the reader may do to machine [machineId] of a Swarm, as the desktop's machine menu and Details offer it+/// (`desktop/lib/super_tabs/machines.dart` `_canRemove`, `contributor == accountId`): only the person who lent a+/// machine pauses or resumes its new work, and only they, and only where they may write, remove it. The server+/// enforces both again (`machine.pause` OWNER_REQUIRED, `machine.remove` FORBIDDEN), so this only decides what to show.+///+/// Null once the Swarm can no longer be read, or the machine is gone from it: nothing to offer, and an open menu+/// closes. [pause] and [remove] are false for anyone else, and while the machine is being removed.+typedef SwarmMachineRights = ({+ bool pause,+ bool paused,+ bool remove,+ String? removeReason,+});++SwarmMachineRights? swarmMachineRights(SwarmReader reader, String machineId) {+ final snapshot = reader.snapshot;+ if (reader.accessRevoked || snapshot == null) return null;+ final pool = snapshot.pool(machineId);+ final onIt = snapshot.agents.where(+ (a) => snapshot.placeOf(a.machineId) == machineId,+ );+ if (pool == null && onIt.isEmpty) return null;+ final removal = pool?['removal'];+ final removing = removal is Map && removal['state'] == 'cleaning';+ final lent = pool != null && pool['contributorId'] == reader.accountId;+ String? reason;+ for (final agent in onIt) {+ reason ??= snapshot.leadProtectionReason(agent.id);+ }+ return (+ pause: lent && removal == null,+ paused: pool?['paused'] == true,+ remove: lent && swarmCanWrite(reader) && !removing,+ removeReason: reason,+ );+}++const _notReached = 'Could not reach this Swarm. Try again.';++/// Pauses or resumes new work on [machineId]; null once the server kept it and the Swarm is read again, else the+/// sentence to show.+Future<String?> swarmPauseMachine(+ SwarmReader reader,+ String machineId, {+ required bool paused,+}) async {+ if (swarmMachineRights(reader, machineId)?.pause != true) {+ return 'You can’t change this machine.';+ }+ return _send(reader, {+ 'type': 'machine.pause',+ 'machineId': machineId,+ 'paused': paused,+ });+}++Future<String?> _send(SwarmReader reader, Map<String, dynamic> command) async {+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {'operationId': superTabOperationId(), 'command': command},+ );+ } on SuperTabFailure catch (failure) {+ return failure.message;+ } catch (_) {+ // A call lost on the way (a timeout, a socket dropped) is no answer.+ return _notReached;+ }+ await reader.refresh();+ return null;+}++/// Says [error] at the foot of the screen, unless the screen is gone or the Swarm can no longer be read.+void _tell(+ ScaffoldMessengerState? messenger,+ SwarmReader reader,+ String? error,+) {+ if (error == null ||+ messenger == null ||+ !messenger.mounted ||+ reader.accessRevoked) {+ return;+ }+ messenger.showSnackBar(+ SnackBar(key: const ValueKey('swarm-machine-failed'), content: Text(error)),+ );+}++/// The long-press menu of a machine row: Details, then Pause or Resume new work and Remove from Swarm for whoever may.+/// The rows follow the Swarm as it is read; the sheet closes itself once the machine, or the reader's access, is gone.+Future<void> showSwarmMachineMenu(+ BuildContext context,+ SwarmReader reader,+ String machineId, {+ required String name,+}) {+ PhoneSheetRows rows() {+ final rights = swarmMachineRights(reader, machineId);+ return (+ actions: [+ if (rights != null) ...[+ PhoneSheetAction(+ icon: LucideIcons.info300,+ label: 'Details',+ onTap: () =>+ unawaited(showSwarmMachine(context, reader, machineId)),+ ),+ if (rights.pause)+ PhoneSheetAction(+ icon: rights.paused ? LucideIcons.play300 : LucideIcons.pause300,+ label: rights.paused ? 'Resume new work' : 'Pause new work',+ onTap: () => unawaited(+ _pause(context, reader, machineId, paused: !rights.paused),+ ),+ ),+ if (rights.remove)+ PhoneSheetAction(+ icon: LucideIcons.trash2300,+ label: 'Remove from Swarm',+ destructive: true,+ enabled: rights.removeReason == null,+ // The whole sentence is the desktop's line under the row; a sheet row has room for a few words.+ value: rights.removeReason == null+ ? null+ : 'Has a Product Manager',+ onTap: () =>+ unawaited(removeSwarmMachine(context, reader, machineId)),+ ),+ ],+ ],+ sections: const [],+ );+ }++ void closeWhenGone(Route<void> route) {+ void check() {+ if (swarmMachineRights(reader, machineId) != null) return;+ reader.removeListener(check);+ if (route.isActive) route.navigator?.removeRoute(route);+ }++ reader.addListener(check);+ unawaited(+ (route is TransitionRoute<void> ? route.completed : route.popped)+ .whenComplete(() => reader.removeListener(check)),+ );+ }++ return showPhoneSheet(+ context,+ title: name,+ rows: rows,+ rebuildOn: reader,+ onShown: closeWhenGone,+ );+}++Future<void> _pause(+ BuildContext context,+ SwarmReader reader,+ String machineId, {+ required bool paused,+}) async {+ final messenger = ScaffoldMessenger.maybeOf(context);+ final error = await swarmPauseMachine(reader, machineId, paused: paused);+ _tell(messenger, reader, error);+}++/// What taking [machineId] out of the Swarm would do, as the server counts it (`GET …/machines/ID/removal`, the one+/// the desktop's Remove question reads): the agents that stop, the projects whose code is only there, and the Product+/// Manager that blocks it.+class _Preview {+ const _Preview(this.agents, this.soleSourceProjects, this.blockedProject);++ final List<({String name, String project, String? task})> agents;+ final List<String> soleSourceProjects;+ final String? blockedProject;++ static _Preview parse(Object? raw) {+ if (raw is! Map ||+ raw['agents'] is! List ||+ raw['soleSourceProjects'] is! List) {+ throw const FormatException('Invalid machine removal preview');+ }+ String text(Object? value) {+ if (value is String && value.isNotEmpty) return value;+ throw const FormatException('Invalid machine removal preview');+ }++ final blocked = raw['blockedBy'];+ if (blocked != null && blocked is! Map) {+ throw const FormatException('Invalid machine removal preview');+ }+ return _Preview(+ [+ for (final item in raw['agents'] as List)+ if (item is Map)+ (+ name: text(item['name']),+ // A Swarm-wide Buddy has no project: the server sends an empty name, and the agent is listed by its name alone.+ project: item['projectName'] is String+ ? item['projectName'] as String+ : throw const FormatException(+ 'Invalid machine removal preview',+ ),+ task: item['task'] is String ? item['task'] as String : null,+ )+ else+ throw const FormatException('Invalid machine removal preview'),+ ],+ [+ for (final item in raw['soleSourceProjects'] as List)+ if (item is Map)+ text(item['name'])+ else+ throw const FormatException('Invalid machine removal preview'),+ ],+ blocked == null ? null : text((blocked as Map)['projectName']),+ );+ }+}++/// Most names the question lists before "and N more": the dialog does not scroll.+const _listed = 5;++String _warning(_Preview preview) {+ final lines = <String>['The Swarm stops using this machine for new work.'];+ if (preview.agents.isNotEmpty) {+ lines.add('\nThese agents will stop:');+ for (final agent in preview.agents.take(_listed)) {+ lines.add(+ '${agent.name}${agent.project.isEmpty ? '' : ' · ${agent.project}'}'+ '${agent.task == null ? '' : '\nThe open task “${agent.task}” loses its agent.'}',+ );+ }+ if (preview.agents.length > _listed) {+ lines.add('and ${preview.agents.length - _listed} more');+ }+ }+ if (preview.soleSourceProjects.isNotEmpty) {+ lines.add('\nThese projects have code only on this machine:');+ lines.addAll(preview.soleSourceProjects.take(_listed));+ if (preview.soleSourceProjects.length > _listed) {+ lines.add('and ${preview.soleSourceProjects.length - _listed} more');+ }+ }+ lines.add(+ '\nThe Swarm folders on this machine will be deleted, including uncommitted or unpushed work.',+ );+ return lines.join('\n');+}++/// Remove from Swarm: reads what it would do, asks with that, and sends `machine.remove`. Nothing is shown or sent for+/// someone who may not, a machine that changed meanwhile, or a Swarm the reader lost access to while it was asking.+Future<void> removeSwarmMachine(+ BuildContext context,+ SwarmReader reader,+ String machineId,+) async {+ bool allowed() {+ final rights = swarmMachineRights(reader, machineId);+ return rights != null && rights.remove && rights.removeReason == null;+ }++ if (!allowed()) return;+ final messenger = ScaffoldMessenger.maybeOf(context);+ final generation = reader.generation;+ final name =+ reader.snapshot?.pool(machineId)?['name'] as String? ?? 'this machine';+ final _Preview preview;+ try {+ preview = _Preview.parse(+ await reader.request(+ 'GET',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/machines/${Uri.encodeComponent(machineId)}/removal',+ ),+ );+ } on SuperTabFailure catch (failure) {+ _tell(messenger, reader, failure.message);+ return;+ } catch (_) {+ _tell(messenger, reader, 'Could not check this machine.');+ return;+ }+ // An answer asked for under an earlier read of the Swarm may carry what the reader can no longer see.+ if (!context.mounted || reader.generation != generation || !allowed()) return;+ if (preview.blockedProject case final project?) {+ _tell(+ messenger,+ reader,+ 'This machine runs the Product Manager of project $project. Delete the project first.',+ );+ return;+ }+ final confirmed = await confirmPhoneAction(+ context,+ icon: LucideIcons.trash2300,+ title: 'Remove $name from this Swarm?',+ message: _warning(preview),+ confirmLabel: 'Remove from Swarm',+ );+ if (!confirmed ||+ !context.mounted ||+ reader.generation != generation ||+ !allowed()) {+ return;+ }+ _tell(+ messenger,+ reader,+ await _send(reader, {'type': 'machine.remove', 'machineId': machineId}),+ );+}++/// Details' Pause new work / Resume new work, for the person who lent the machine.+class SwarmMachinePauseButton extends StatefulWidget {+ const SwarmMachinePauseButton({+ super.key,+ required this.reader,+ required this.machineId,+ });+ final SwarmReader reader;+ final String machineId;++ @override+ State<SwarmMachinePauseButton> createState() =>+ _SwarmMachinePauseButtonState();+}++class _SwarmMachinePauseButtonState extends State<SwarmMachinePauseButton> {+ bool _busy = false;++ @override+ Widget build(BuildContext context) {+ final rights = swarmMachineRights(widget.reader, widget.machineId);+ if (rights == null || !rights.pause) return const SizedBox.shrink();+ return TextButton(+ key: const ValueKey('swarm-machine-pause'),+ onPressed: _busy+ ? null+ : () async {+ final messenger = ScaffoldMessenger.maybeOf(context);+ setState(() => _busy = true);+ final error = await swarmPauseMachine(+ widget.reader,+ widget.machineId,+ paused: !rights.paused,+ );+ if (!mounted) return;+ setState(() => _busy = false);+ _tell(messenger, widget.reader, error);+ },+ child: Text(rights.paused ? 'Resume new work' : 'Pause new work'),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_machines.dart b/mobile/lib/swarm/swarm_machines.dartindex b4baadd12..04b237c3e 100644--- a/mobile/lib/swarm/swarm_machines.dart+++ b/mobile/lib/swarm/swarm_machines.dart@@ -11,6 +11,7 @@ import '../shared/theme/app_type.dart';import 'identity.dart';import 'model.dart';import 'swarm_buddy.dart';+import 'swarm_machine_menu.dart';import 'swarm_reader.dart';import 'swarm_style.dart';import 'team_glance.dart';@@ -22,12 +23,17 @@ class SwarmMachinesSection extends StatefulWidget {super.key,required this.reader,required this.open,+ this.menu,this.swarmName,});final SwarmReader reader;final String? swarmName;final void Function(String machineId) open;+ /// A long press on a machine: its Details / Pause / Remove menu ([showSwarmMachineMenu]); null leaves the row with+ /// its tap alone.+ final void Function(String machineId, String name)? menu;+@overrideState<SwarmMachinesSection> createState() => _SwarmMachinesSectionState();}@@ -105,6 +111,9 @@ class _SwarmMachinesSectionState extends State<SwarmMachinesSection> {Widget _machineRow(_MachineView view) => _tap(key: ValueKey('swarm-machine-${widget.reader.tabId}-${view.id}'),onTap: () => widget.open(view.id),+ onLongPress: widget.menu == null+ ? null+ : () => widget.menu!(view.id, view.name),child: Row(children: [Icon(@@ -155,21 +164,23 @@ class _SwarmMachinesSectionState extends State<SwarmMachinesSection> {);}-Widget _tap({Key? key, required VoidCallback onTap, required Widget child}) =>- Material(- color: Colors.transparent,- child: InkWell(- key: key,- onTap: onTap,- child: ConstrainedBox(- constraints: const BoxConstraints(minHeight: 52),- child: Padding(- padding: const EdgeInsets.all(AppSpace.s),- child: child,- ),- ),- ),- );+Widget _tap({+ Key? key,+ required VoidCallback onTap,+ VoidCallback? onLongPress,+ required Widget child,+}) => Material(+ color: Colors.transparent,+ child: InkWell(+ key: key,+ onTap: onTap,+ onLongPress: onLongPress,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 52),+ child: Padding(padding: const EdgeInsets.all(AppSpace.s), child: child),+ ),+ ),+);/// A read-only sheet that keeps following the same reader as the drawer.Future<void> showSwarmMachine(@@ -301,6 +312,7 @@ class SwarmMachineSheet extends StatelessWidget {a.name,'${snapshot.roleOf(a.agent.id)?.badge ?? 'Dev'} · ${a.label}',),+ SwarmMachinePauseButton(reader: reader, machineId: machineId),],),),diff --git a/mobile/test/swarm/swarm_machines_test.dart b/mobile/test/swarm/swarm_machines_test.dartindex c84a508ba..4ae33aa3b 100644--- a/mobile/test/swarm/swarm_machines_test.dart+++ b/mobile/test/swarm/swarm_machines_test.dart@@ -1,9 +1,12 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/notify/system_notices.dart';import 'package:harness_mobile/settings/experimental_features.dart';import 'package:harness_mobile/swarm/swarm_devices_page.dart';+import 'package:harness_mobile/swarm/swarm_machine_menu.dart';import 'package:harness_mobile/swarm/swarm_machines.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';@@ -63,6 +66,8 @@ void main() {WidgetTester tester, {List<Map<String, dynamic>>? machines,List<Map<String, dynamic>>? agents,+ String role = 'owner',+ void Function(FakeSwarm fake)? routes,}) async {tester.view.physicalSize = const Size(1170, 2532);tester.view.devicePixelRatio = 3;@@ -77,9 +82,12 @@ void main() {final rows = machines ?? [machinePool('mac-1', 'Tony’s Mac')];fake.routes['/api/super-tabs/$tab/parts'] = (_) => {...firstLoad(agents: agents),+ 'members': [part(me, 1, person(me, role: role))],'machines': [for (final m in rows) part(m['machineId'] as String, 1, m)],};fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {'result': {}};+ routes?.call(fake);final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())..value = {PhoneExperiment.swarm};final account = ValueNotifier<String?>(me);@@ -119,7 +127,7 @@ void main() {);testWidgets(- 'tap shows capacity, allowance reset and running agents, without management',+ 'tap shows capacity, allowance reset and running agents, without Remove or Configure',(tester) async {await open(tester);await tester.tap(key('swarm-machine-$tab-mac-1'));@@ -145,7 +153,8 @@ void main() {),findsOneWidget,);- for (final text in ['Remove', 'Configure', 'Pause']) {+ // Management lives in the long-press menu; Details holds only Pause/Resume, for who lent the machine.+ for (final text in ['Remove', 'Remove from Swarm', 'Configure']) {expect(find.text(text), findsNothing);}},@@ -369,4 +378,373 @@ void main() {findsOneWidget,);});++ group('long-press menu (Huy, 11-02)', () {+ // No Product Manager on the machine, which would hold Remove back.+ final plain = [agent('agent-builder', displayName: 'Nova')];++ Future<void> press(WidgetTester tester, [String id = 'mac-1']) async {+ await tester.longPress(key('swarm-machine-$tab-$id'));+ await tester.pumpAndSettle();+ }++ Map<String, dynamic> preview({+ List<Map<String, dynamic>> agents = const [],+ List<Map<String, dynamic>> projects = const [],+ Map<String, dynamic>? blockedBy,+ }) => {+ 'blockedBy': blockedBy,+ 'agents': agents,+ 'soleSourceProjects': projects,+ };++ int removalReads() => fake.calls+ .where((c) => c.path.endsWith('/machines/mac-1/removal'))+ .length;++ testWidgets(+ 'the person who lent a machine sees Details, Pause and Remove',+ (tester) async {+ await open(tester, agents: plain);+ await press(tester);+ expect(find.text('Details'), findsOneWidget);+ expect(find.text('Pause new work'), findsOneWidget);+ expect(find.text('Remove from Swarm'), findsOneWidget);+ expect(find.byType(SwarmMachineSheet), findsNothing);+ },+ );++ testWidgets(+ 'a machine that runs a Product Manager holds Remove back, and says so briefly',+ (tester) async {+ await open(tester);+ await press(tester);+ expect(find.text('Has a Product Manager'), findsOneWidget);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(fake.calls.where((c) => c.path.endsWith('/removal')), isEmpty);+ expect(fake.commands, isEmpty);+ expect(find.text('Pause new work'), findsOneWidget);+ },+ );++ testWidgets('someone else’s machine offers Details alone', (tester) async {+ await open(+ tester,+ agents: plain,+ machines: [machinePool('mac-1', 'Dee’s Mac', owner: 'person-dee')],+ );+ await press(tester);+ expect(find.text('Details'), findsOneWidget);+ expect(find.text('Pause new work'), findsNothing);+ expect(find.text('Remove from Swarm'), findsNothing);+ await tester.tap(find.text('Details'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmMachineSheet), findsOneWidget);+ expect(key('swarm-machine-pause'), findsNothing);+ });++ testWidgets(+ 'a reader who may not write cannot remove, but still pauses their own',+ (tester) async {+ await open(tester, agents: plain, role: 'viewer');+ await press(tester);+ expect(find.text('Pause new work'), findsOneWidget);+ expect(find.text('Remove from Swarm'), findsNothing);+ },+ );++ testWidgets('a machine being removed offers neither Pause nor Remove', (+ tester,+ ) async {+ await open(+ tester,+ agents: plain,+ machines: [+ {+ ...machinePool('mac-1', 'Tony’s Mac'),+ 'removal': {'state': 'cleaning'},+ },+ ],+ );+ await press(tester);+ expect(find.text('Details'), findsOneWidget);+ expect(find.text('Pause new work'), findsNothing);+ expect(find.text('Remove from Swarm'), findsNothing);+ });++ testWidgets(+ 'Pause new work sends machine.pause; a paused machine offers Resume',+ (tester) async {+ await open(tester, agents: plain);+ await press(tester);+ await tester.tap(find.text('Pause new work'));+ await tester.pumpAndSettle();+ expect(fake.commands, [+ {'type': 'machine.pause', 'machineId': 'mac-1', 'paused': true},+ ]);+ await tester.pumpWidget(const SizedBox());+ await open(+ tester,+ machines: [+ {...machinePool('mac-1', 'Tony’s Mac'), 'paused': true},+ ],+ );+ await press(tester);+ expect(find.text('Resume new work'), findsOneWidget);+ await tester.tap(find.text('Resume new work'));+ await tester.pumpAndSettle();+ expect(fake.commands.last['paused'], isFalse);+ },+ );++ testWidgets(+ 'Details carries Pause/Resume for the lender and sends the same command',+ (tester) async {+ await open(tester, agents: plain);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ await tester.dragUntilVisible(+ key('swarm-machine-pause'),+ find.byType(SingleChildScrollView).last,+ const Offset(0, -200),+ );+ await tester.tap(key('swarm-machine-pause'));+ await tester.pumpAndSettle();+ expect(fake.commands, [+ {'type': 'machine.pause', 'machineId': 'mac-1', 'paused': true},+ ]);+ },+ );++ testWidgets('a refused pause says why and changes nothing', (tester) async {+ await open(+ tester,+ agents: plain,+ routes: (f) => f.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw SuperTabFailure(+ 'OWNER_REQUIRED',+ 'Only its contributor can change this machine.',+ statusCode: 403,+ ),+ );+ await press(tester);+ await tester.tap(find.text('Pause new work'));+ await tester.pumpAndSettle();+ expect(+ find.text('Only its contributor can change this machine.'),+ findsOneWidget,+ );+ });++ testWidgets(+ 'Remove asks with what stops and is deleted, then sends machine.remove',+ (tester) async {+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ preview(+ agents: [+ {+ 'name': 'Nova',+ 'projectName': 'Mobile',+ 'task': 'Fix sync',+ },+ ],+ projects: [+ {'name': 'Beacon'},+ ],+ ),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(find.text('Remove Tony’s Mac from this Swarm?'), findsOneWidget);+ expect(find.textContaining('Nova · Mobile'), findsOneWidget);+ expect(+ find.textContaining('“Fix sync” loses its agent'),+ findsOneWidget,+ );+ expect(find.textContaining('Beacon'), findsOneWidget);+ expect(+ find.textContaining('Swarm folders on this machine will be deleted'),+ findsOneWidget,+ );+ expect(fake.commands, isEmpty);+ await tester.tap(+ find.widgetWithText(FilledButton, 'Remove from Swarm'),+ );+ await tester.pumpAndSettle();+ expect(fake.commands, [+ {'type': 'machine.remove', 'machineId': 'mac-1'},+ ]);+ },+ );++ testWidgets(+ 'a Buddy with no project is listed by its name alone, and Remove still works',+ (tester) async {+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ preview(+ agents: [+ {'name': 'Wren', 'projectName': ''},+ ],+ ),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(find.textContaining('from this Swarm?'), findsOneWidget);+ expect(find.text('Could not check this machine.'), findsNothing);+ expect(find.textContaining('Wren'), findsOneWidget);+ expect(find.textContaining('Wren ·'), findsNothing);+ await tester.tap(+ find.widgetWithText(FilledButton, 'Remove from Swarm'),+ );+ await tester.pumpAndSettle();+ expect(fake.commands, [+ {'type': 'machine.remove', 'machineId': 'mac-1'},+ ]);+ },+ );++ testWidgets('cancelling the question sends nothing', (tester) async {+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ preview(),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);+ });++ testWidgets(+ 'a Product Manager on the machine blocks it, with no question',+ (tester) async {+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ preview(+ blockedBy: {'projectId': project, 'projectName': 'Mobile'},+ ),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(find.textContaining('Delete the project first'), findsOneWidget);+ expect(+ find.textContaining('Remove Tony’s Mac from this Swarm?'),+ findsNothing,+ );+ expect(fake.commands, isEmpty);+ },+ );++ testWidgets(+ 'a failed read of what would happen shows no question and sends nothing, and retries later',+ (tester) async {+ var fail = true;+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ fail ? throw StateError('socket') : preview(),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(find.text('Could not check this machine.'), findsOneWidget);+ expect(find.textContaining('from this Swarm?'), findsNothing);+ expect(fake.commands, isEmpty);+ fail = false;+ await tester.pump(const Duration(seconds: 5));+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(find.textContaining('from this Swarm?'), findsOneWidget);+ expect(removalReads(), 2);+ },+ );++ testWidgets(+ 'access ending while the question is being read shows and sends nothing',+ (tester) async {+ final gate = Completer<Map<String, dynamic>>();+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ gate.future,+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pump();+ host.session!.inbox.reader(tab)!.revoke();+ gate.complete(preview());+ await tester.pumpAndSettle();+ expect(find.textContaining('from this Swarm?'), findsNothing);+ expect(fake.commands, isEmpty);+ },+ );++ testWidgets('access ending while the question is open sends nothing', (+ tester,+ ) async {+ await open(+ tester,+ agents: plain,+ routes: (f) =>+ f.routes['/api/super-tabs/$tab/machines/mac-1/removal'] = (_) =>+ preview(),+ );+ await press(tester);+ await tester.tap(find.text('Remove from Swarm'));+ await tester.pumpAndSettle();+ host.session!.inbox.reader(tab)!.revoke();+ await tester.pump();+ await tester.tap(find.widgetWithText(FilledButton, 'Remove from Swarm'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);+ });++ testWidgets('the menu closes when access ends under it', (tester) async {+ await open(tester, agents: plain);+ await press(tester);+ expect(find.text('Pause new work'), findsOneWidget);+ // The sheet's title beside the row's own name.+ expect(find.text('Tony’s Mac'), findsNWidgets(2));+ host.session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();+ expect(find.text('Pause new work'), findsNothing);+ expect(find.text('Details'), findsNothing);+ // The sheet itself is gone, not just emptied.+ expect(find.text('Tony’s Mac'), findsNothing);+ });++ testWidgets(+ 'a machine lost from the Swarm closes its menu, and an id from elsewhere offers nothing',+ (tester) async {+ await open(tester, agents: plain);+ final reader = host.session!.inbox.reader(tab)!;+ expect(swarmMachineRights(reader, 'someone-elses-machine'), isNull);+ expect(swarmMachineRights(reader, 'mac-1'), isNotNull);+ },+ );+ });}